Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
14 / 14 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
DateTime | |
100.00% |
14 / 14 |
|
100.00% |
3 / 3 |
7 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
filter | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
safeCreateDateTimeZone | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
4 |
1 | <?php |
2 | |
3 | namespace Verja\Filter; |
4 | |
5 | use Verja\Filter; |
6 | use Verja\Gate; |
7 | use Verja\Validator\DateTime as DateTimeValidator; |
8 | |
9 | class DateTime extends Filter |
10 | { |
11 | /** @var string */ |
12 | protected $format; |
13 | |
14 | /** @var bool */ |
15 | protected $strict; |
16 | |
17 | /** @var \DateTimeZone */ |
18 | protected $timeZone; |
19 | |
20 | /** |
21 | * DateTime constructor. |
22 | * |
23 | * @param string|\DateTimeZone|int $timeZone |
24 | * @param string $format |
25 | * @param bool $strict |
26 | */ |
27 | public function __construct($timeZone = null, string $format = null, bool $strict = false) |
28 | { |
29 | $this->format = $format; |
30 | $this->strict = $strict; |
31 | $this->timeZone = self::safeCreateDateTimeZone($timeZone); |
32 | } |
33 | |
34 | /** |
35 | * Filter $value |
36 | * |
37 | * @param mixed $value |
38 | * @param array $context |
39 | * @return mixed |
40 | */ |
41 | public function filter($value, array $context = []) |
42 | { |
43 | Gate::assert(new DateTimeValidator($this->format, $this->strict), $value); |
44 | |
45 | return empty($this->format) ? new \DateTime($value, $this->timeZone) : |
46 | \DateTime::createFromFormat($this->format, $value, $this->timeZone); |
47 | } |
48 | |
49 | /** |
50 | * Creates a DateTimeZone from a string, DateTimeZone or integer offset. |
51 | * |
52 | * @param \DateTimeZone|string|int|null $object |
53 | * |
54 | * @throws \InvalidArgumentException |
55 | * |
56 | * @return \DateTimeZone |
57 | */ |
58 | protected static function safeCreateDateTimeZone($object) |
59 | { |
60 | if ($object === null) { |
61 | return new \DateTimeZone(date_default_timezone_get()); |
62 | } |
63 | |
64 | if ($object instanceof \DateTimeZone) { |
65 | return $object; |
66 | } |
67 | |
68 | $tz = @timezone_open((string) $object); |
69 | |
70 | if ($tz === false) { |
71 | throw new \InvalidArgumentException('Unknown or bad timezone ('.$object.')'); |
72 | } |
73 | |
74 | return $tz; |
75 | } |
76 | } |