DateTimeZone::valueIsNullAndValid()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 3
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
namespace TraderInteractive\Filter;
4
5
use TraderInteractive\Exceptions\FilterException;
6
7
/**
8
 * A collection of filters for filtering strings into \DateTimeZone objects.
9
 */
10
class DateTimeZone
11
{
12
    /**
13
     * Filters the given value into a \DateTimeZone object.
14
     *
15
     * @param mixed   $value     The value to be filtered.
16
     * @param boolean $allowNull True to allow nulls through, and false (default) if nulls should not be allowed.
17
     *
18
     * @return \DateTimeZone|null
19
     *
20
     * @throws FilterException if the value did not pass validation.
21
     */
22
    public static function filter($value, bool $allowNull = false)
23
    {
24
        if (self::valueIsNullAndValid($allowNull, $value)) {
25
            return null;
26
        }
27
28
        if ($value instanceof \DateTimeZone) {
29
            return $value;
30
        }
31
32
        if (!is_string($value) || trim($value) == '') {
33
            throw new FilterException('$value not a non-empty string');
34
        }
35
36
        try {
37
            return new \DateTimeZone($value);
38
        } catch (\Exception $e) {
39
            throw new FilterException($e->getMessage(), $e->getCode(), $e);
40
        }
41
    }
42
43
    private static function valueIsNullAndValid(bool $allowNull, $value = null) : bool
44
    {
45
        if ($allowNull === false && $value === null) {
46
            throw new FilterException('Value failed filtering, $allowNull is set to false');
47
        }
48
        return $allowNull === true && $value === null;
49
    }
50
}
51