1
|
|
|
<?php |
2
|
|
|
namespace MetaHydrator\Parser; |
3
|
|
|
|
4
|
|
|
use MetaHydrator\Exception\ParsingException; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* An implementation of ParserInterface used to reconstruct DateTime objects from a string |
8
|
|
|
*/ |
9
|
|
|
class DateTimeParser extends AbstractParser |
10
|
|
|
{ |
11
|
|
|
/** @var null|string */ |
12
|
|
|
private $format; |
13
|
|
|
public function getFormat() { return $this->format; } |
14
|
|
|
public function setFormat(string $format) { $this->format = $format; } |
15
|
|
|
|
16
|
|
|
/** @var bool */ |
17
|
|
|
private $ignoreWarnings; |
18
|
|
|
public function getIgnoreWarnings() { return $this->ignoreWarnings; } |
19
|
|
|
public function setIgnoreWarnings(bool $ignoreWarnings) { $this->ignoreWarnings = $ignoreWarnings; } |
20
|
|
|
|
21
|
|
|
/** @var bool */ |
22
|
|
|
private $immutable; |
23
|
|
|
public function getImmutable() { return $this->immutable; } |
24
|
|
|
public function setImmutable(bool $immutable) { $this->immutable = $immutable; } |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* DateTimeParser constructor. |
28
|
|
|
* @param string|null $format |
29
|
|
|
* @param bool $ignoreWarnings |
30
|
|
|
* @param string $errorMessage |
31
|
|
|
*/ |
32
|
|
|
public function __construct(string $format = null, bool $ignoreWarnings = false, string $errorMessage = "", bool $immutable = false) |
33
|
|
|
{ |
34
|
|
|
parent::__construct($errorMessage); |
35
|
|
|
$this->format = $format; |
36
|
|
|
$this->ignoreWarnings = $ignoreWarnings; |
37
|
|
|
$this->immutable = $immutable; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param mixed $rawValue |
42
|
|
|
* @return \DateTime |
43
|
|
|
* @throws ParsingException |
44
|
|
|
*/ |
45
|
|
|
public function parse($rawValue) |
46
|
|
|
{ |
47
|
|
|
if ($rawValue === null || $rawValue === '') { |
48
|
|
|
return null; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if ($this->format) { |
|
|
|
|
52
|
|
|
$date = \DateTime::createFromFormat($this->format, $rawValue); |
53
|
|
|
} else { |
54
|
|
|
$date = new \DateTime($rawValue); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$errors = \DateTime::getLastErrors(); |
58
|
|
|
if ($errors['error_count'] > 0) { |
59
|
|
|
$this->throw(); |
60
|
|
|
} |
61
|
|
|
if (!$this->ignoreWarnings && $errors['warning_count'] > 0) { |
62
|
|
|
$this->throw(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if ($this->immutable) { |
66
|
|
|
$date = \DateTimeImmutable::createFromMutable($date); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $date; |
|
|
|
|
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: