db->prepare( 'SELECT * FROM %i WHERE `id` = %d LIMIT 1', $this->table( 'service_categories' ), $id ); $row = $this->db->get_row( $sql, ARRAY_A ); return is_array( $row ) ? $this->hydrate( $row ) : null; } /** * Find by uuid. * * {@inheritDoc} * * @param Uuid $uuid Parameter. * @since 0.1.0 */ public function find_by_uuid( Uuid $uuid ): ?ServiceCategory { $sql = $this->db->prepare( 'SELECT * FROM %i WHERE `uuid` = %s LIMIT 1', $this->table( 'service_categories' ), $uuid->to_string() ); $row = $this->db->get_row( $sql, ARRAY_A ); return is_array( $row ) ? $this->hydrate( $row ) : null; } /** * Save. * * {@inheritDoc} * * @param ServiceCategory $category Parameter. * @since 0.1.0 */ public function save( ServiceCategory $category ): void { $data = [ 'uuid' => $category->uuid()->to_string(), 'parent_id' => $category->parent_id(), 'name' => $category->name(), 'slug' => $category->slug(), 'description' => $category->description(), 'image_id' => $category->image_id(), 'sort_order' => $category->sort_order(), 'created_at' => $this->format_datetime( $category->created_at() ), 'updated_at' => $this->format_datetime( $category->updated_at() ), ]; if ( null === $category->id() ) { $this->db->insert( $this->table( 'service_categories' ), $data ); $category->assign_id( $this->last_insert_id() ); return; } $this->db->update( $this->table( 'service_categories' ), $data, [ 'id' => $category->id() ] ); } /** * Active categories. * * {@inheritDoc} * * @param int $limit Max rows. * @param int $offset Offset. * @return list * * @since 0.1.0 */ public function find_active( int $limit = 100, int $offset = 0 ): array { $sql = $this->db->prepare( 'SELECT * FROM %i ORDER BY `sort_order` ASC, `id` ASC LIMIT %d OFFSET %d', $this->table( 'service_categories' ), max( 1, min( 100, $limit ) ), max( 0, $offset ) ); $rows = $this->db->get_results( $sql, ARRAY_A ); if ( ! is_array( $rows ) ) { return []; } $out = []; foreach ( $rows as $row ) { if ( is_array( $row ) ) { $out[] = $this->hydrate( $row ); } } return $out; } /** * Map a database row to an entity. * * @param array $row Database row. */ private function hydrate( array $row ): ServiceCategory { return new ServiceCategory( (int) $row['id'], new Uuid( (string) $row['uuid'] ), null !== $row['parent_id'] ? (int) $row['parent_id'] : null, (string) $row['name'], (string) $row['slug'], null !== $row['description'] ? (string) $row['description'] : null, null !== $row['image_id'] ? (int) $row['image_id'] : null, (int) $row['sort_order'], $this->parse_datetime( (string) $row['created_at'] ), $this->parse_datetime( (string) $row['updated_at'] ), ); } }