Passed
Pull Request — master (#410)
by Joshua
13:01 queued 07:30
created

PhoneNumberMatcher::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 85
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 31
nc 1
nop 0
dl 0
loc 85
ccs 25
cts 26
cp 0.9615
crap 1
rs 9.424
c 2
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
            '/+(.*)',
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
        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::initExtnPatterns();
182
183
        // Phone number pattern allowing optional punctuation.
184 1
        static::$pattern = '(?:' . $leadClass . $punctuation . ')' . $leadLimit
185 1
            . $digitSequence . '(?:' . $punctuation . $digitSequence . ')' . $blockLimit
186 1
            . '(?:' . PhoneNumberUtil::$EXTN_PATTERNS_FOR_MATCHING . ')?';
187
188 1
        static::$initialized = true;
189 1
    }
190
191
    /**
192
     * Helper function to generate regular expression with an upper and lower limit.
193
     *
194
     * @param int $lower
195
     * @param int $upper
196
     * @return string
197
     */
198 1
    protected static function limit($lower, $upper)
199
    {
200 1
        if (($lower < 0) || ($upper <= 0) || ($upper < $lower)) {
201
            throw new \InvalidArgumentException();
202
        }
203
204 1
        return '{' . $lower . ',' . $upper . '}';
205
    }
206
207
    /**
208
     * The phone number utility.
209
     * @var PhoneNumberUtil
210
     */
211
    protected $phoneUtil;
212
213
    /**
214
     * The text searched for phone numbers.
215
     * @var string
216
     */
217
    protected $text;
218
219
    /**
220
     * The region (country) to assume for phone numbers without an international prefix, possibly
221
     * null.
222
     * @var string
223
     */
224
    protected $preferredRegion;
225
226
    /**
227
     * The degrees of validation requested.
228
     * @var AbstractLeniency
229
     */
230
    protected $leniency;
231
232
    /**
233
     * The maximum number of retires after matching an invalid number.
234
     * @var int
235
     */
236
    protected $maxTries;
237
238
    /**
239
     * One of:
240
     *  - NOT_READY
241
     *  - READY
242
     *  - DONE
243
     * @var string
244
     */
245
    protected $state = 'NOT_READY';
246
247
    /**
248
     * The last successful match, null unless $this->state = READY
249
     * @var PhoneNumberMatch
250
     */
251
    protected $lastMatch;
252
253
    /**
254
     * The next index to start searching at. Undefined when $this->state = DONE
255
     * @var int
256
     */
257
    protected $searchIndex = 0;
258
259
    /**
260
     * Creates a new instance. See the factory methods in PhoneNumberUtil on how to obtain a new instance.
261
     *
262
     *
263
     * @param PhoneNumberUtil $util The Phone Number Util to use
264
     * @param string|null $text The text that we will search, null for no text
265
     * @param string|null $country The country to assume for phone numbers not written in international format.
266
     *  (with a leading plus, or with the international dialling prefix of the specified region).
267
     *  May be null, or "ZZ" if only numbers with a leading plus should be considered.
268
     * @param AbstractLeniency $leniency The leniency to use when evaluating candidate phone numbers
269
     * @param int $maxTries The maximum number of invalid numbers to try before giving up on the text.
270
     *  This is to cover degenerate cases where the text has a lot of false positives in it. Must be >= 0
271
     * @throws \NullPointerException
272
     * @throws \InvalidArgumentException
273
     */
274 207
    public function __construct(PhoneNumberUtil $util, $text, $country, AbstractLeniency $leniency, $maxTries)
275
    {
276 207
        if ($maxTries < 0) {
277
            throw new \InvalidArgumentException();
278
        }
279
280 207
        $this->phoneUtil = $util;
281 207
        $this->text = ($text !== null) ? $text : '';
282 207
        $this->preferredRegion = $country;
283 207
        $this->leniency = $leniency;
284 207
        $this->maxTries = $maxTries;
285
286 207
        if (static::$initialized === false) {
287 1
            static::init();
288
        }
289 207
    }
290
291
    /**
292
     * Attempts to find the next subsequence in the searched sequence on or after {@code searchIndex}
293
     * that represents a phone number. Returns the next match, null if none was found.
294
     *
295
     * @param int $index The search index to start searching at
296
     * @return PhoneNumberMatch|null The Phone Number Match found, null if none can be found
297
     */
298 201
    protected function find($index)
299
    {
300 201
        $matcher = new Matcher(static::$pattern, $this->text);
301 201
        while (($this->maxTries > 0) && $matcher->find($index)) {
302 200
            $start = $matcher->start();
303 200
            $cutLength = $matcher->end() - $start;
304 200
            $candidate = \mb_substr($this->text, $start, $cutLength);
305
306
            // Check for extra numbers at the end.
307
            // TODO: This is the place to start when trying to support extraction of multiple phone number
308
            // from split notations (+41 49 123 45 67 / 68).
309 200
            $candidate = static::trimAfterFirstMatch(PhoneNumberUtil::$SECOND_NUMBER_START_PATTERN, $candidate);
310
311 200
            $match = $this->extractMatch($candidate, $start);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $match is correct as $this->extractMatch($candidate, $start) targeting libphonenumber\PhoneNumberMatcher::extractMatch() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
312 200
            if ($match !== null) {
313 126
                return $match;
314
            }
315
316 92
            $index = $start + \mb_strlen($candidate);
317 92
            $this->maxTries--;
318
        }
319
320 95
        return null;
321
    }
322
323
    /**
324
     * Trims away any characters after the first match of $pattern in $candidate,
325
     * returning the trimmed version.
326
     *
327
     * @param string $pattern
328
     * @param string $candidate
329
     * @return string
330
     */
331 200
    protected static function trimAfterFirstMatch($pattern, $candidate)
332
    {
333 200
        $trailingCharsMatcher = new Matcher($pattern, $candidate);
334 200
        if ($trailingCharsMatcher->find()) {
335 10
            $startChar = $trailingCharsMatcher->start();
336 10
            $candidate = \mb_substr($candidate, 0, $startChar);
337
        }
338 200
        return $candidate;
339
    }
340
341
    /**
342
     * Helper method to determine if a character is a Latin-script letter or not. For our purposes,
343
     * combining marks should also return true since we assume they have been added to a preceding
344
     * Latin character.
345
     *
346
     * @param string $letter
347
     * @return bool
348
     * @internal
349
     */
350 60
    public static function isLatinLetter($letter)
351
    {
352
        // Combining marks are a subset of non-spacing-mark.
353 60
        if (\preg_match('/\p{L}/u', $letter) !== 1 && \preg_match('/\p{Mn}/u', $letter) !== 1) {
354 54
            return false;
355
        }
356
357 9
        return (\preg_match('/\p{Latin}/u', $letter) === 1)
358 9
        || (\preg_match('/\pM+/u', $letter) === 1);
359
    }
360
361
    /**
362
     * @param string $character
363
     * @return bool
364
     */
365 49
    protected static function isInvalidPunctuationSymbol($character)
366
    {
367 49
        return $character == '%' || \preg_match('/\p{Sc}/u', $character);
368
    }
369
370
    /**
371
     * Attempts to extract a match from a $candidate.
372
     *
373
     * @param string $candidate The candidate text that might contain a phone number
374
     * @param int $offset The offset of $candidate within $this->text
375
     * @return PhoneNumberMatch|null The match found, null if none can be found
376
     */
377 200
    protected function extractMatch($candidate, $offset)
378
    {
379
        // Skip a match that is more likely to be a date.
380 200
        $dateMatcher = new Matcher(static::$slashSeparatedDates, $candidate);
381 200
        if ($dateMatcher->find()) {
382 33
            return null;
383
        }
384
385
        // Skip potential time-stamps.
386 180
        $timeStampMatcher = new Matcher(static::$timeStamps, $candidate);
387 180
        if ($timeStampMatcher->find()) {
388 20
            $followingText = \mb_substr($this->text, $offset + \mb_strlen($candidate));
389 20
            $timeStampSuffixMatcher = new Matcher(static::$timeStampsSuffix, $followingText);
390 20
            if ($timeStampSuffixMatcher->lookingAt()) {
391 16
                return null;
392
            }
393
        }
394
395
        // Try to come up with a valid match given the entire candidate.
396 180
        $match = $this->parseAndVerify($candidate, $offset);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $match is correct as $this->parseAndVerify($candidate, $offset) targeting libphonenumber\PhoneNumb...tcher::parseAndVerify() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
397 180
        if ($match !== null) {
0 ignored issues
show
introduced by
The condition $match !== null is always false.
Loading history...
398 124
            return $match;
399
        }
400
401
        // If that failed, try to find an "inner match" - there might be a phone number within this
402
        // candidate.
403 76
        return $this->extractInnerMatch($candidate, $offset);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->extractInnerMatch($candidate, $offset) targeting libphonenumber\PhoneNumb...er::extractInnerMatch() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
404
    }
405
406
    /**
407
     * Attempts to extract a match from $candidate if the whole candidate does not qualify as a
408
     * match.
409
     *
410
     * @param string $candidate The candidate text that might contact a phone number
411
     * @param int $offset The current offset of $candidate within $this->text
412
     * @return PhoneNumberMatch|null The match found, null if none can be found
413
     */
414 76
    protected function extractInnerMatch($candidate, $offset)
415
    {
416 76
        foreach (static::$innerMatches as $possibleInnerMatch) {
417 76
            $groupMatcher = new Matcher($possibleInnerMatch, $candidate);
418 76
            $isFirstMatch = true;
419
420 76
            while ($groupMatcher->find() && $this->maxTries > 0) {
421 20
                if ($isFirstMatch) {
422
                    // We should handle any group before this one too.
423 20
                    $group = static::trimAfterFirstMatch(
424 20
                        PhoneNumberUtil::$UNWANTED_END_CHAR_PATTERN,
425 20
                        \mb_substr($candidate, 0, $groupMatcher->start())
426
                    );
427
428 20
                    $match = $this->parseAndVerify($group, $offset);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $match is correct as $this->parseAndVerify($group, $offset) targeting libphonenumber\PhoneNumb...tcher::parseAndVerify() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
429 20
                    if ($match !== null) {
430 6
                        return $match;
431
                    }
432 17
                    $this->maxTries--;
433 17
                    $isFirstMatch = false;
434
                }
435 17
                $group = static::trimAfterFirstMatch(
436 17
                    PhoneNumberUtil::$UNWANTED_END_CHAR_PATTERN,
437 17
                    $groupMatcher->group(1)
438
                );
439 17
                $match = $this->parseAndVerify($group, $offset + $groupMatcher->start(1));
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $match is correct as $this->parseAndVerify($g...groupMatcher->start(1)) targeting libphonenumber\PhoneNumb...tcher::parseAndVerify() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
440 17
                if ($match !== null) {
441 7
                    return $match;
442
                }
443 16
                $this->maxTries--;
444
            }
445
        }
446 72
        return null;
447
    }
448
449
    /**
450
     * Parses a phone number from the $candidate} using PhoneNumberUtil::parse() and
451
     * verifies it matches the requested leniency. If parsing and verification succeed, a
452
     * corresponding PhoneNumberMatch is returned, otherwise this method returns null.
453
     *
454
     * @param string $candidate The candidate match
455
     * @param int $offset The offset of $candidate within $this->text
456
     * @return PhoneNumberMatch|null The parsed and validated phone number match, or null
457
     */
458 180
    protected function parseAndVerify($candidate, $offset)
459
    {
460
        try {
461
            // Check the candidate doesn't contain any formatting which would indicate that it really
462
            // isn't a phone number
463 180
            $matchingBracketsMatcher = new Matcher(static::$matchingBrackets, $candidate);
464 180
            $pubPagesMatcher = new Matcher(static::$pubPages, $candidate);
465 180
            if (!$matchingBracketsMatcher->matches() || $pubPagesMatcher->find()) {
466 11
                return null;
467
            }
468
469
            // If leniency is set to VALID or stricter, we also want to skip numbers that are surrounded
470
            // by Latin alphabetic characters, to skip cases like abc8005001234 or 8005001234def.
471 180
            if ($this->leniency->compareTo(Leniency::VALID()) >= 0) {
472
                // If the candidate is not at the start of the text, and does not start with phone-number
473
                // punctuation, check the previous character.
474 137
                $leadClassMatcher = new Matcher(static::$leadClass, $candidate);
475 137
                if ($offset > 0 && !$leadClassMatcher->lookingAt()) {
476 44
                    $previousChar = \mb_substr($this->text, $offset - 1, 1);
477
                    // We return null if it is a latin letter or an invalid punctuation symbol.
478 44
                    if (static::isInvalidPunctuationSymbol($previousChar) || static::isLatinLetter($previousChar)) {
479 2
                        return null;
480
                    }
481
                }
482 137
                $lastCharIndex = $offset + \mb_strlen($candidate);
483 137
                if ($lastCharIndex < \mb_strlen($this->text)) {
484 40
                    $nextChar = \mb_substr($this->text, $lastCharIndex, 1);
485 40
                    if (static::isInvalidPunctuationSymbol($nextChar) || static::isLatinLetter($nextChar)) {
486 2
                        return null;
487
                    }
488
                }
489
            }
490
491 179
            $number = $this->phoneUtil->parseAndKeepRawInput($candidate, $this->preferredRegion);
492
493 178
            if ($this->leniency->verify($number, $candidate, $this->phoneUtil)) {
494
                // We used parseAndKeepRawInput to create this number, but for now we don't return the extra
495
                // values parsed. TODO: stop clearing all values here and switch all users over
496
                // to using rawInput() rather than the rawString() of PhoneNumberMatch
497 126
                $number->clearCountryCodeSource();
498 126
                $number->clearRawInput();
499 126
                $number->clearPreferredDomesticCarrierCode();
500 178
                return new PhoneNumberMatch($offset, $candidate, $number);
501
            }
502 28
        } catch (NumberParseException $e) {
503
            // ignore and continue
504
        }
505 74
        return null;
506
    }
507
508
    /**
509
     * @param PhoneNumberUtil $util
510
     * @param PhoneNumber $number
511
     * @param string $normalizedCandidate
512
     * @param string[] $formattedNumberGroups
513
     * @return bool
514
     */
515 27
    public static function allNumberGroupsRemainGrouped(
516
        PhoneNumberUtil $util,
517
        PhoneNumber $number,
518
        $normalizedCandidate,
519
        $formattedNumberGroups
520
    ) {
521 27
        $fromIndex = 0;
522 27
        if ($number->getCountryCodeSource() !== CountryCodeSource::FROM_DEFAULT_COUNTRY) {
523
            // First skip the country code if the normalized candidate contained it.
524 11
            $countryCode = $number->getCountryCode();
525 11
            $fromIndex = \mb_strpos($normalizedCandidate, $countryCode) + \mb_strlen($countryCode);
526
        }
527
528
        // Check each group of consecutive digits are not broken into separate groupings in the
529
        // $normalizedCandidate string.
530 27
        $formattedNumberGroupsLength = \count($formattedNumberGroups);
531 27
        for ($i = 0; $i < $formattedNumberGroupsLength; $i++) {
532
            // Fails if the substring of $normalizedCandidate starting from $fromIndex
533
            // doesn't contain the consecutive digits in $formattedNumberGroups[$i].
534 27
            $fromIndex = \mb_strpos($normalizedCandidate, $formattedNumberGroups[$i], $fromIndex);
535 27
            if ($fromIndex === false) {
536 9
                return false;
537
            }
538
539
            // Moves $fromIndex forward.
540 26
            $fromIndex += \mb_strlen($formattedNumberGroups[$i]);
541 26
            if ($i === 0 && $fromIndex < \mb_strlen($normalizedCandidate)) {
542
                // We are at the position right after the NDC. We get the region used for formatting
543
                // information based on the country code in the phone number, rather than the number itself,
544
                // as we do not need to distinguish between different countries with the same country
545
                // calling code and this is faster.
546 26
                $region = $util->getRegionCodeForCountryCode($number->getCountryCode());
547
548 26
                if ($util->getNddPrefixForRegion($region, true) !== null
549 26
                    && \is_int(\mb_substr($normalizedCandidate, $fromIndex, 1))
550
                ) {
551
                    // This means there is no formatting symbol after the NDC. In this case, we only
552
                    // accept the number if there is no formatting symbol at all in the number, except
553
                    // for extensions. This is only important for countries with national prefixes.
554
                    $nationalSignificantNumber = $util->getNationalSignificantNumber($number);
555
                    return \mb_substr(
556
                        \mb_substr($normalizedCandidate, $fromIndex - \mb_strlen($formattedNumberGroups[$i])),
557
                        \mb_strlen($nationalSignificantNumber)
558
                    ) === $nationalSignificantNumber;
559
                }
560
            }
561
        }
562
        // The check here makes sure that we haven't mistakenly already used the extension to
563
        // match the last group of the subscriber number. Note the extension cannot have
564
        // formatting in-between digits
565
566 25
        if ($number->hasExtension()) {
567 4
            return \mb_strpos(\mb_substr($normalizedCandidate, $fromIndex), $number->getExtension()) !== false;
568
        }
569
570 21
        return true;
571
    }
572
573
    /**
574
     * @param PhoneNumberUtil $util
575
     * @param PhoneNumber $number
576
     * @param string $normalizedCandidate
577
     * @param string[] $formattedNumberGroups
578
     * @return bool
579
     */
580 27
    public static function allNumberGroupsAreExactlyPresent(
581
        PhoneNumberUtil $util,
582
        PhoneNumber $number,
583
        $normalizedCandidate,
584
        $formattedNumberGroups
585
    ) {
586 27
        $candidateGroups = \preg_split(PhoneNumberUtil::NON_DIGITS_PATTERN, $normalizedCandidate);
587
588
        // Set this to the last group, skipping it if the number has an extension.
589 27
        $candidateNumberGroupIndex = $number->hasExtension() ? \count($candidateGroups) - 2 : \count($candidateGroups) - 1;
0 ignored issues
show
Bug introduced by
It seems like $candidateGroups can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

589
        $candidateNumberGroupIndex = $number->hasExtension() ? \count(/** @scrutinizer ignore-type */ $candidateGroups) - 2 : \count($candidateGroups) - 1;
Loading history...
590
591
        // First we check if the national significant number is formatted as a block.
592
        // We use contains and not equals, since the national significant number may be present with
593
        // a prefix such as a national number prefix, or the country code itself.
594 27
        if (\count($candidateGroups) == 1
595 24
            || \mb_strpos(
596 24
                $candidateGroups[$candidateNumberGroupIndex],
597 24
                $util->getNationalSignificantNumber($number)
598 27
            ) !== false
599
        ) {
600 8
            return true;
601
        }
602
603
        // Starting from the end, go through in reverse, excluding the first group, and check the
604
        // candidate and number groups are the same.
605 19
        for ($formattedNumberGroupIndex = (\count($formattedNumberGroups) - 1);
606 19
             $formattedNumberGroupIndex > 0 && $candidateNumberGroupIndex >= 0;
607
             $formattedNumberGroupIndex--, $candidateNumberGroupIndex--) {
608 19
            if ($candidateGroups[$candidateNumberGroupIndex] != $formattedNumberGroups[$formattedNumberGroupIndex]) {
609 6
                return false;
610
            }
611
        }
612
613
        // Now check the first group. There may be a national prefix at the start, so we only check
614
        // that the candidate group ends with the formatted number group.
615 18
        return ($candidateNumberGroupIndex >= 0
616 18
            && \mb_substr(
617 18
                $candidateGroups[$candidateNumberGroupIndex],
618 18
                -\mb_strlen($formattedNumberGroups[0])
619 18
            ) == $formattedNumberGroups[0]);
620
    }
621
622
    /**
623
     * Helper method to get the national-number part of a number, formatted without any national
624
     * prefix, and return it as a set of digit blocks that would be formatted together.
625
     *
626
     * @param PhoneNumberUtil $util
627
     * @param PhoneNumber $number
628
     * @param NumberFormat $formattingPattern
629
     * @return string[]
630
     */
631 54
    protected static function getNationalNumberGroups(
632
        PhoneNumberUtil $util,
633
        PhoneNumber $number,
634
        NumberFormat $formattingPattern = null
635
    ) {
636 54
        if ($formattingPattern === null) {
637
            // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits.
638 54
            $rfc3966Format = $util->format($number, PhoneNumberFormat::RFC3966);
639
            // We remove the extension part from the formatted string before splitting it into different
640
            // groups.
641 54
            $endIndex = \mb_strpos($rfc3966Format, ';');
642 54
            if ($endIndex === false) {
643 44
                $endIndex = \mb_strlen($rfc3966Format);
644
            }
645
646
            // The country-code will have a '-' following it.
647 54
            $startIndex = \mb_strpos($rfc3966Format, '-') + 1;
648 54
            return \explode('-', \mb_substr($rfc3966Format, $startIndex, $endIndex - $startIndex));
649
        }
650
651
        // If a format is provided, we format the NSN only, and split that according to the separator.
652 15
        $nationalSignificantNumber = $util->getNationalSignificantNumber($number);
653 15
        return \explode('-', $util->formatNsnUsingPattern(
654 15
            $nationalSignificantNumber,
655
            $formattingPattern,
656 15
            PhoneNumberFormat::RFC3966
657
        ));
658
    }
659
660
    /**
661
     * @param PhoneNumber $number
662
     * @param string $candidate
663
     * @param PhoneNumberUtil $util
664
     * @param \Closure $checker
665
     * @return bool
666
     */
667 54
    public static function checkNumberGroupingIsValid(
668
        PhoneNumber $number,
669
        $candidate,
670
        PhoneNumberUtil $util,
671
        \Closure $checker
672
    ) {
673 54
        $normalizedCandidate = PhoneNumberUtil::normalizeDigits($candidate, true /* keep non-digits */);
674 54
        $formattedNumberGroups = static::getNationalNumberGroups($util, $number);
675 54
        if ($checker($util, $number, $normalizedCandidate, $formattedNumberGroups)) {
676 39
            return true;
677
        }
678
679
        // If this didn't pass, see if there are any alternative formats that match, and try them instead.
680 15
        $alternateFormats = static::getAlternateFormatsForCountry($number->getCountryCode());
681
682 15
        $nationalSignificantNumber = $util->getNationalSignificantNumber($number);
683 15
        if ($alternateFormats !== null) {
684 15
            foreach ($alternateFormats->numberFormats() as $alternateFormat) {
685 15
                if ($alternateFormat->leadingDigitsPatternSize() > 0) {
686
                    // There is only one leading digits pattern for alternate formats.
687 13
                    $pattern = $alternateFormat->getLeadingDigitsPattern(0);
688
689 13
                    $nationalSignificantNumberMatcher = new Matcher($pattern, $nationalSignificantNumber);
690 13
                    if (!$nationalSignificantNumberMatcher->lookingAt()) {
691
                        // Leading digits don't match; try another one.
692 13
                        continue;
693
                    }
694
                }
695
696 15
                $formattedNumberGroups = static::getNationalNumberGroups($util, $number, $alternateFormat);
697 15
                if ($checker($util, $number, $normalizedCandidate, $formattedNumberGroups)) {
698 11
                    return true;
699
                }
700
            }
701
        }
702 4
        return false;
703
    }
704
705
    /**
706
     * @param PhoneNumber $number
707
     * @param string $candidate
708
     * @return bool
709
     */
710 55
    public static function containsMoreThanOneSlashInNationalNumber(PhoneNumber $number, $candidate)
711
    {
712 55
        $firstSlashInBodyIndex = \mb_strpos($candidate, '/');
713 55
        if ($firstSlashInBodyIndex === false) {
714
            // No slashes, this is okay
715 53
            return false;
716
        }
717
718
        // Now look for a second one.
719 2
        $secondSlashInBodyIndex = \mb_strpos($candidate, '/', $firstSlashInBodyIndex + 1);
720 2
        if ($secondSlashInBodyIndex === false) {
721
            // Only one slash, this is okay
722 1
            return false;
723
        }
724
725
        // If the first slash is after the country calling code, this is permitted
726 1
        $candidateHasCountryCode = ($number->getCountryCodeSource() === CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN
727 1
            || $number->getCountryCodeSource() === CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN);
728
729 1
        if ($candidateHasCountryCode
730 1
            && PhoneNumberUtil::normalizeDigitsOnly(
731 1
                \mb_substr($candidate, 0, $firstSlashInBodyIndex)
732 1
            ) == $number->getCountryCode()
733
        ) {
734
            // Any more slashes and this is illegal
735 1
            return (\mb_strpos(\mb_substr($candidate, $secondSlashInBodyIndex + 1), '/') !== false);
736
        }
737
738 1
        return true;
739
    }
740
741
    /**
742
     * @param PhoneNumber $number
743
     * @param string $candidate
744
     * @param PhoneNumberUtil $util
745
     * @return bool
746
     */
747 99
    public static function containsOnlyValidXChars(PhoneNumber $number, $candidate, PhoneNumberUtil $util)
748
    {
749
        // The characters 'x' and 'X' can be (1) a carrier code, in which case they always precede the
750
        // national significant number or (2) an extension sign, in which case they always precede the
751
        // extension number. We assume a carrier code is more than 1 digit, so the first case has to
752
        // have more than 1 consecutive 'x' or 'X', whereas the second case can only have exactly 1 'x'
753
        // or 'X'. We ignore the character if it appears as the last character of the string.
754 99
        $candidateLength = \mb_strlen($candidate);
755
756 99
        for ($index = 0; $index < $candidateLength - 1; $index++) {
757 99
            $charAtIndex = \mb_substr($candidate, $index, 1);
758 99
            if ($charAtIndex == 'x' || $charAtIndex == 'X') {
759 15
                $charAtNextIndex = \mb_substr($candidate, $index + 1, 1);
760 15
                if ($charAtNextIndex == 'x' || $charAtNextIndex == 'X') {
761
                    // This is the carrier code case, in which the 'X's always precede the national
762
                    // significant number.
763
                    $index++;
764
765
                    if ($util->isNumberMatch($number, \mb_substr($candidate, $index)) != MatchType::NSN_MATCH) {
766
                        return false;
767
                    }
768 15
                } elseif (!PhoneNumberUtil::normalizeDigitsOnly(\mb_substr(
769 15
                    $candidate,
770 15
                    $index
771 15
                )) == $number->getExtension()
772
                ) {
773
                    // This is the extension sign case, in which the 'x' or 'X' should always precede the
774
                    // extension number
775
                    return false;
776
                }
777
            }
778
        }
779 99
        return true;
780
    }
781
782
    /**
783
     * @param PhoneNumber $number
784
     * @param PhoneNumberUtil $util
785
     * @return bool
786
     */
787 99
    public static function isNationalPrefixPresentIfRequired(PhoneNumber $number, PhoneNumberUtil $util)
788
    {
789
        // First, check how we deduced the country code. If it was written in international format, then
790
        // the national prefix is not required.
791 99
        if ($number->getCountryCodeSource() !== CountryCodeSource::FROM_DEFAULT_COUNTRY) {
792 41
            return true;
793
        }
794
795 65
        $phoneNumberRegion = $util->getRegionCodeForCountryCode($number->getCountryCode());
796 65
        $metadata = $util->getMetadataForRegion($phoneNumberRegion);
797 65
        if ($metadata === null) {
798
            return true;
799
        }
800
801
        // Check if a national prefix should be present when formatting this number.
802 65
        $nationalNumber = $util->getNationalSignificantNumber($number);
803 65
        $formatRule = $util->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
804
        // To do this, we check that a national prefix formatting rule was present and that it wasn't
805
        // just the first-group symbol ($1) with punctuation.
806 65
        if (($formatRule !== null) && \mb_strlen($formatRule->getNationalPrefixFormattingRule()) > 0) {
807 44
            if ($formatRule->getNationalPrefixOptionalWhenFormatting()) {
808
                // The national-prefix is optional in these cases, so we don't need to check if it was
809
                // present.
810 7
                return true;
811
            }
812
813 37
            if (PhoneNumberUtil::formattingRuleHasFirstGroupOnly($formatRule->getNationalPrefixFormattingRule())) {
814
                // National Prefix not needed for this number.
815 3
                return true;
816
            }
817
818
            // Normalize the remainder.
819 34
            $rawInputCopy = PhoneNumberUtil::normalizeDigitsOnly($number->getRawInput());
820 34
            $rawInput = $rawInputCopy;
821
            // Check if we found a national prefix and/or carrier code at the start of the raw input, and
822
            // return the result.
823 34
            $carrierCode = null;
824 34
            return $util->maybeStripNationalPrefixAndCarrierCode($rawInput, $metadata, $carrierCode);
825
        }
826 25
        return true;
827
    }
828
829
830
    /**
831
     * Storage for Alternate Formats
832
     * @var PhoneMetadata[]
833
     */
834
    protected static $callingCodeToAlternateFormatsMap = array();
835
836
    /**
837
     * @param $countryCallingCode
838
     * @return PhoneMetadata|null
839
     */
840 15
    protected static function getAlternateFormatsForCountry($countryCallingCode)
841
    {
842 15
        $countryCodeSet = AlternateFormatsCountryCodeSet::$alternateFormatsCountryCodeSet;
843
844 15
        if (!\in_array($countryCallingCode, $countryCodeSet)) {
845
            return null;
846
        }
847
848 15
        if (!isset(static::$callingCodeToAlternateFormatsMap[$countryCallingCode])) {
849 3
            static::loadAlternateFormatsMetadataFromFile($countryCallingCode);
850
        }
851
852 15
        return static::$callingCodeToAlternateFormatsMap[$countryCallingCode];
853
    }
854
855
    /**
856
     * @param string $countryCallingCode
857
     * @throws \Exception
858
     */
859 3
    protected static function loadAlternateFormatsMetadataFromFile($countryCallingCode)
860
    {
861 3
        $fileName = static::$alternateFormatsFilePrefix . '_' . $countryCallingCode . '.php';
862
863 3
        if (!\is_readable($fileName)) {
864
            throw new \Exception('missing metadata: ' . $fileName);
865
        }
866
867 3
        $metadataLoader = new DefaultMetadataLoader();
868 3
        $data = $metadataLoader->loadMetadata($fileName);
869 3
        $metadata = new PhoneMetadata();
870 3
        $metadata->fromArray($data);
871 3
        static::$callingCodeToAlternateFormatsMap[$countryCallingCode] = $metadata;
872 3
    }
873
874
875
    /**
876
     * Return the current element
877
     * @link http://php.net/manual/en/iterator.current.php
878
     * @return PhoneNumberMatch|null
879
     */
880 199
    public function current()
881
    {
882 199
        return $this->lastMatch;
883
    }
884
885
    /**
886
     * Move forward to next element
887
     * @link http://php.net/manual/en/iterator.next.php
888
     * @return void Any returned value is ignored.
889
     */
890 201
    public function next()
891
    {
892 201
        $this->lastMatch = $this->find($this->searchIndex);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $this->lastMatch is correct as $this->find($this->searchIndex) targeting libphonenumber\PhoneNumberMatcher::find() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
893
894 201
        if ($this->lastMatch === null) {
895 95
            $this->state = 'DONE';
896
        } else {
897 126
            $this->searchIndex = $this->lastMatch->end();
0 ignored issues
show
Bug introduced by
The method end() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

897
            /** @scrutinizer ignore-call */ 
898
            $this->searchIndex = $this->lastMatch->end();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
898 126
            $this->state = 'READY';
899
        }
900
901 201
        $this->searchIndex++;
902 201
    }
903
904
    /**
905
     * Return the key of the current element
906
     * @link http://php.net/manual/en/iterator.key.php
907
     * @return mixed scalar on success, or null on failure.
908
     * @since 5.0.0
909
     */
910
    public function key()
911
    {
912
        return $this->searchIndex;
913
    }
914
915
    /**
916
     * Checks if current position is valid
917
     * @link http://php.net/manual/en/iterator.valid.php
918
     * @return boolean The return value will be casted to boolean and then evaluated.
919
     * Returns true on success or false on failure.
920
     * @since 5.0.0
921
     */
922 29
    public function valid()
923
    {
924 29
        return $this->state === 'READY';
925
    }
926
927
    /**
928
     * Rewind the Iterator to the first element
929
     * @link http://php.net/manual/en/iterator.rewind.php
930
     * @return void Any returned value is ignored.
931
     * @since 5.0.0
932
     */
933 18
    public function rewind()
934
    {
935 18
        $this->searchIndex = 0;
936 18
        $this->next();
937 18
    }
938
}
939