Completed
Push — master ( 8f94c7...cf704a )
by Dmitry
44:25 queued 29:23
created

PhoneValidator   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 1
dl 0
loc 28
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
A replaceParams() 0 9 2
1
<?php
2
3
namespace hiapi\validators;
4
5
use yii\validators\RegularExpressionValidator;
6
7
/**
8
 * Class PhoneValidator
9
 *
10
 * @author Dmytro Naumenko <[email protected]>
11
 */
12
class PhoneValidator extends RegularExpressionValidator
13
{
14
    public function __construct($config = [])
15
    {
16
        $this->pattern = $this->replaceParams(
17
            '/^\+?({part1})? ?(?(?=\()(\({part2}\) ?{part3})|([. -]?({part2}[. -]*)?{part3}))$/',
18
            [
19
                'part1' => '\d{0,3}',
20
                'part2' => '\d{1,3}',
21
                'part3' => '((\d{3,5})[. -]?(\d{4})|(\d{2}[. -]?){4})',
22
            ]
23
        );
24
25
        parent::__construct($config);
26
27
        $this->message = '{attribute} must be a valid phone number';
28
    }
29
30
    private function replaceParams($format, array $params)
31
    {
32
        $string = $format;
33
        foreach ($params as $name => $value) {
34
            $string = str_replace('{'.$name.'}', $value, $string);
35
        }
36
37
        return $string;
38
    }
39
}
40