Validator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 1
cbo 0
dl 0
loc 70
ccs 11
cts 11
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 8 2
A __construct() 0 10 2
1
<?php
2
3
namespace VasilDakov\Postcode;
4
5
/**
6
 * Class Validator
7
 * @author Vasil Dakov <[email protected]>
8
 */
9
class Validator implements ValidatorInterface
10
{
11
    private $code;
12
13
    /**
14
     * Two-letter country codes defined in ISO 3166-1
15
     *
16
     * @var array<ISO 3166-1>
17
     */
18
    protected static $codes = [
19
        'BE', 'BG', 'CA', 'DE', 'DK', 'ES', 'FR', 'IT',
20
        'JP', 'MT', 'NL', 'US', 'SE', 'UK', 'US'
21
    ];
22
23
    /**
24
     * Postcode regexes by country code
25
     *
26
     * @var array
27
     */
28
    protected static $regexes = [
29
        'BE' => '[1-9]{1}[0-9]{3}',
30
        'BG' => '\d{4}',
31
        'CA' => '([A-Z]\d[A-Z]\s\d[A-Z]\d)',
32
        'DE' => '\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b',
33
        'DK' => '([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}',
34
        'ES' => '([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}',
35
        'FR' => '(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$',
36
        'IT' => '(V-|I-)?[0-9]{5}',
37
        'JP' => '\d{3}-\d{4}',
38
        'MT' => '([A-Z]{3}\d{2}\d?)',
39
        'NL' => '[1-9][0-9]{3} ?(?!sa|sd|ss)[A-Za-z]{2}',
40
        'SE' => '(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}',
41
        'UK' => '([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})
42
    |(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})',
43
        'US' => 'd{5}\p{Punct}?\s?(?:\d{4})?',
44
    ];
45
46
47
    /**
48
     * Constructor
49
     *
50
     * @param string $code  Country code ISO 3166-1
51
     */
52 3
    public function __construct($code)
53
    {
54 3
        if (!array_key_exists($code, static::$regexes)) {
55 2
            throw new \InvalidArgumentException(
56 2
                "Country code '{$code}' invalid by ISO 3166-1 or not supported"
57 2
            );
58
        }
59
60 1
        $this->code = $code;
61 1
    }
62
63
64
    /**
65
     * Returns true if $value is a valid postcode
66
     *
67
     * @param  string  $value
68
     * @return boolean
69
     */
70 54
    public function isValid($value)
71
    {
72 54
        if (!preg_match('/^' . static::$regexes[$this->code] . '$/', $value)) {
73 8
            return false;
74
        }
75
76 46
        return true;
77
    }
78
}
79