Passed
Push — master ( 257e17...004729 )
by Tim
02:49
created

PhoneNumber   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 11
dl 0
loc 26
rs 10
c 1
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A sanitizePhoneNumber() 0 17 4
1
<?php
2
3
/**
4
 * Phone number utilities for SMS-based OTP.
5
 *
6
 * @package tvdijen/simplesamlphp-module-cmdotcom
7
 */
8
9
declare(strict_types=1);
10
11
namespace SimpleSAML\Module\cmdotcom\Utils;
12
13
use libphonenumber\NumberParseException;
14
use libphonenumber\PhoneNumber as Number;
15
use libphonenumber\PhoneNumberFormat;
16
use libphonenumber\PhoneNumberUtil;
17
18
class PhoneNumber
19
{
20
    /**
21
     * Sanitize the mobile phone number for use with the cm.com Rest API
22
     *
23
     * @param string $number
24
     * @return string
25
     * @throws \UnexpectedValueException if the mobile phone number contains illegal characters or is otherwise invalid.
26
     */
27
    public function sanitizePhoneNumber(string $number, $defaultRegion = 'NL'): string
28
    {
29
        $util = PhoneNumberUtil::getInstance();
30
        $region = strpos($number, '+') === false ? $defaultRegion : 'ZZ';
31
        $proto = $util->parse($number, $region);
32
33
        if (
34
            $util->isViablePhoneNumber($number) === false
35
            || $util->isValidNumber($proto) === false
36
        ) {
37
            throw new NumberParseException(
38
                NumberParseException::NOT_A_NUMBER,
39
                "The string supplied did not seem to be a phone number."
40
            );
41
        }
42
43
        return '00' . $proto->getCountryCode() . $proto->getNationalNumber();
44
    }
45
}
46