| 1: | <?php |
| 2: | declare(strict_types=1); |
| 3: | |
| 4: | namespace om; |
| 5: | |
| 6: | use ArrayObject; |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | |
| 13: | |
| 14: | |
| 15: | |
| 16: | |
| 17: | class EventsList extends ArrayObject { |
| 18: | |
| 19: | |
| 20: | |
| 21: | public function getArrayCopy(): array { |
| 22: | return array_values(parent::getArrayCopy()); |
| 23: | } |
| 24: | |
| 25: | |
| 26: | |
| 27: | |
| 28: | public function sorted(): EventsList { |
| 29: | return $this->sortByStart(true); |
| 30: | } |
| 31: | |
| 32: | |
| 33: | |
| 34: | |
| 35: | public function reversed(): EventsList { |
| 36: | return $this->sortByStart(false); |
| 37: | } |
| 38: | |
| 39: | |
| 40: | |
| 41: | |
| 42: | private function sortByStart(bool $ascending): EventsList { |
| 43: | $events = parent::getArrayCopy(); |
| 44: | $timestamps = []; |
| 45: | $undated = []; |
| 46: | foreach ($events as $key => $event) { |
| 47: | $start = $event['DTSTART'] ?? null; |
| 48: | if ($start === null) { |
| 49: | $undated[] = $key; |
| 50: | } else { |
| 51: | $timestamps[$key] = $this->dtTimestamp($start); |
| 52: | } |
| 53: | } |
| 54: | $ascending ? asort($timestamps, SORT_NUMERIC) : arsort($timestamps, SORT_NUMERIC); |
| 55: | |
| 56: | $sorted = []; |
| 57: | foreach ([...array_keys($timestamps), ...$undated] as $key) { |
| 58: | $sorted[$key] = $events[$key]; |
| 59: | } |
| 60: | $this->exchangeArray($sorted); |
| 61: | return $this; |
| 62: | } |
| 63: | |
| 64: | |
| 65: | |
| 66: | |
| 67: | private function dtTimestamp(mixed $value): int { |
| 68: | if ($value instanceof \DateTimeInterface) { |
| 69: | return $value->getTimestamp(); |
| 70: | } |
| 71: | if (is_int($value) || is_float($value) || is_numeric($value)) { |
| 72: | return (int) $value; |
| 73: | } |
| 74: | $ts = strtotime((string) $value); |
| 75: | return $ts === false ? 0 : $ts; |
| 76: | } |
| 77: | |
| 78: | } |
| 79: | |