Passed
Pull Request — master (#14)
by Rimas
02:08
created

Phone::buildPattern()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 8
c 0
b 0
f 0
rs 10
cc 2
nc 2
nop 1
1
<?php
2
namespace Dokobit\Gateway\Validator\Constraints;
3
4
use Symfony\Component\Validator\Constraints\Regex;
5
6
/**
7
 * Class Phone
8
 * @package DokobitApiBundle
9
 */
10
class Phone extends Regex
11
{
12
    /**
13
     * Base validation pattern which includes + char only,
14
     * all other parts are built on the fly
15
     */
16
    const VALIDATION_PATTERN = '/^\+(%s)$/';
17
18
    /**
19
     * @var string
20
     */
21
    public $message = 'Phone number format is not valid';
22
23
    /**
24
     * @param mixed $options
25
     * @return self
26
     */
27
    public function __construct($options = null)
28
    {
29
        $options['pattern'] = sprintf(
30
            self::VALIDATION_PATTERN,
31
            $this->buildPattern($this->getCountryPatterns())
32
        );
33
        parent::__construct($options);
34
    }
35
36
    /**
37
     * Build one regexp pattern from given list of patterns
38
     * @param array $patterns
39
     * @return string built regexp
40
     */
41
    private function buildPattern(array $patterns)
42
    {
43
        $parts = [];
44
        foreach ($patterns as $pattern) {
45
            $parts[] = sprintf('(%s)', $pattern);
46
        }
47
48
        return implode('|', $parts);
49
    }
50
51
    /**
52
     * Regexp patterns by country
53
     * IMPORTANT!
54
     * DO NOT FORGET TO UPDATE REGULAR EXPRESSION VALIDATOR IN JAVASCRIPT!
55
     * @return array
56
     */
57
    private function getCountryPatterns()
58
    {
59
        return [
60
            'lt' => '3706\d{7}',
61
            'ee' => '372\d{7,8}',
62
            'fi' => '358(4[0-9]{1}|467|50)\d{4,8}',
63
        ];
64
    }
65
}
66