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