File size: 1,822 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php

namespace Mautic\CoreBundle\Helper;

use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

class PhoneNumberHelper
{
    /**
     * @param int $format
     *
     * @return string
     */
    public function format($number, $format = PhoneNumberFormat::E164)
    {
        $phoneUtil   = PhoneNumberUtil::getInstance();
        $phoneNumber = $phoneUtil->parse($number, 'US');

        return $phoneUtil->format($phoneNumber, $format);
    }

    public function getFormattedNumberList($number): array
    {
        return array_unique(
            [
                $number,
                $this->format($number, PhoneNumberFormat::E164),
                $this->formatNumericalNational($number),
                $this->format($number, PhoneNumberFormat::NATIONAL),
                $this->formatDelimitedNational($number),
                $this->format($number, PhoneNumberFormat::INTERNATIONAL),
                $this->formatNumericalInternational($number),
                $this->formatDelimitedNational($number, '.'),
            ]
        );
    }

    public function formatNumericalInternational($number): ?string
    {
        return preg_replace('/[^0-9]/', '', $this->format($number, PhoneNumberFormat::INTERNATIONAL));
    }

    public function formatNumericalNational($number): ?string
    {
        return preg_replace('/[^0-9]/', '', $this->format($number, PhoneNumberFormat::NATIONAL));
    }

    /**
     * @param string $number
     * @param string $delimiter
     */
    public function formatDelimitedNational($number, $delimiter = '-'): ?string
    {
        $national = $this->format($number, PhoneNumberFormat::NATIONAL);
        $national = str_replace([') ', '-'], $delimiter, $national);

        return preg_replace('/[^0-9'.$delimiter.']/', '', $national);
    }
}