1: <?php
2: declare(strict_types=1);
3:
4: namespace om;
5:
6: use ArrayObject;
7: use DateInterval;
8: use DateTime;
9: use DateTimeInterface;
10: use DateTimeZone;
11: use Exception;
12: use InvalidArgumentException;
13: use om\ICal\ContentLine;
14: use om\ICal\Value\Duration;
15: use om\RRule\RecurrenceSet;
16: use om\RRule\Rule;
17: use RuntimeException;
18:
19: /**
20: * iCalendar (RFC 5545) parser producing PHP arrays.
21: *
22: * Copyright (c) Roman Ožana (https://ozana.cz)
23: *
24: * @license BSD-3-Clause
25: * @author Roman Ožana <roman@ozana.cz>
26: *
27: * @deprecated 5.0, removed in 5.5 at the latest; use om\ICal::parse() or om\ICal::parser(), see UPGRADING.md
28: */
29: class IcalParser {
30: private const array DATE_PROPERTIES = ['DTSTAMP' => true, 'LAST-MODIFIED' => true, 'CREATED' => true, 'DTSTART' => true, 'DTEND' => true, 'DUE' => true, 'COMPLETED' => true];
31: private const array MULTIPLE_KEYS = ['ATTACH' => 'ATTACHMENTS', 'EXDATE' => 'EXDATES', 'RDATE' => 'RDATES', 'ATTENDEE' => 'ATTENDEES'];
32: private const array COMMA_SEPARATED_KEYS = ['X-CATEGORIES' => 'X-CATEGORIES', 'CATEGORIES' => 'CATEGORIES'];
33: private const array META_KEYS = ['DTSTART' => true, 'RRULE' => true, 'EXDATE' => true, 'RECURRENCE-ID' => true];
34:
35: /** Properties of the TEXT value type (RFC 5545, section 3.3.11) that are unescaped. */
36: private const array TEXT_PROPERTIES = [
37: 'CALSCALE' => true, 'METHOD' => true, 'PRODID' => true, 'VERSION' => true, 'CATEGORIES' => true,
38: 'CLASS' => true, 'COMMENT' => true, 'DESCRIPTION' => true, 'LOCATION' => true, 'RESOURCES' => true,
39: 'STATUS' => true, 'SUMMARY' => true, 'TRANSP' => true, 'TZID' => true, 'TZNAME' => true, 'CONTACT' => true,
40: 'RELATED-TO' => true, 'UID' => true, 'ACTION' => true, 'REQUEST-STATUS' => true, 'URL' => true,
41: ];
42:
43: private const array TEXT_ESCAPES = ['\\\\' => '\\', '\\N' => "\n", '\\n' => "\n", '\\;' => ';', '\\,' => ','];
44:
45: /** Timezone of floating dates: the last X-WR-TIMEZONE or TZID property seen. */
46: public ?DateTimeZone $timezone = null;
47: /** @var array<string, mixed>|null */
48: public ?array $data = null;
49: /** @var array<string, int> */
50: protected array $counters = [];
51:
52: private readonly ParserOptions $options;
53: private readonly TimezoneResolver $timezones;
54:
55: /**
56: * Parser details of components that are not part of the public data:
57: * date-only flags, raw RRULE and RECURRENCE-ID timezone.
58: *
59: * @var array<string, array<int, array<string, mixed>>>
60: */
61: private array $meta = [];
62:
63: /**
64: * Overridden instances (VEVENT with RECURRENCE-ID) by UID and RANGE, TZID and RECURRENCE-ID,
65: * with the counter of the current revision.
66: *
67: * @var array<string, array<string, array{value: string, timezone: ?DateTimeZone, counter: int}>>
68: */
69: private array $overrides = [];
70:
71: public function __construct(?ParserOptions $options = null) {
72: $this->options = $options ?? new ParserOptions();
73: $this->timezones = new TimezoneResolver($this->options->windowsTimezones ?? []);
74: }
75:
76: /**
77: * Parse a file or any stream wrapper URL.
78: *
79: * @throws RuntimeException when the file cannot be read
80: * @throws InvalidArgumentException when the content is not iCalendar data
81: */
82: /**
83: * @return array<string, mixed>|null
84: */
85: public function parseFile(string $file, ?callable $callback = null): ?array {
86: // the content is passed as a temporary value, so parseString() can free it while normalizing
87: return $this->parseString(self::readFile($file), $callback);
88: }
89:
90: private static function readFile(string $file): string {
91: $content = @file_get_contents($file);
92: if ($content === false) {
93: throw new RuntimeException(sprintf('Cannot read iCalendar file "%s".', $file));
94: }
95: return $content;
96: }
97:
98: /**
99: * Parse iCalendar data.
100: *
101: * With a callback, rows are not stored; the callback receives every property row as
102: * ($row, $key, $middle, $value, $section, $counter) and the method returns null.
103: *
104: * @param bool $add if true the parsed string is added to existing data
105: * @return array<string, mixed>|null
106: * @throws InvalidArgumentException when the content is not iCalendar data
107: */
108: public function parseString(string $string, ?callable $callback = null, bool $add = false): ?array {
109: if (stripos($string, 'BEGIN:VCALENDAR') === false) {
110: throw new InvalidArgumentException('Invalid ICAL data format');
111: }
112:
113: if ($add === false || $this->data === null) {
114: $this->data = [];
115: $this->counters = [];
116: $this->meta = [];
117: $this->overrides = [];
118: $this->timezone = null;
119: }
120:
121: // Normalize line breaks and unfold lines (RFC 5545, section 3.1). Each replacement
122: // copies the whole string, so rare patterns are replaced only when present.
123: $string = str_replace("\r\n", "\n", $string);
124: if (str_contains($string, "\r")) {
125: $string = str_replace("\r", "\n", $string);
126: }
127: $string = str_replace("\n ", '', $string);
128: if (str_contains($string, "\n\t")) {
129: $string = str_replace("\n\t", '', $string);
130: }
131: if (str_starts_with($string, "\u{FEFF}")) {
132: $string = substr($string, 3);
133: }
134:
135: $section = 'VCALENDAR';
136: $parents = [];
137:
138: foreach (explode("\n", $string) as $row) {
139: if ($row === '') {
140: continue;
141: }
142:
143: if (strncasecmp($row, 'BEGIN:', 6) === 0) {
144: $component = strtoupper(trim(substr($row, 6)));
145: if ($component !== 'VCALENDAR') {
146: $parents[] = $section;
147: $section = $component;
148: $this->counters[$section] = isset($this->counters[$section]) ? $this->counters[$section] + 1 : 0;
149: if ($callback === null) {
150: $this->data[$section][$this->counters[$section]] = [];
151: }
152: }
153: continue;
154: }
155:
156: if (strncasecmp($row, 'END:', 4) === 0) {
157: $component = strtoupper(trim(substr($row, 4)));
158: if ($component !== 'VCALENDAR') {
159: if ($component === 'VEVENT' && $callback === null && isset($this->data['VEVENT'][$this->counters['VEVENT'] ?? -1]['RECURRENCE-ID'])) {
160: $this->registerOverride($this->counters['VEVENT']);
161: }
162: $section = array_pop($parents) ?? 'VCALENDAR';
163: }
164: continue;
165: }
166:
167: $row = $this->parseRow($row);
168: if ($row === null) {
169: continue;
170: }
171: [$key, $middle, $value, $raw, $line] = $row;
172:
173: if ($callback) {
174: $callback($line, $key, $middle, $value, $section, $this->counters[$section] ?? 0);
175: } elseif ($section === 'VCALENDAR') {
176: $this->data[$key] = $value;
177: } else {
178: $this->store($section, $this->counters[$section], $key, $middle, $value, $raw);
179: }
180: }
181:
182: if ($callback) {
183: return null;
184: }
185:
186: $this->expandRecurringEvents();
187: return $this->data;
188: }
189:
190: /**
191: * Expand the recurrence set of an event (RRULE, RDATE and EXDATE) into DateTime objects.
192: *
193: * @param array<string, mixed> $event parsed VEVENT
194: * @return list<DateTime>
195: * @throws InvalidArgumentException for an invalid RRULE in strict mode
196: */
197: public function parseRecurrences(array $event): array {
198: // details such as a date-only UNTIL or EXDATE are known for events of the parsed data
199: $counter = array_search($event, $this->data['VEVENT'] ?? [], true);
200: return $this->recurrences($event, $counter === false ? [] : $this->meta['VEVENT'][$counter] ?? []);
201: }
202:
203: public function isMultipleKey(string $key): ?string {
204: return self::MULTIPLE_KEYS[$key] ?? null;
205: }
206:
207: public function isMultipleKeyWithCommaSeparation(string $key): ?string {
208: return self::COMMA_SEPARATED_KEYS[$key] ?? null;
209: }
210:
211: /**
212: * @return array<int, array<string, mixed>>
213: */
214: public function getAlarms(): array {
215: return $this->data['VALARM'] ?? [];
216: }
217:
218: /**
219: * @return array<int, array<string, mixed>>
220: */
221: public function getTimezone(): array {
222: return $this->getTimezones();
223: }
224:
225: /**
226: * @return array<int, array<string, mixed>>
227: */
228: public function getTimezones(): array {
229: return $this->data['VTIMEZONE'] ?? [];
230: }
231:
232: /**
233: * @return array<int, array<string, mixed>>
234: */
235: public function getTodos(): array {
236: return array_values($this->data['VTODO'] ?? []);
237: }
238:
239: /**
240: * @return array<int, array<string, mixed>>
241: */
242: public function getJournals(): array {
243: return array_values($this->data['VJOURNAL'] ?? []);
244: }
245:
246: /**
247: * Return sorted event list as ArrayObject
248: *
249: * @deprecated use IcalParser::getEvents()->sorted() instead
250: * @return ArrayObject<int, array<string, mixed>>
251: */
252: public function getSortedEvents(): ArrayObject {
253: return $this->getEvents()->sorted();
254: }
255:
256: /**
257: * @deprecated use IcalParser::getEvents()->reversed() instead
258: * @return ArrayObject<int, array<string, mixed>>
259: */
260: public function getReverseSortedEvents(): ArrayObject {
261: return $this->getEvents()->reversed();
262: }
263:
264: /**
265: * Events with recurring events expanded into single instances.
266: *
267: * Every instance has DTEND: from DTEND, from DURATION, or one day for all-day
268: * events (RFC 5545, section 3.6.1). Recurring instances also carry RECURRING
269: * and RECURRENCE_INSTANCE (zero based). Of several revisions of an overridden
270: * instance (same UID and RECURRENCE-ID), only the one with the highest SEQUENCE is returned.
271: */
272: public function getEvents(): EventsList {
273: $events = new EventsList();
274: foreach ($this->data['VEVENT'] ?? [] as $counter => $event) {
275: if (isset($this->meta['VEVENT'][$counter]['superseded'])) {
276: continue; // an older revision of an override
277: }
278: $start = $event['DTSTART'] ?? null;
279: if (!isset($event['RECURRENCES']) || !$start instanceof DateTimeInterface) {
280: if (!array_key_exists('DTEND', $event) && $start instanceof DateTimeInterface
281: && ($duration = $this->duration($event, $this->meta['VEVENT'][$counter] ?? [])) !== null) {
282: $end = DateTime::createFromInterface($start);
283: $event['DTEND'] = $end->add($duration);
284: }
285: $events->append($event);
286: continue;
287: }
288:
289: $event['RECURRING'] = true;
290: $duration = $this->duration($event, $this->meta['VEVENT'][$counter] ?? []) ?? new DateInterval('PT0S');
291: $template = $event;
292: unset($template['RECURRENCES']);
293: foreach ($event['RECURRENCES'] as $index => $date) {
294: if (!$date instanceof DateTime) {
295: continue;
296: }
297: $instance = $index === 0 ? $event : $template;
298: $instance['DTSTART'] = clone $date;
299: $instance['DTEND'] = (clone $date)->add($duration);
300: $instance['RECURRENCE_INSTANCE'] = $index;
301: $events->append($instance);
302: }
303: }
304: return $events;
305: }
306:
307: /**
308: * Store a property of a component in the public data array.
309: */
310: private function store(string $section, int $counter, string $key, mixed $middle, mixed $value, string $raw): void {
311: $this->data ??= [];
312:
313: // Multiple entries are collected in an array under a separate key,
314: // the original key keeps the last value.
315: if ($newKey = self::MULTIPLE_KEYS[$key] ?? null) {
316: $this->data[$section][$counter][$newKey][] = $value;
317: }
318:
319: if (isset(self::COMMA_SEPARATED_KEYS[$key])) {
320: // split on commas not preceded by backslash, then unescape
321: foreach (preg_split('/(?<!\\\\),/', $raw) ?: [] as $item) {
322: $this->data[$section][$counter][$key][] = trim(strtr($item, self::TEXT_ESCAPES));
323: }
324: return;
325: }
326:
327: if ($key === 'ORGANIZER') {
328: foreach (is_array($middle) ? $middle : [] as $midKey => $midVal) {
329: $this->data[$section][$counter][$key . '-' . $midKey] = $midVal;
330: }
331: }
332: if ($key === 'ATTENDEE' || $key === 'ORGANIZER') {
333: $value = $value['VALUE']; // backwards compatibility (leaves ATTENDEE entry as it was)
334: }
335: $this->data[$section][$counter][$key] = $value;
336:
337: if (isset(self::META_KEYS[$key])) {
338: $this->storeMeta($section, $counter, $key, $middle, $raw);
339: }
340: }
341:
342: /**
343: * Remember parser details that the public data cannot express.
344: * Only values other than the defaults are stored, to keep large calendars small.
345: */
346: private function storeMeta(string $section, int $counter, string $key, mixed $middle, string $raw): void {
347: $params = is_array($middle) ? $middle : [];
348: $dateOnly = ($params['VALUE'] ?? null) === 'DATE';
349: switch ($key) {
350: case 'DTSTART':
351: if ($dateOnly || (strlen($raw) === 8 && ctype_digit($raw))) {
352: $this->meta[$section][$counter]['dateOnly'] = true;
353: } else {
354: unset($this->meta[$section][$counter]['dateOnly']);
355: }
356: break;
357: case 'RRULE':
358: $this->meta[$section][$counter]['rrule'] = $raw;
359: break;
360: case 'EXDATE':
361: foreach (explode(',', $raw) as $item) {
362: $item = trim($item);
363: if ($dateOnly || preg_match('/^\d{8}$/D', $item)) {
364: $this->meta[$section][$counter]['exdateDays'][] = substr($item, 0, 8);
365: }
366: }
367: break;
368: case 'RECURRENCE-ID':
369: if (($params['TZID'] ?? null) instanceof DateTimeZone) {
370: $this->meta[$section][$counter]['recurrenceIdTimezone'] = $params['TZID'];
371: }
372: if (is_string($params['RANGE'] ?? null) && strtoupper($params['RANGE']) === 'THISANDFUTURE') {
373: $this->meta[$section][$counter]['thisAndFuture'] = true;
374: }
375: break;
376: }
377: }
378:
379: private function registerOverride(int $counter): void {
380: $event = $this->data['VEVENT'][$counter] ?? [];
381: if (!isset($event['RECURRENCE-ID'], $event['UID']) || !is_string($event['RECURRENCE-ID'])) {
382: return;
383: }
384: $meta = $this->meta['VEVENT'][$counter] ?? [];
385: $timezone = $meta['recurrenceIdTimezone'] ?? null;
386:
387: // of several revisions of one instance, the one with the highest SEQUENCE (RFC 5545, section 3.8.7.4)
388: // is kept, the later one when they are equal; unlike the new API, the RECURRENCE-ID is compared as written
389: $key = (empty($meta['thisAndFuture']) ? '' : 'range ') . $timezone?->getName() . ':' . $event['RECURRENCE-ID'];
390: $previous = $this->overrides[$event['UID']][$key]['counter'] ?? null;
391: if ($previous !== null) {
392: $loser = self::sequence($event) >= self::sequence($this->data['VEVENT'][$previous] ?? []) ? $previous : $counter;
393: $this->meta['VEVENT'][$loser]['superseded'] = true;
394: if ($loser === $counter) {
395: return;
396: }
397: }
398: $this->data['_RECURRENCE_IDS'][$event['UID']][$event['RECURRENCE-ID']] = $event;
399: $this->overrides[$event['UID']][$key] = ['value' => $event['RECURRENCE-ID'], 'timezone' => $timezone, 'counter' => $counter];
400: }
401:
402: /**
403: * SEQUENCE of a component, 0 when missing or invalid (as in the new API).
404: *
405: * @param array<string, mixed> $event
406: */
407: private static function sequence(array $event): int {
408: $value = is_string($event['SEQUENCE'] ?? null) ? trim($event['SEQUENCE']) : '';
409: return preg_match('/^[+-]?\d{1,18}$/D', $value) ? (int) $value : 0;
410: }
411:
412: private function expandRecurringEvents(): void {
413: foreach ($this->data['VEVENT'] ?? [] as $counter => $event) {
414: if (empty($event['RRULE']) && empty($event['RDATE']) && empty($event['EXDATE'])) {
415: continue;
416: }
417: if (!($event['DTSTART'] ?? null) instanceof DateTimeInterface) {
418: continue;
419: }
420: $this->data['VEVENT'][$counter]['RECURRENCES'] = $this->recurrences($event, $this->meta['VEVENT'][$counter] ?? []);
421: if (!empty($event['UID'])) {
422: $this->data['_RECURRENCE_COUNTERS_BY_UID'][$event['UID']] = $counter;
423: }
424: }
425: }
426:
427: /**
428: * @param array<string, mixed> $event
429: * @param array<string, mixed> $meta
430: * @return list<DateTime>
431: */
432: private function recurrences(array $event, array $meta): array {
433: $start = $event['DTSTART'] ?? null;
434: if (!$start instanceof DateTimeInterface) {
435: throw new InvalidArgumentException('A recurring event requires a valid DTSTART.');
436: }
437: $start = DateTime::createFromInterface($start);
438: $timezone = $start->getTimezone();
439:
440: $rule = null;
441: if (!empty($event['RRULE'])) {
442: try {
443: $rule = isset($meta['rrule']) ? Rule::fromString($meta['rrule'], true) : Rule::fromArray($event['RRULE'], true);
444: $rule->assertGregorian(); // another calendar system (RFC 7529) is not expanded
445: } catch (InvalidArgumentException $e) {
446: if ($this->options->strict) {
447: throw $e;
448: }
449: $rule = null;
450: }
451: }
452:
453: // Rules without an end are expanded until the horizon, optionally skipping old occurrences
454: $until = $from = null;
455: if ($rule !== null && $rule->count === null && $rule->until === null) {
456: $now = $this->options->now();
457: $until = ($this->options->untilInterval ? $now->add($this->options->untilInterval) : $now)->getTimestamp();
458: if ($this->options->shiftEventDates) {
459: $from = $now->sub($this->options->shiftEventDates)->getTimestamp();
460: }
461: }
462:
463: $set = new RecurrenceSet(
464: $start,
465: $rule,
466: rdates: self::timestamps($event['RDATES'] ?? []),
467: exdates: self::timestamps($event['EXDATES'] ?? []),
468: exdays: $meta['exdateDays'] ?? [],
469: until: $until,
470: from: $from,
471: limit: $this->options->maxOccurrences,
472: strict: $this->options->strict,
473: );
474: [$overriddenTimestamps, $overriddenDays] = $this->overriddenInstances($event['UID'] ?? null, $timezone);
475:
476: $recurrences = [];
477: foreach ($set as $timestamp) {
478: if (isset($overriddenTimestamps[$timestamp])) {
479: continue;
480: }
481: $date = (clone $start)->setTimestamp($timestamp);
482: if ($overriddenDays !== [] && isset($overriddenDays[$date->format('Ymd')])) {
483: continue;
484: }
485: $recurrences[] = $date;
486: }
487: return $recurrences;
488: }
489:
490: /**
491: * Instances replaced by a VEVENT with the same UID and a RECURRENCE-ID.
492: *
493: * @return array{array<int, true>, array<string, true>} timestamps, and days of date-only IDs
494: */
495: private function overriddenInstances(?string $uid, DateTimeZone $timezone): array {
496: $timestamps = $days = [];
497: foreach ($this->overrides[$uid ?? ''] ?? [] as ['value' => $value, 'timezone' => $idTimezone]) {
498: $value = trim($value);
499: if (preg_match('/^\d{8}$/D', $value)) {
500: $days[$value] = true;
501: continue;
502: }
503: try {
504: $timestamps[(new DateTime($value, $idTimezone ?? $timezone))->getTimestamp()] = true;
505: } catch (Exception) {
506: // invalid RECURRENCE-ID matches nothing
507: }
508: }
509: return [$timestamps, $days];
510: }
511:
512: /**
513: * @param array<string, mixed> $event
514: * @param array<string, mixed> $meta
515: */
516: private function duration(array $event, array $meta): ?DateInterval {
517: if (($event['DTEND'] ?? null) instanceof DateTimeInterface) {
518: return $event['DTSTART']->diff($event['DTEND']);
519: }
520: if (is_string($event['DURATION'] ?? null) && ($duration = self::parseDuration($event['DURATION'])) !== null) {
521: return $duration;
522: }
523: return !empty($meta['dateOnly']) ? new DateInterval('P1D') : null;
524: }
525:
526: /**
527: * Parse a DURATION value (RFC 5545, section 3.3.6), e.g. "PT1H30M", "-P1W" or "P1DT12H".
528: */
529: public static function parseDuration(string $value): ?DateInterval {
530: return Duration::parse($value);
531: }
532:
533: /**
534: * @param array<mixed> $dates EXDATES or RDATES: dates and lists of dates
535: * @return list<int>
536: */
537: private static function timestamps(array $dates): array {
538: $result = [];
539: foreach ($dates as $date) {
540: foreach (is_array($date) ? $date : [$date] as $single) {
541: if ($single instanceof DateTimeInterface) {
542: $result[] = $single->getTimestamp();
543: }
544: }
545: }
546: return $result;
547: }
548:
549: /**
550: * Parse one content line (RFC 5545, section 3.1) into its name, parameters and value.
551: *
552: * @return array{string, mixed, mixed, string, string}|null [key, middle, value, raw value, line]
553: */
554: private function parseRow(string $row): ?array {
555: $line = ContentLine::split($row);
556: if ($line === null) {
557: return null;
558: }
559: [$key, $middle, $raw] = $line;
560: $value = $raw;
561: $timezone = null;
562:
563: if ($key === 'X-WR-TIMEZONE' || $key === 'TZID') {
564: $resolved = $this->timezones->resolve($value);
565: if ($resolved !== null) {
566: $value = $resolved->getName();
567: $this->timezone = $resolved;
568: }
569: }
570:
571: if ($middle !== '' && ($params = ContentLine::parameters($middle)) !== []) {
572: $middle = [];
573: foreach ($params as $name => $paramValue) {
574: if ($name === 'TZID') {
575: $resolved = $this->timezones->resolve($paramValue);
576: $middle[$name] = $resolved ?? $paramValue;
577: $timezone = $resolved;
578: } elseif ($name === 'ENCODING') {
579: if (strtoupper($paramValue) === 'QUOTED-PRINTABLE') {
580: $value = $raw = quoted_printable_decode($value);
581: }
582: } else {
583: $middle[$name] = $paramValue;
584: }
585: }
586: }
587:
588: if (isset(self::DATE_PROPERTIES[$key])) {
589: $value = self::createDate($value, $timezone ?? $this->timezone);
590: } elseif ($key === 'EXDATE' || $key === 'RDATE') {
591: $values = [];
592: foreach (explode(',', $value) as $singleValue) {
593: // a PERIOD value (start/end or start/duration) is represented by its start
594: $singleValue = strstr($singleValue, '/', true) ?: $singleValue;
595: if (($date = self::createDate($singleValue, $timezone ?? $this->timezone)) !== null) {
596: $values[] = $date;
597: }
598: }
599: $value = count($values) === 1 ? $values[0] : $values;
600: } elseif ($key === 'RRULE' && preg_match_all('#(?<key>[^=;]+)=(?<value>[^;]+)#', $value, $matches, PREG_SET_ORDER)) {
601: $middle = null;
602: $value = [];
603: foreach ($matches as $match) {
604: if ($match['key'] === 'UNTIL') {
605: $value[$match['key']] = self::createDate($match['value'], $timezone ?? $this->timezone) ?? $match['value'];
606: } else {
607: $value[$match['key']] = $match['value'];
608: }
609: }
610: } elseif (isset(self::TEXT_PROPERTIES[$key]) || str_starts_with($key, 'X-')) {
611: // 3.3.11 Text ESCAPED-CHAR
612: $value = strtr($value, self::TEXT_ESCAPES);
613: }
614:
615: if ($key === 'ATTENDEE' || $key === 'ORGANIZER') {
616: $value = array_merge(is_array($middle) ? $middle : ['middle' => $middle], ['VALUE' => $value]);
617: }
618:
619: return [$key, $middle, $value, $raw, $row];
620: }
621:
622: private static function createDate(string $value, ?DateTimeZone $timezone): ?DateTime {
623: try {
624: // Fast path for UTC values like 20240105T100000Z: resolving the "Z" abbreviation
625: // is slow, so the date is read in UTC and the shared "Z" timezone is attached.
626: if (strlen($value) === 16 && $value[15] === 'Z' && $value[8] === 'T') {
627: static $utc, $zulu;
628: $utc ??= new DateTimeZone('UTC');
629: $zulu ??= (new DateTime('20000101T000000Z'))->getTimezone();
630: return (new DateTime(substr($value, 0, 15), $utc))->setTimezone($zulu);
631: }
632: return new DateTime($value, $timezone);
633: } catch (Exception) {
634: return null;
635: }
636: }
637: }
638: