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