Completed
Pull Request — master (#4)
by Dmitry
15:31 queued 10s
created

PhoneValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 1
nc 1
nop 1
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