Completed
Pull Request — master (#1982)
by Basil
02:09
created

PhoneNumberValidator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 49
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
 * Validates a given phone number, and converts into standardized format by default. See {{PhoneNumberValidator::$autoFormat}}
14
 * 
15
 * @see https://github.com/giggsey/libphonenumber-for-php This library is used to parse, format and validate.
16
 * @author Basil Suter  <[email protected]>
17
 * @since 1.0.25
18
 */
19
class PhoneNumberValidator extends Validator
20
{
21
    /**
22
     * @var string If a phone number does not contain the country prefix (+41 f.e), define a default country format which then defines the 
23
     * country prefix.
24
     * 
25
     * ```php
26
     * 'country' => 'CH',
27
     * ```
28
     */
29
    public $country;
30
31
    /**
32
     * @var boolean Whether the phone number value should be standardized with formating function and write back to the model. This is usefull
33
     * in order to have all phone numbers save in the correct format in the database.
34
     */
35
    public $autoFormat = true;
36
37
    /**
38
     * @var string The format which should be taken to auto format the phone number value.
39
     */
40
    public $autoFormatFormat = PhoneNumberFormat::E164;
41
42
    /**
43
     * {@inheritDoc}
44
     */
45
    public function validateAttribute($model, $attribute)
46
    {
47
        $phoneUtil = PhoneNumberUtil::getInstance();
48
49
        $value = $model->{$attribute};
50
51
        try {
52
            $number = $phoneUtil->parse($value, $this->country);
53
54
            if (!$phoneUtil->isValidNumber($number)) {
55
                return $this->addError($model, $attribute, 'The given number is invalid.');
56
            }
57
58
            // refactor the phone number
59
            if ($number && $this->autoFormat) {
60
                $model->{$attribute} = $phoneUtil->format($number, $this->autoFormatFormat);
61
            }
62
63
        } catch (NumberParseException $exception) {
64
            $this->addError($model, $attribute, 'Invalid Phone Number, ensure the correct country code is available.');
65
        }
66
    }
67
}