Passed
Pull Request — master (#1)
by
unknown
01:48
created

DateTimeZone::filter()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 5
nop 2
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
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 \InvalidArgumentException Thrown if $allowNull was not a boolean value.
21
     * @throws FilterException if the value did not pass validation.
22
     */
23
    public static function filter($value, bool $allowNull = false)
24
    {
25
        if (self::valueIsNullAndValid($allowNull, $value)) {
26
            return null;
27
        }
28
29
        if ($value instanceof \DateTimeZone) {
30
            return $value;
31
        }
32
33
        if (!is_string($value) || trim($value) == '') {
34
            throw new FilterException('$value not a non-empty string');
35
        }
36
37
        try {
38
            return new \DateTimeZone($value);
39
        } catch (\Exception $e) {
40
            throw new FilterException($e->getMessage(), $e->getCode(), $e);
41
        }
42
    }
43
44
    private static function valueIsNullAndValid(bool $allowNull, $value = null) : bool
45
    {
46
        if ($allowNull === false && $value === null) {
47
            throw new FilterException('Value failed filtering, $allowNull is set to false');
48
        }
49
        return $allowNull === true && $value === null;
50
    }
51
}
52