Completed
Pull Request — master (#1982)
by Basil
02:27
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
/**
11
 * Phone Number Validator.
12
 * 
13
 * @author Basil Suter  <[email protected]>
14
 * @since 1.0.25
15
 */
16
class PhoneNumberValidator extends Validator
17
{
18
    public $country;
19
20
    public $autoFormat = true;
21
22
    public $autoFormatFormat = PhoneNumberFormat::E164;
23
24
    public function validateAttribute($model, $attribute)
25
    {
26
        $phoneUtil = PhoneNumberUtil::getInstance();
27
28
        $value = $model->{$attribute};
29
30
        try {
31
            $number = $phoneUtil->parse($value, $this->country);
32
33
            if (!$phoneUtil->isValidNumber($number)) {
34
                return $this->addError($model, $attribute, 'The given number is invalid.');
35
            }
36
37
            // refactor the phone number
38
            if ($number && $this->autoFormat) {
39
                $model->{$attribute} = $phoneUtil->format($number, $this->autoFormatFormat);
40
            }
41
42
        } catch (NumberParseException $exception) {
43
            $this->addError($model, $attribute, 'Invalid Phone Number, ensure the correct country code is available.');
44
        }
45
    }
46
}