1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TraderInteractive\Filter; |
4
|
|
|
|
5
|
|
|
use DateTimeInterface; |
6
|
|
|
use DateTimeZone as DateTimeZoneStandard; |
7
|
|
|
use DateTime as DateTimeStandard; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* A collection of filters for filtering strings into \DateTime objects. |
11
|
|
|
*/ |
12
|
|
|
class DateTime |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Filters the given value into a \DateTime object. |
16
|
|
|
* |
17
|
|
|
* @param mixed $value The value to be filtered. |
18
|
|
|
* @param boolean $allowNull True to allow nulls through, and false (default) if nulls should |
19
|
|
|
* not be allowed. |
20
|
|
|
* @param DateTimeZoneStandard $timezone A \DateTimeZone object representing the timezone of $value. |
21
|
|
|
* If $timezone is omitted, the current timezone will be used. |
22
|
|
|
* |
23
|
|
|
* @return DateTimeStandard|null |
24
|
|
|
* |
25
|
|
|
* @throws Exception if the value did not pass validation. |
26
|
|
|
*/ |
27
|
|
|
public static function filter($value, bool $allowNull = false, DateTimeZoneStandard $timezone = null) |
28
|
|
|
{ |
29
|
|
|
if ($value === null && $allowNull) { |
30
|
|
|
return null; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
if ($value instanceof \DateTime) { |
34
|
|
|
return $value; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
if (is_int($value) || ctype_digit($value)) { |
38
|
|
|
$value = "@{$value}"; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (!is_string($value) || trim($value) == '') { |
42
|
|
|
throw new Exception('$value is not a non-empty string'); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return new \DateTime($value, $timezone); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Filters the give \DateTime object to a formatted string. |
50
|
|
|
* |
51
|
|
|
* @param DateTimeInterface $dateTime The date to be formatted. |
52
|
|
|
* @param string $format The format of the outputted date string. |
53
|
|
|
* |
54
|
|
|
* @return string |
55
|
|
|
* |
56
|
|
|
* @throws \InvalidArgumentException Thrown if $format is not a string |
57
|
|
|
*/ |
58
|
|
|
public static function format(DateTimeInterface $dateTime, string $format = 'c') : string |
59
|
|
|
{ |
60
|
|
|
if (!is_string($format) || trim($format) === '') { |
61
|
|
|
throw new \InvalidArgumentException('$format is not a non-empty string'); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $dateTime->format($format); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|