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

PhoneNumberValidator::validateAttribute()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2568
c 0
b 0
f 0
cc 5
nc 7
nop 2
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
}