DateTimeZone   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 39
rs 10
c 0
b 0
f 0
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A filter() 0 18 6
A valueIsNullAndValid() 0 6 4
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