db->prepare( 'SELECT * FROM %i WHERE `id` = %d LIMIT 1', $this->table( 'service_durations' ), $id ); $row = $this->db->get_row( $sql, ARRAY_A ); return is_array( $row ) ? $this->hydrate( $row ) : null; } /** * Find by service id. * * {@inheritDoc} * * @param int $service_id Parameter. * @since 0.1.0 */ public function find_by_service_id( int $service_id ): array { $sql = $this->db->prepare( 'SELECT * FROM %i WHERE `service_id` = %d ORDER BY `sort_order` ASC, `id` ASC', $this->table( 'service_durations' ), $service_id ); $rows = $this->db->get_results( $sql, ARRAY_A ); if ( ! is_array( $rows ) ) { return []; } $out = []; foreach ( $rows as $row ) { $out[] = $this->hydrate( $row ); } return $out; } /** * Save. * * {@inheritDoc} * * @param ServiceDuration $duration Parameter. * @since 0.1.0 */ public function save( ServiceDuration $duration ): void { $data = [ 'service_id' => $duration->service_id(), 'duration_min' => $duration->duration_min(), 'price_minor' => $duration->price()->amount_minor(), 'currency' => $duration->price()->currency(), 'label' => $duration->label(), 'is_default' => $duration->is_default() ? 1 : 0, 'sort_order' => $duration->sort_order(), ]; if ( null === $duration->id() ) { $this->db->insert( $this->table( 'service_durations' ), $data ); $duration->assign_id( $this->last_insert_id() ); return; } $this->db->update( $this->table( 'service_durations' ), $data, [ 'id' => $duration->id() ] ); } /** * Delete. * * {@inheritDoc} * * @param ServiceDuration $duration Parameter. * @since 0.1.0 */ public function delete( ServiceDuration $duration ): void { if ( null === $duration->id() ) { return; } $this->db->delete( $this->table( 'service_durations' ), [ 'id' => $duration->id() ] ); } /** * Map a database row to an entity. * * @param array $row Database row. */ private function hydrate( array $row ): ServiceDuration { return new ServiceDuration( (int) $row['id'], (int) $row['service_id'], (int) $row['duration_min'], new Money( (int) $row['price_minor'], (string) $row['currency'] ), null !== $row['label'] ? (string) $row['label'] : null, (bool) (int) $row['is_default'], (int) $row['sort_order'], ); } }