| 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 = []; |
| 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($this->entries, function ($entry) use ($date) { |
| 45 |
return $entry->matches_date($date); |
| 46 |
}); |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Get the first date for the date range |
| 51 |
* |
| 52 |
* @param DateTime $date |
| 53 |
* @return Schedule_Entry|null |
| 54 |
*/ |
| 55 |
public function get_first_date(DateTime $date): ?Schedule_Entry { |
| 56 |
if (!is_array($this->entries)) { |
| 57 |
return null; |
| 58 |
} |
| 59 |
$custom_date_entry = null; |
| 60 |
$week_day_entry = null; |
| 61 |
$dow = intval($date->format('N')); |
| 62 |
foreach ($this->entries as $entry) { |
| 63 |
if ($entry->get_custom_date() === $date->format('Y-m-d')) { |
| 64 |
$custom_date_entry = $entry; |
| 65 |
break; |
| 66 |
} elseif (empty($entry->get_custom_date()) && (int)$entry->get_day_of_week() === $dow) { |
| 67 |
$week_day_entry = $entry; |
| 68 |
} |
| 69 |
} |
| 70 |
return $custom_date_entry ?? $week_day_entry; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Get id |
| 75 |
* |
| 76 |
* @return mixed |
| 77 |
*/ |
| 78 |
public function get_id() { |
| 79 |
return $this->id; |
| 80 |
} |
| 81 |
|
| 82 |
/** |
| 83 |
* Get all entries |
| 84 |
* |
| 85 |
* @return Schedule_Entry[] |
| 86 |
*/ |
| 87 |
public function get_entries(): array { |
| 88 |
return $this->entries; |
| 89 |
} |
| 90 |
} |
| 91 |
|