| 1 |
<?php |
| 2 |
declare(strict_types=1); |
| 3 |
|
| 4 |
namespace Booktics\Appointment\Schedule; |
| 5 |
|
| 6 |
use DateTime; |
| 7 |
|
| 8 |
/** |
| 9 |
* Class schedule collection |
| 10 |
*/ |
| 11 |
class Schedule_Collection { |
| 12 |
/** |
| 13 |
* @var mixed |
| 14 |
*/ |
| 15 |
protected $id; |
| 16 |
|
| 17 |
/** |
| 18 |
* Store collection of schedules |
| 19 |
* |
| 20 |
* @var Schedule_Entry[] |
| 21 |
*/ |
| 22 |
private array $entries = array(); |
| 23 |
|
| 24 |
/** |
| 25 |
* Constructor for schedule collections |
| 26 |
* |
| 27 |
* @param array $raw_data |
| 28 |
* @param mixed $id |
| 29 |
*/ |
| 30 |
public function __construct( array $raw_data, $id = null ) { |
| 31 |
$this->id = $id; |
| 32 |
foreach ( $raw_data as $item ) { |
| 33 |
$this->entries[] = new Schedule_Entry( $item ); |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Get collection of date entry for matching date |
| 39 |
* |
| 40 |
* @param DateTime $date |
| 41 |
* @return Schedule_Entry[] |
| 42 |
*/ |
| 43 |
public function get_dates( DateTime $date ): array { |
| 44 |
return array_filter( |
| 45 |
$this->entries, function ( $entry ) use ( $date ) { |
| 46 |
return $entry->matches_date( $date ); |
| 47 |
} |
| 48 |
); |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Get all schedule entries for the date range |
| 53 |
* |
| 54 |
* @param DateTime $date |
| 55 |
* @return array Array of Schedule_Entry objects |
| 56 |
*/ |
| 57 |
public function get_first_date( DateTime $date ): array { |
| 58 |
if ( ! is_array( $this->entries ) ) { |
| 59 |
return array(); |
| 60 |
} |
| 61 |
$custom_date_entries = array(); |
| 62 |
$week_day_entries = array(); |
| 63 |
$dow = intval( $date->format( 'N' ) ); |
| 64 |
|
| 65 |
foreach ( $this->entries as $entry ) { |
| 66 |
if ( $entry->get_custom_date() === $date->format( 'Y-m-d' ) ) { |
| 67 |
$custom_date_entries[] = $entry; |
| 68 |
} elseif ( empty( $entry->get_custom_date() ) && (int) $entry->get_day_of_week() === $dow ) { |
| 69 |
$week_day_entries[] = $entry; |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
// Prioritize custom date entries over regular weekday entries |
| 74 |
return ! empty( $custom_date_entries ) ? $custom_date_entries : $week_day_entries; |
| 75 |
} |
| 76 |
/** |
| 77 |
* Get id |
| 78 |
* |
| 79 |
* @return mixed |
| 80 |
*/ |
| 81 |
public function get_id() { |
| 82 |
return $this->id; |
| 83 |
} |
| 84 |
|
| 85 |
/** |
| 86 |
* Get all entries |
| 87 |
* |
| 88 |
* @return Schedule_Entry[] |
| 89 |
*/ |
| 90 |
public function get_entries(): array { |
| 91 |
return $this->entries; |
| 92 |
} |
| 93 |
} |
| 94 |
|