db->prepare( 'SELECT * FROM %i WHERE `id` = %d LIMIT 1', $this->table( 'schedules' ), $id ); $row = $this->db->get_row( $sql, ARRAY_A ); return is_array( $row ) ? $this->hydrate( $row ) : null; } /** * Find by owner. * * {@inheritDoc} * * @param ScheduleOwnerType $owner_type Parameter. * @param int $owner_id Parameter. * @since 0.1.0 */ public function find_by_owner( ScheduleOwnerType $owner_type, int $owner_id ): array { $sql = $this->db->prepare( 'SELECT * FROM %i WHERE `owner_type` = %s AND `owner_id` = %d ORDER BY `day_of_week` ASC, `start_local` ASC', $this->table( 'schedules' ), $owner_type->value, $owner_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 WeeklySchedule $schedule Parameter. * @since 0.1.0 */ public function save( WeeklySchedule $schedule ): void { $data = [ 'owner_type' => $schedule->owner_type()->value, 'owner_id' => $schedule->owner_id(), 'day_of_week' => $schedule->day_of_week(), 'start_local' => $schedule->start_local(), 'end_local' => $schedule->end_local(), 'valid_from' => null === $schedule->valid_from() ? null : $schedule->valid_from()->format( 'Y-m-d' ), 'valid_until' => null === $schedule->valid_until() ? null : $schedule->valid_until()->format( 'Y-m-d' ), ]; if ( null === $schedule->id() ) { $this->db->insert( $this->table( 'schedules' ), $data ); $schedule->assign_id( $this->last_insert_id() ); return; } $this->db->update( $this->table( 'schedules' ), $data, [ 'id' => $schedule->id() ] ); } /** * Delete. * * {@inheritDoc} * * @param WeeklySchedule $schedule Parameter. * @since 0.1.0 */ public function delete( WeeklySchedule $schedule ): void { if ( null === $schedule->id() ) { return; } $this->db->delete( $this->table( 'schedules' ), [ 'id' => $schedule->id() ] ); } /** * Map a database row to an entity. * * @param array $row Database row. */ private function hydrate( array $row ): WeeklySchedule { $utc = new DateTimeZone( 'UTC' ); return new WeeklySchedule( (int) $row['id'], ScheduleOwnerType::from( (string) $row['owner_type'] ), (int) $row['owner_id'], (int) $row['day_of_week'], (string) $row['start_local'], (string) $row['end_local'], null !== $row['valid_from'] ? new DateTimeImmutable( (string) $row['valid_from'] . ' 00:00:00', $utc ) : null, null !== $row['valid_until'] ? new DateTimeImmutable( (string) $row['valid_until'] . ' 00:00:00', $utc ) : null, ); } }