Completed
Pull Request — master (#1982)
by Basil
08:11
created

PhoneNumberValidator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 31
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A validateAttribute() 0 22 5
1
<?php
2
3
namespace luya\validators;
4
5
use libphonenumber\NumberParseException;
6
use libphonenumber\PhoneNumberFormat;
7
use libphonenumber\PhoneNumberUtil;
8
use yii\validators\Validator;
9
10
class PhoneNumberValidator extends Validator
11
{
12
    public $country;
13
14
    public $autoFormat = true;
15
16
    public $autoFormatFormat = PhoneNumberFormat::E164;
17
18
    public function validateAttribute($model, $attribute)
19
    {
20
        $phoneUtil = PhoneNumberUtil::getInstance();
21
22
        $value = $model->{$attribute};
23
24
        try {
25
            $number = $phoneUtil->parse($value, $this->country);
26
27
            if (!$phoneUtil->isValidNumber($number)) {
28
                return $this->addError($model, $attribute, 'The given number is invalid.');
29
            }
30
31
            // refactor the phone number
32
            if ($number && $this->autoFormat) {
33
                $model->{$attribute} = $phoneUtil->format($number, $this->autoFormatFormat);
34
            }
35
36
        } catch (NumberParseException $exception) {
37
            $this->addError($model, $attribute, 'Invalid Phone Number, ensure the correct country code is available.');
38
        }
39
    }
40
}