Completed
Pull Request — master (#75)
by
unknown
01:26
created

DateTimeZone::filter()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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