Completed
Pull Request — master (#193)
by Joshua
23:22 queued 13:10
created

PhoneNumberMatcher   D

Complexity

Total Complexity 108

Size/Duplication

Total Lines 922
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 93.48%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 108
lcom 1
cbo 10
dl 0
loc 922
ccs 258
cts 276
cp 0.9348
rs 4.4444
c 1
b 0
f 0

24 Methods

Rating   Name   Duplication   Size   Complexity  
B init() 0 88 1
A limit() 0 8 4
A __construct() 0 16 4
B find() 0 24 4
A trimAfterFirstMatch() 0 9 2
A isLatinLetter() 0 10 4
A isInvalidPunctuationSymbol() 0 4 2
B extractMatch() 0 28 5
C extractInnerMatch() 0 30 7
C parseAndVerify() 0 69 18
B allNumberGroupsRemainGrouped() 0 57 9
C allNumberGroupsAreExactlyPresent() 0 37 8
B getNationalNumberGroups() 0 25 3
B checkNumberGroupingIsValid() 0 27 5
B containsMoreThanOneSlashInNationalNumber() 0 30 6
C containsOnlyValidXChars() 0 32 8
C isNationalPrefixPresentIfRequired() 0 41 7
A getAlternateFormatsForCountry() 0 14 3
A loadAlternateFormatsMetadataFromFile() 0 14 2
A current() 0 4 1
A next() 0 13 2
A key() 0 4 1
A valid() 0 4 1
A rewind() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like PhoneNumberMatcher often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PhoneNumberMatcher, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace libphonenumber;
4
5
use libphonenumber\Leniency\AbstractLeniency;
6
7
/**
8
 * A class that finds and extracts telephone numbers from $text.
9
 * Instances can be created using PhoneNumberUtil::findNumbers()
10
 *
11
 * Vanity numbers (phone numbers using alphabetic digits such as '1-800-SIX-FLAGS' are
12
 * not found.
13
 *
14
 * @package libphonenumber
15
 */
16
class PhoneNumberMatcher implements \Iterator
17
{
18
    protected static $initialized = false;
19
20
    /**
21
     * The phone number pattern used by $this->find(), similar to
22
     * PhoneNumberUtil::VALID_PHONE_NUMBER, but with the following differences:
23
     * <ul>
24
     *   <li>All captures are limited in order to place an upper bound to the text matched by the
25
     *       pattern.
26
     * <ul>
27
     *   <li>Leading punctuation / plus signs are limited.
28
     *   <li>Consecutive occurrences of punctuation are limited.
29
     *   <li>Number of digits is limited.
30
     * </ul>
31
     *   <li>No whitespace is allowed at the start or end.
32
     *   <li>No alpha digits (vanity numbers such as 1-800-SIX-FLAGS) are currently supported.
33
     * </ul>
34
     *
35
     * @var string
36
     */
37
    protected static $pattern;
38
39
    /**
40
     * Matches strings that look like publication pages. Example:
41
     * <pre>Computing Complete Answers to Queries in the Presence of Limited Access Patterns.
42
     * Chen Li. VLDB J. 12(3): 211-227 (2003).</pre>
43
     *
44
     * The string "211-227 (2003)" is not a telephone number.
45
     *
46
     * @var string
47
     */
48
    protected static $pubPages = "\\d{1,5}-+\\d{1,5}\\s{0,4}\\(\\d{1,4}";
49
50
    /**
51
     * Matches strings that look like dates using "/" as a separator. Examples 3/10/2011, 31/10/2011 or
52
     * 08/31/95.
53
     *
54
     * @var string
55
     */
56
    protected static $slashSeparatedDates = "(?:(?:[0-3]?\\d/[01]?\\d)|(?:[01]?\\d/[0-3]?\\d))/(?:[12]\\d)?\\d{2}";
57
58
    /**
59
     * Matches timestamps. Examples: "2012-01-02 08:00". Note that the reg-ex does not include the
60
     * trailing ":\d\d" -- that is covered by timeStampsSuffix.
61
     *
62
     * @var string
63
     */
64
    protected static $timeStamps = "[12]\\d{3}[-/]?[01]\\d[-/]?[0-3]\\d +[0-2]\\d$";
65
    protected static $timeStampsSuffix = ":[0-5]\\d";
66
67
    /**
68
     * Pattern to check that brackets match. Opening brackets should be closed within a phone number.
69
     * This also checks that there is something inside the brackets. Having no brackets at all is also
70
     * fine.
71
     *
72
     * @var string
73
     */
74
    protected static $matchingBrackets;
75
76
    /**
77
     * Patterns used to extract phone numbers from a larger phone-number-like pattern. These are
78
     * ordered according to specificity. For example, white-space is last since that is frequently
79
     * used in numbers, not just to separate two numbers. We have separate patterns since we don't
80
     * want to break up the phone-number-like text on more than one different kind of symbol at one
81
     * time, although symbols of the same type (e.g. space) can be safely grouped together.
82
     *
83
     * Note that if there is a match, we will always check any text found up to the first match as
84
     * well.
85
     *
86
     * @var string[]
87
     */
88
    protected static $innerMatches = array();
89
90
    /**
91
     * Punctuation that may be at the start of a phone number - brackets and plus signs.
92
     *
93
     * @var string
94
     */
95
    protected static $leadClass;
96
97
    /**
98
     * Prefix of the files
99
     * @var string
100
     */
101
    protected static $alternateFormatsFilePrefix;
102
    const META_DATA_FILE_PREFIX = 'PhoneNumberAlternateFormats';
103
104 1
    protected static function init()
105
    {
106 1
        static::$alternateFormatsFilePrefix = dirname(__FILE__) . '/data/' . static::META_DATA_FILE_PREFIX;
107
108 1
        static::$innerMatches = array(
109
            // Breaks on the slash - e.g. "651-234-2345/332-445-1234"
110 1
            "/+(.*)",
111
            // Note that the bracket here is inside the capturing group, since we consider it part of the
112
            // phone number. Will match a pattern like "(650) 223 3345 (754) 223 3321".
113
            "(\\([^(]*)",
114
            // Breaks on a hyphen - e.g. "12345 - 332-445-1234 is my number."
115
            // We require a space on either side of the hyphen for it to be considered a separator.
116
            "(?:\\p{Z}-|-\\p{Z})\\p{Z}*(.+)",
117
            // Various types of wide hyphens. Note we have decided not to enforce a space here, since it's
118
            // possible that it's supposed to be used to break two numbers without spaces, and we haven't
119
            // seen many instances of it used within a number.
120
            "[‒-―-]\\p{Z}*(.+)",
121
            // Breaks on a full stop - e.g. "12345. 332-445-1234 is my number."
122
            "\\.+\\p{Z}*([^.]+)",
123
            // Breaks on space - e.g. "3324451234 8002341234"
124
            "\\p{Z}+(\\P{Z}+)"
125
        );
126
127
        /*
128
         * Builds the matchingBrackets and pattern regular expressions. The building blocks exist
129
         * to make the pattern more easily understood.
130
         */
131
132 1
        $openingParens = "(\\[\xEF\xBC\x88\xEF\xBC\xBB";
133 1
        $closingParens = ")\\]\xEF\xBC\x89\xEF\xBC\xBD";
134 1
        $nonParens = "[^" . $openingParens . $closingParens . "]";
135
136
        // Limit on the number of pairs of brackets in a phone number.
137 1
        $bracketPairLimit = static::limit(0, 3);
138
139
        /*
140
         * An opening bracket at the beginning may not be closed, but subsequent ones should be.  It's
141
         * also possible that the leading bracket was dropped, so we shouldn't be surprised if we see a
142
         * closing bracket first. We limit the sets of brackets in a phone number to four.
143
         */
144 1
        static::$matchingBrackets =
145 1
            "(?:[" . $openingParens . "])?" . "(?:" . $nonParens . "+" . "[" . $closingParens . "])?"
146 1
            . $nonParens . "+"
147 1
            . "(?:[" . $openingParens . "]" . $nonParens . "+[" . $closingParens . "])" . $bracketPairLimit
148 1
            . $nonParens . "*";
149
150
        // Limit on the number of leading (plus) characters.
151 1
        $leadLimit = static::limit(0, 2);
152
153
        // Limit on the number of consecutive punctuation characters.
154 1
        $punctuationLimit = static::limit(0, 4);
155
156
        /*
157
         * The maximum number of digits allowed in a digit-separated block. As we allow all digits in a
158
         * single block, set high enough to accommodate the entire national number and the international
159
         * country code
160
         */
161 1
        $digitBlockLimit = PhoneNumberUtil::MAX_LENGTH_FOR_NSN + PhoneNumberUtil::MAX_LENGTH_COUNTRY_CODE;
162
163
        /*
164
         * Limit on the number of blocks separated by the punctuation. Uses digitBlockLimit since some
165
         * formats use spaces to separate each digit
166
         */
167 1
        $blockLimit = static::limit(0, $digitBlockLimit);
168
169
        // A punctuation sequence allowing white space
170 1
        $punctuation = '[' . PhoneNumberUtil::VALID_PUNCTUATION . ']' . $punctuationLimit;
171
172
        // A digits block without punctuation.
173 1
        $digitSequence = "\\p{Nd}" . static::limit(1, $digitBlockLimit);
174
175
176 1
        $leadClassChars = $openingParens . PhoneNumberUtil::PLUS_CHARS;
177 1
        $leadClass = '[' . $leadClassChars . ']';
178 1
        static::$leadClass = $leadClass;
179
180
        // Init extension patterns from PhoneNumberUtil
181 1
        PhoneNumberUtil::initCapturingExtnDigits();
182 1
        PhoneNumberUtil::initExtnPatterns();
183
184
185
        // Phone number pattern allowing optional punctuation.
186 1
        static::$pattern = "(?:" . $leadClass . $punctuation . ")" . $leadLimit
187 1
            . $digitSequence . "(?:" . $punctuation . $digitSequence . ")" . $blockLimit
188 1
            . "(?:" . PhoneNumberUtil::$EXTN_PATTERNS_FOR_MATCHING . ")?";
189
190 1
        static::$initialized = true;
191 1
    }
192
193
    /**
194
     * Helper function to generate regular expression with an upper and lower limit.
195
     *
196
     * @param int $lower
197
     * @param int $upper
198
     * @return string
199
     */
200 1
    protected static function limit($lower, $upper)
201
    {
202 1
        if (($lower < 0) || ($upper <= 0) || ($upper < $lower)) {
203
            throw new \InvalidArgumentException();
204
        }
205
206 1
        return '{' . $lower . ',' . $upper . '}';
207
    }
208
209
    /**
210
     * The phone number utility.
211
     * @var PhoneNumberUtil
212
     */
213
    protected $phoneUtil;
214
215
    /**
216
     * The text searched for phone numbers.
217
     * @var string
218
     */
219
    protected $text;
220
221
    /**
222
     * The region (country) to assume for phone numbers without an international prefix, possibly
223
     * null.
224
     * @var string
225
     */
226
    protected $preferredRegion;
227
228
    /**
229
     * The degrees of validation requested.
230
     * @var AbstractLeniency
231
     */
232
    protected $leniency;
233
234
    /**
235
     * The maximum number of retires after matching an invalid number.
236
     * @var int
237
     */
238
    protected $maxTries;
239
240
    /**
241
     * One of:
242
     *  - NOT_READY
243
     *  - READY
244
     *  - DONE
245
     * @var string
246
     */
247
    protected $state = 'NOT_READY';
248
249
    /**
250
     * The last successful match, null unless $this->state = READY
251
     * @var PhoneNumberMatch
252
     */
253
    protected $lastMatch;
254
255
    /**
256
     * The next index to start searching at. Undefined when $this->state = DONE
257
     * @var int
258
     */
259
    protected $searchIndex = 0;
260
261
    /**
262
     * Creates a new instance. See the factory methods in PhoneNumberUtil on how to obtain a new instance.
263
     *
264
     *
265
     * @param PhoneNumberUtil $util The Phone Number Util to use
266
     * @param string|null $text The text that we will search, null for no text
267
     * @param string|null $country The country to assume for phone numbers not written in international format.
268
     *  (with a leading plus, or with the international dialling prefix of the specified region).
269
     *  May be null, or "ZZ" if only numbers with a leading plus should be considered.
270
     * @param AbstractLeniency $leniency The leniency to use when evaluating candidate phone numbers
271
     * @param int $maxTries The maximum number of invalid numbers to try before giving up on the text.
272
     *  This is to cover degenerate cases where the text has a lot of false positives in it. Must be >= 0
273
     * @throws \NullPointerException
274
     * @throws \InvalidArgumentException
275
     */
276 205
    public function __construct(PhoneNumberUtil $util, $text, $country, AbstractLeniency $leniency, $maxTries)
277
    {
278 205
        if ($maxTries < 0) {
279
            throw new \InvalidArgumentException();
280
        }
281
282 205
        $this->phoneUtil = $util;
283 205
        $this->text = ($text !== null) ? $text : "";
284 205
        $this->preferredRegion = $country;
285 205
        $this->leniency = $leniency;
286 205
        $this->maxTries = $maxTries;
287
288 205
        if (static::$initialized === false) {
289 1
            static::init();
290
        }
291 205
    }
292
293
    /**
294
     * Attempts to find the next subsequence in the searched sequence on or after {@code searchIndex}
295
     * that represents a phone number. Returns the next match, null if none was found.
296
     *
297
     * @param int $index The search index to start searching at
298
     * @return PhoneNumberMatch|null The Phone Number Match found, null if none can be found
299
     */
300 199
    protected function find($index)
301
    {
302 199
        $matcher = new Matcher(static::$pattern, $this->text);
303 199
        while (($this->maxTries > 0) && $matcher->find($index)) {
304 198
            $start = $matcher->start();
305 198
            $cutLength = $matcher->end() - $start;
306 198
            $candidate = mb_substr($this->text, $start, $cutLength);
307
308
            // Check for extra numbers at the end.
309
            // TODO: This is the place to start when trying to support extraction of multiple phone number
310
            // from split notations (+41 49 123 45 67 / 68).
311 198
            $candidate = static::trimAfterFirstMatch(PhoneNumberUtil::$SECOND_NUMBER_START_PATTERN, $candidate);
312
313 198
            $match = $this->extractMatch($candidate, $start);
314 198
            if ($match !== null) {
315 126
                return $match;
316
            }
317
318 90
            $index = $start + mb_strlen($candidate);
319 90
            $this->maxTries--;
320
        }
321
322 93
        return null;
323
    }
324
325
    /**
326
     * Trims away any characters after the first match of $pattern in $candidate,
327
     * returning the trimmed version.
328
     *
329
     * @param string $pattern
330
     * @param string $candidate
331
     * @return string
332
     */
333 198
    protected static function trimAfterFirstMatch($pattern, $candidate)
334
    {
335 198
        $trailingCharsMatcher = new Matcher($pattern, $candidate);
336 198
        if ($trailingCharsMatcher->find()) {
337 10
            $startChar = $trailingCharsMatcher->start();
338 10
            $candidate = mb_substr($candidate, 0, $startChar);
339
        }
340 198
        return $candidate;
341
    }
342
343
    /**
344
     * Helper method to determine if a character is a Latin-script letter or not. For our purposes,
345
     * combining marks should also return true since we assume they have been added to a preceding
346
     * Latin character.
347
     *
348
     * @param string $letter
349
     * @return bool
350
     * @internal
351
     */
352 58
    public static function isLatinLetter($letter)
353
    {
354
        // Combining marks are a subset of non-spacing-mark.
355 58
        if (preg_match('/\p{L}/u', $letter) !== 1 && preg_match('/\p{Mn}/u', $letter) !== 1) {
356 52
            return false;
357
        }
358
359 9
        return (preg_match('/\p{Latin}/u', $letter) === 1)
360 9
        || (preg_match('/\pM+/u', $letter) === 1);
361
    }
362
363
    /**
364
     * @param string $character
365
     * @return bool
366
     */
367 47
    protected static function isInvalidPunctuationSymbol($character)
368
    {
369 47
        return $character == '%' || preg_match('/\p{Sc}/u', $character);
370
    }
371
372
    /**
373
     * Attempts to extract a match from a $candidate.
374
     *
375
     * @param string $candidate The candidate text that might contain a phone number
376
     * @param int $offset The offset of $candidate within $this->text
377
     * @return PhoneNumberMatch|null The match found, null if none can be found
378
     */
379 198
    protected function extractMatch($candidate, $offset)
380
    {
381
        // Skip a match that is more likely to be a date.
382 198
        $dateMatcher = new Matcher(static::$slashSeparatedDates, $candidate);
383 198
        if ($dateMatcher->find()) {
384 33
            return null;
385
        }
386
387
        // Skip potential time-stamps.
388 178
        $timeStampMatcher = new Matcher(static::$timeStamps, $candidate);
389 178
        if ($timeStampMatcher->find()) {
390 20
            $followingText = mb_substr($this->text, $offset + mb_strlen($candidate));
391 20
            $timeStampSuffixMatcher = new Matcher(static::$timeStampsSuffix, $followingText);
392 20
            if ($timeStampSuffixMatcher->lookingAt()) {
393 16
                return null;
394
            }
395
        }
396
397
        // Try to come up with a valid match given the entire candidate.
398 178
        $match = $this->parseAndVerify($candidate, $offset);
399 178
        if ($match !== null) {
400 124
            return $match;
401
        }
402
403
        // If that failed, try to find an "inner match" - there might be a phone number within this
404
        // candidate.
405 74
        return $this->extractInnerMatch($candidate, $offset);
406
    }
407
408
    /**
409
     * Attempts to extract a match from $candidate if the whole candidate does not qualify as a
410
     * match.
411
     *
412
     * @param string $candidate The candidate text that might contact a phone number
413
     * @param int $offset The current offset of $candidate within $this->text
414
     * @return PhoneNumberMatch|null The match found, null if none can be found
415
     */
416 74
    protected function extractInnerMatch($candidate, $offset)
417
    {
418 74
        foreach (static::$innerMatches as $possibleInnerMatch) {
419 74
            $groupMatcher = new Matcher($possibleInnerMatch, $candidate);
420 74
            $isFirstMatch = true;
421
422 74
            while ($groupMatcher->find() && $this->maxTries > 0) {
423 18
                if ($isFirstMatch) {
424
                    // We should handle any group before this one too.
425 18
                    $group = static::trimAfterFirstMatch(PhoneNumberUtil::$UNWANTED_END_CHAR_PATTERN,
426 18
                        mb_substr($candidate, 0, $groupMatcher->start()));
427
428 18
                    $match = $this->parseAndVerify($group, $offset);
429 18
                    if ($match !== null) {
430 6
                        return $match;
431
                    }
432 15
                    $this->maxTries--;
433 15
                    $isFirstMatch = false;
434
                }
435 15
                $group = static::trimAfterFirstMatch(PhoneNumberUtil::$UNWANTED_END_CHAR_PATTERN,
436 15
                    $groupMatcher->group(1));
437 15
                $match = $this->parseAndVerify($group, $offset + $groupMatcher->start(1));
438 15
                if ($match !== null) {
439 7
                    return $match;
440
                }
441 14
                $this->maxTries--;
442
            }
443
        }
444 70
        return null;
445
    }
446
447
    /**
448
     * Parses a phone number from the $candidate} using PhoneNumberUtil::parse() and
449
     * verifies it matches the requested leniency. If parsing and verification succeed, a
450
     * corresponding PhoneNumberMatch is returned, otherwise this method returns null.
451
     *
452
     * @param string $candidate The candidate match
453
     * @param int $offset The offset of $candidate within $this->text
454
     * @return PhoneNumberMatch|null The parsed and validated phone number match, or null
455
     */
456 178
    protected function parseAndVerify($candidate, $offset)
457
    {
458
        try {
459
            // Check the candidate doesn't contain any formatting which would indicate that it really
460
            // isn't a phone number
461 178
            $matchingBracketsMatcher = new Matcher(static::$matchingBrackets, $candidate);
462 178
            $pubPagesMatcher = new Matcher(static::$pubPages, $candidate);
463 178
            if (!$matchingBracketsMatcher->matches() || $pubPagesMatcher->find()) {
464 11
                return null;
465
            }
466
467
            // If leniency is set to VALID or stricter, we also want to skip numbers that are surrounded
468
            // by Latin alphabetic characters, to skip cases like abc8005001234 or 8005001234def.
469 178
            if ($this->leniency->compareTo(Leniency::VALID()) >= 0) {
470
                // If the candidate is not at the start of the text, and does not start with phone-number
471
                // punctuation, check the previous character.
472 135
                $leadClassMatcher = new Matcher(static::$leadClass, $candidate);
473 135
                if ($offset > 0 && !$leadClassMatcher->lookingAt()) {
474 42
                    $previousChar = mb_substr($this->text, $offset - 1, 1);
475
                    // We return null if it is a latin letter or an invalid punctuation symbol.
476 42
                    if (static::isInvalidPunctuationSymbol($previousChar) || static::isLatinLetter($previousChar)) {
477 2
                        return null;
478
                    }
479
                }
480 135
                $lastCharIndex = $offset + mb_strlen($candidate);
481 135
                if ($lastCharIndex < mb_strlen($this->text)) {
482 38
                    $nextChar = mb_substr($this->text, $lastCharIndex, 1);
483 38
                    if (static::isInvalidPunctuationSymbol($nextChar) || static::isLatinLetter($nextChar)) {
484 2
                        return null;
485
                    }
486
                }
487
            }
488
489 177
            $number = $this->phoneUtil->parseAndKeepRawInput($candidate, $this->preferredRegion);
490
491
            // Check Israel * numbers: these are a special case in that they are four-digit numbers that
492
            // our library supports, but they can only be dialled with a leading *. Since we don't
493
            // actually store or detect the * in our phone number library, this means in practice we
494
            // detect most four digit numbers as being valid for Israel. We are considering moving these
495
            // numbers to ShortNumberInfo instead, in which case this problem would go away, but in the
496
            // meantime we want to restrict the false matches so we only allow these numbers if they are
497
            // preceded by a star. We enforce this for all leniency levels even though these numbers are
498
            // technically accepted by isPossibleNumber and isValidNumber since we consider it to be a
499
            // deficiency in those methods that they accept these numbers without the *.
500
            // TODO: Remove this or make it significantly less hacky once we've decided how to
501
            // handle these short codes going forward in ShortNumberInfo. We could use the formatting
502
            // rules for instance, but that would be slower.
503 176
            if ($this->phoneUtil->getRegionCodeForCountryCode($number->getCountryCode()) == "IL"
504 176
                && mb_strlen($this->phoneUtil->getNationalSignificantNumber($number)) === 4
505 176
                && ($offset === 0 || ($offset > 0 && mb_substr($this->text, $offset - 1, 1) != '*'))
506
            ) {
507
                // No match.
508
                return null;
509
            }
510
511 176
            if ($this->leniency->verify($number, $candidate, $this->phoneUtil)) {
512
                // We used parseAndKeepRawInput to create this number, but for now we don't return the extra
513
                // values parsed. TODO: stop clearing all values here and switch all users over
514
                // to using rawInput() rather than the rawString() of PhoneNumberMatch
515 126
                $number->clearCountryCodeSource();
516 126
                $number->clearRawInput();
517 126
                $number->clearPreferredDomesticCarrierCode();
518 176
                return new PhoneNumberMatch($offset, $candidate, $number);
519
            }
520 26
        } catch (NumberParseException $e) {
521
            // ignore and continue
522
        }
523 72
        return null;
524
    }
525
526
    /**
527
     * @param PhoneNumberUtil $util
528
     * @param PhoneNumber $number
529
     * @param string $normalizedCandidate
530
     * @param string[] $formattedNumberGroups
531
     * @return bool
532
     */
533 26
    public static function allNumberGroupsRemainGrouped(
534
        PhoneNumberUtil $util,
535
        PhoneNumber $number,
536
        $normalizedCandidate,
537
        $formattedNumberGroups
538
    ) {
539 26
        $fromIndex = 0;
540 26
        if ($number->getCountryCodeSource() !== CountryCodeSource::FROM_DEFAULT_COUNTRY) {
541
            // First skip the country code if the normalized candidate contained it.
542 10
            $countryCode = $number->getCountryCode();
543 10
            $fromIndex = mb_strpos($normalizedCandidate, $countryCode) + mb_strlen($countryCode);
544
        }
545
546
        // Check each group of consecutive digits are not broken into separate groupings in the
547
        // $normalizedCandidate string.
548 26
        $formattedNumberGroupsLength = count($formattedNumberGroups);
549 26
        for ($i = 0; $i < $formattedNumberGroupsLength; $i++) {
550
            // Fails if the substring of $normalizedCandidate starting from $fromIndex
551
            // doesn't contain the consecutive digits in $formattedNumberGroups[$i].
552 26
            $fromIndex = mb_strpos($normalizedCandidate, $formattedNumberGroups[$i], $fromIndex);
553 26
            if ($fromIndex === false) {
554 8
                return false;
555
            }
556
557
            // Moves $fromIndex forward.
558 25
            $fromIndex += mb_strlen($formattedNumberGroups[$i]);
559 25
            if ($i === 0 && $fromIndex < mb_strlen($normalizedCandidate)) {
560
                // We are at the position right after the NDC. We get the region used for formatting
561
                // information based on the country code in the phone number, rather than the number itself,
562
                // as we do not need to distinguish between different countries with the same country
563
                // calling code and this is faster.
564 25
                $region = $util->getRegionCodeForCountryCode($number->getCountryCode());
565
566 25
                if ($util->getNddPrefixForRegion($region, true) !== null
567 25
                    && is_int(mb_substr($normalizedCandidate, $fromIndex, 1))
568
                ) {
569
                    // This means there is no formatting symbol after the NDC. In this case, we only
570
                    // accept the number if there is no formatting symbol at all in the number, except
571
                    // for extensions. This is only important for countries with national prefixes.
572
                    $nationalSignificantNumber = $util->getNationalSignificantNumber($number);
573
                    return mb_substr(
574
                        mb_substr($normalizedCandidate, $fromIndex - mb_strlen($formattedNumberGroups[$i])),
575
                        mb_strlen($nationalSignificantNumber)
576
                    ) === $nationalSignificantNumber;
577
                }
578
            }
579
        }
580
        // The check here makes sure that we haven't mistakenly already used the extension to
581
        // match the last group of the subscriber number. Note the extension cannot have
582
        // formatting in-between digits
583
584 25
        if ($number->hasExtension()) {
585 4
            return mb_strpos(mb_substr($normalizedCandidate, $fromIndex), $number->getExtension()) !== false;
586
        }
587
588 21
        return true;
589
    }
590
591
    /**
592
     * @param PhoneNumberUtil $util
593
     * @param PhoneNumber $number
594
     * @param string $normalizedCandidate
595
     * @param string[] $formattedNumberGroups
596
     * @return bool
597
     */
598 26
    public static function allNumberGroupsAreExactlyPresent(
599
        PhoneNumberUtil $util,
600
        PhoneNumber $number,
601
        $normalizedCandidate,
602
        $formattedNumberGroups
603
    ) {
604 26
        $candidateGroups = preg_split(PhoneNumberUtil::NON_DIGITS_PATTERN, $normalizedCandidate);
605
606
        // Set this to the last group, skipping it if the number has an extension.
607 26
        $candidateNumberGroupIndex = $number->hasExtension() ? count($candidateGroups) - 2 : count($candidateGroups) - 1;
608
609
        // First we check if the national significant number is formatted as a block.
610
        // We use contains and not equals, since the national significant number may be present with
611
        // a prefix such as a national number prefix, or the country code itself.
612 26
        if (count($candidateGroups) == 1
613 23
            || mb_strpos($candidateGroups[$candidateNumberGroupIndex],
614 26
                $util->getNationalSignificantNumber($number)) !== false
615
        ) {
616 8
            return true;
617
        }
618
619
        // Starting from the end, go through in reverse, excluding the first group, and check the
620
        // candidate and number groups are the same.
621 18
        for ($formattedNumberGroupIndex = (count($formattedNumberGroups) - 1);
622 18
             $formattedNumberGroupIndex > 0 && $candidateNumberGroupIndex >= 0;
623
             $formattedNumberGroupIndex--, $candidateNumberGroupIndex--) {
624 18
            if ($candidateGroups[$candidateNumberGroupIndex] != $formattedNumberGroups[$formattedNumberGroupIndex]) {
625 5
                return false;
626
            }
627
        }
628
629
        // Now check the first group. There may be a national prefix at the start, so we only check
630
        // that the candidate group ends with the formatted number group.
631 18
        return ($candidateNumberGroupIndex >= 0
632 18
            && mb_substr($candidateGroups[$candidateNumberGroupIndex],
633 18
                -mb_strlen($formattedNumberGroups[0])) == $formattedNumberGroups[0]);
634
    }
635
636
    /**
637
     * Helper method to get the national-number part of a number, formatted without any national
638
     * prefix, and return it as a set of digit blocks that would be formatted together.
639
     *
640
     * @param PhoneNumberUtil $util
641
     * @param PhoneNumber $number
642
     * @param NumberFormat $formattingPattern
643
     * @return string[]
644
     */
645 52
    protected static function getNationalNumberGroups(
646
        PhoneNumberUtil $util,
647
        PhoneNumber $number,
648
        NumberFormat $formattingPattern = null
649
    ) {
650 52
        if ($formattingPattern === null) {
651
            // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits.
652 52
            $rfc3966Format = $util->format($number, PhoneNumberFormat::RFC3966);
653
            // We remove the extension part from the formatted string before splitting it into different
654
            // groups.
655 52
            $endIndex = mb_strpos($rfc3966Format, ';');
656 52
            if ($endIndex === false) {
657 42
                $endIndex = mb_strlen($rfc3966Format);
658
            }
659
660
            // The country-code will have a '-' following it.
661 52
            $startIndex = mb_strpos($rfc3966Format, '-') + 1;
662 52
            return explode('-', mb_substr($rfc3966Format, $startIndex, $endIndex - $startIndex));
663
        } else {
664
            // We format the NSN only, and split that according to the separator.
665 13
            $nationalSignificantNumber = $util->getNationalSignificantNumber($number);
666 13
            return explode('-', $util->formatNsnUsingPattern($nationalSignificantNumber, $formattingPattern,
667 13
                PhoneNumberFormat::RFC3966));
668
        }
669
    }
670
671
    /**
672
     * @param PhoneNumber $number
673
     * @param string $candidate
674
     * @param PhoneNumberUtil $util
675
     * @param \Closure $checker
676
     * @return bool
677
     */
678 52
    public static function checkNumberGroupingIsValid(
679
        PhoneNumber $number,
680
        $candidate,
681
        PhoneNumberUtil $util,
682
        \Closure $checker
683
    ) {
684
        // TODO: Evaluate how this works for other locales (testing has been limited to NANPA regions)
685
        // and optimise if necessary.
686 52
        $normalizedCandidate = PhoneNumberUtil::normalizeDigits($candidate, true /* keep non-digits */);
687 52
        $formattedNumberGroups = static::getNationalNumberGroups($util, $number, null);
688 52
        if ($checker($util, $number, $normalizedCandidate, $formattedNumberGroups)) {
689 39
            return true;
690
        }
691
692
        // If this didn't pass, see if there are any alternative formats, and try them instead.
693 13
        $alternateFormats = static::getAlternateFormatsForCountry($number->getCountryCode());
694
695 13
        if ($alternateFormats !== null) {
696 13
            foreach ($alternateFormats->numberFormats() as $alternateFormat) {
697 13
                $formattedNumberGroups = static::getNationalNumberGroups($util, $number, $alternateFormat);
698 13
                if ($checker($util, $number, $normalizedCandidate, $formattedNumberGroups)) {
699 13
                    return true;
700
                }
701
            }
702
        }
703 2
        return false;
704
    }
705
706
    /**
707
     * @param PhoneNumber $number
708
     * @param string $candidate
709
     * @return bool
710
     */
711 53
    public static function containsMoreThanOneSlashInNationalNumber(PhoneNumber $number, $candidate)
712
    {
713 53
        $firstSlashInBodyIndex = mb_strpos($candidate, '/');
714 53
        if ($firstSlashInBodyIndex === false) {
715
            // No slashes, this is okay
716 51
            return false;
717
        }
718
719
        // Now look for a second one.
720 2
        $secondSlashInBodyIndex = mb_strpos($candidate, '/', $firstSlashInBodyIndex + 1);
721 2
        if ($secondSlashInBodyIndex === false) {
722
            // Only one slash, this is okay
723 1
            return false;
724
        }
725
726
        // If the first slash is after the country calling code, this is permitted
727 1
        $candidateHasCountryCode = ($number->getCountryCodeSource() === CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN
728 1
            || $number->getCountryCodeSource() === CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN);
729
730 1
        if ($candidateHasCountryCode
731 1
            && PhoneNumberUtil::normalizeDigitsOnly(
732 1
                mb_substr($candidate, 0, $firstSlashInBodyIndex)
733 1
            ) == $number->getCountryCode()
734
        ) {
735
            // Any more slashes and this is illegal
736 1
            return (mb_strpos(mb_substr($candidate, $secondSlashInBodyIndex + 1), '/') !== false);
737
        }
738
739 1
        return true;
740
    }
741
742
    /**
743
     * @param PhoneNumber $number
744
     * @param string $candidate
745
     * @param PhoneNumberUtil $util
746
     * @return bool
747
     */
748 97
    public static function containsOnlyValidXChars(PhoneNumber $number, $candidate, PhoneNumberUtil $util)
749
    {
750
        // The characters 'x' and 'X' can be (1) a carrier code, in which case they always precede the
751
        // national significant number or (2) an extension sign, in which case they always precede the
752
        // extension number. We assume a carrier code is more than 1 digit, so the first case has to
753
        // have more than 1 consecutive 'x' or 'X', whereas the second case can only have exactly 1 'x'
754
        // or 'X'. We ignore the character if it appears as the last character of the string.
755 97
        $candidateLength = mb_strlen($candidate);
756
757 97
        for ($index = 0; $index < $candidateLength - 1; $index++) {
758 97
            $charAtIndex = mb_substr($candidate, $index, 1);
759 97
            if ($charAtIndex == 'x' || $charAtIndex == 'X') {
760 15
                $charAtNextIndex = mb_substr($candidate, $index + 1, 1);
761 15
                if ($charAtNextIndex == 'x' || $charAtNextIndex == 'X') {
762
                    // This is the carrier code case, in which the 'X's always precede the national
763
                    // significant number.
764
                    $index++;
765
766
                    if ($util->isNumberMatch($number, mb_substr($candidate, $index)) != MatchType::NSN_MATCH) {
767
                        return false;
768
                    }
769 15
                } elseif (!PhoneNumberUtil::normalizeDigitsOnly(mb_substr($candidate,
770 15
                        $index)) == $number->getExtension()
771
                ) {
772
                    // This is the extension sign case, in which the 'x' or 'X' should always precede the
773
                    // extension number
774
                    return false;
775
                }
776
            }
777
        }
778 97
        return true;
779
    }
780
781
    /**
782
     * @param PhoneNumber $number
783
     * @param PhoneNumberUtil $util
784
     * @return bool
785
     */
786 97
    public static function isNationalPrefixPresentIfRequired(PhoneNumber $number, PhoneNumberUtil $util)
787
    {
788
        // First, check how we deduced the country code. If it was written in international format, then
789
        // the national prefix is not required.
790 97
        if ($number->getCountryCodeSource() !== CountryCodeSource::FROM_DEFAULT_COUNTRY) {
791 39
            return true;
792
        }
793
794 65
        $phoneNumberRegion = $util->getRegionCodeForCountryCode($number->getCountryCode());
795 65
        $metadata = $util->getMetadataForRegion($phoneNumberRegion);
796 65
        if ($metadata === null) {
797
            return true;
798
        }
799
800
        // Check if a national prefix should be present when formatting this number.
801 65
        $nationalNumber = $util->getNationalSignificantNumber($number);
802 65
        $formatRule = $util->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
803
        // To do this, we check that a national prefix formatting rule was present and that it wasn't
804
        // just the first-group symbol ($1) with punctuation.
805 65
        if (($formatRule !== null) && mb_strlen($formatRule->getNationalPrefixFormattingRule()) > 0) {
806 44
            if ($formatRule->getNationalPrefixOptionalWhenFormatting()) {
807
                // The national-prefix is optional in these cases, so we don't need to check if it was
808
                // present.
809 7
                return true;
810
            }
811
812 37
            if (PhoneNumberUtil::formattingRuleHasFirstGroupOnly($formatRule->getNationalPrefixFormattingRule())) {
813
                // National Prefix not needed for this number.
814 3
                return true;
815
            }
816
817
            // Normalize the remainder.
818 34
            $rawInputCopy = PhoneNumberUtil::normalizeDigitsOnly($number->getRawInput());
819 34
            $rawInput = $rawInputCopy;
820
            // Check if we found a national prefix and/or carrier code at the start of the raw input, and
821
            // return the result.
822 34
            $carrierCode = null;
823 34
            return $util->maybeStripNationalPrefixAndCarrierCode($rawInput, $metadata, $carrierCode);
824
        }
825 25
        return true;
826
    }
827
828
829
    /**
830
     * Storage for Alternate Formats
831
     * @var PhoneMetadata[]
832
     */
833
    protected static $callingCodeToAlternateFormatsMap = array();
834
835
    /**
836
     * @param $countryCallingCode
837
     * @return PhoneMetadata|null
838
     */
839 13
    protected static function getAlternateFormatsForCountry($countryCallingCode)
840
    {
841 13
        $countryCodeSet = AlternateFormatsCountryCodeSet::$alternateFormatsCountryCodeSet;
842
843 13
        if (!in_array($countryCallingCode, $countryCodeSet)) {
844
            return null;
845
        }
846
847 13
        if (!isset(static::$callingCodeToAlternateFormatsMap[$countryCallingCode])) {
848 2
            static::loadAlternateFormatsMetadataFromFile($countryCallingCode);
849
        }
850
851 13
        return static::$callingCodeToAlternateFormatsMap[$countryCallingCode];
852
    }
853
854
    /**
855
     * @param string $countryCallingCode
856
     * @throws \Exception
857
     */
858 2
    protected static function loadAlternateFormatsMetadataFromFile($countryCallingCode)
859
    {
860 2
        $fileName = static::$alternateFormatsFilePrefix . '_' . $countryCallingCode . '.php';
861
862 2
        if (!is_readable($fileName)) {
863
            throw new \Exception('missing metadata: ' . $fileName);
864
        }
865
866 2
        $metadataLoader = new DefaultMetadataLoader();
867 2
        $data = $metadataLoader->loadMetadata($fileName);
868 2
        $metadata = new PhoneMetadata();
869 2
        $metadata->fromArray($data);
870 2
        static::$callingCodeToAlternateFormatsMap[$countryCallingCode] = $metadata;
871 2
    }
872
873
874
    /**
875
     * Return the current element
876
     * @link http://php.net/manual/en/iterator.current.php
877
     * @return PhoneNumberMatch|null
878
     */
879 197
    public function current()
880
    {
881 197
        return $this->lastMatch;
882
    }
883
884
    /**
885
     * Move forward to next element
886
     * @link http://php.net/manual/en/iterator.next.php
887
     * @return void Any returned value is ignored.
888
     */
889 199
    public function next()
890
    {
891 199
        $this->lastMatch = $this->find($this->searchIndex);
892
893 199
        if ($this->lastMatch === null) {
894 93
            $this->state = 'DONE';
895
        } else {
896 126
            $this->searchIndex = $this->lastMatch->end();
897 126
            $this->state = 'READY';
898
        }
899
900 199
        $this->searchIndex++;
901 199
    }
902
903
    /**
904
     * Return the key of the current element
905
     * @link http://php.net/manual/en/iterator.key.php
906
     * @return mixed scalar on success, or null on failure.
907
     * @since 5.0.0
908
     */
909
    public function key()
910
    {
911
        return $this->searchIndex;
912
    }
913
914
    /**
915
     * Checks if current position is valid
916
     * @link http://php.net/manual/en/iterator.valid.php
917
     * @return boolean The return value will be casted to boolean and then evaluated.
918
     * Returns true on success or false on failure.
919
     * @since 5.0.0
920
     */
921 29
    public function valid()
922
    {
923 29
        return $this->state === 'READY';
924
    }
925
926
    /**
927
     * Rewind the Iterator to the first element
928
     * @link http://php.net/manual/en/iterator.rewind.php
929
     * @return void Any returned value is ignored.
930
     * @since 5.0.0
931
     */
932 18
    public function rewind()
933
    {
934 18
        $this->searchIndex = 0;
935 18
        $this->next();
936 18
    }
937
}
938