Completed
Push — master ( 4a10be...f9e60f )
by Chad
8s
created

DateTime::filter()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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