1: <?php declare(strict_types=1);
2:
3: namespace Salient\Core;
4:
5: use Salient\Contract\Core\DateParserInterface;
6: use DateTimeImmutable;
7: use DateTimeZone;
8:
9: /**
10: * Parses date and time strings with a given format
11: *
12: * @api
13: */
14: final class DateFormatParser implements DateParserInterface
15: {
16: private string $Format;
17:
18: /**
19: * Creates a new DateFormatParser object
20: *
21: * @see DateTimeImmutable::createFromFormat()
22: */
23: public function __construct(string $format)
24: {
25: // Reset fields that don't appear in the format string to zero-like
26: // values, otherwise they will be set to the current date and time
27: if (strpos($format, '!') === false && strpos($format, '|') === false) {
28: $format .= '|';
29: }
30:
31: $this->Format = $format;
32: }
33:
34: /**
35: * @inheritDoc
36: */
37: public function parse(string $value, ?DateTimeZone $timezone = null): ?DateTimeImmutable
38: {
39: $date = DateTimeImmutable::createFromFormat($this->Format, $value, $timezone);
40: if ($date === false) {
41: return null;
42: }
43: return $date;
44: }
45: }
46: