Completed
Push — master ( dd9cf2...939550 )
by Joshua
13s
created

ShortNumberInfo   D

Complexity

Total Complexity 85

Size/Duplication

Total Lines 637
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 10

Test Coverage

Coverage 92.72%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 85
lcom 2
cbo 10
dl 0
loc 637
ccs 191
cts 206
cp 0.9272
rs 4.7215
c 1
b 0
f 0

25 Methods

Rating   Name   Duplication   Size   Complexity  
A getInstance() 0 8 2
A resetInstance() 0 4 1
A getRegionCodesForCountryCode() 0 10 3
A regionDialingFromMatchesNumber() 0 6 1
A getSupportedRegions() 0 4 1
A getExampleShortNumber() 0 14 4
A getMetadataForRegion() 0 14 4
C getExampleShortNumberForCost() 0 30 7
A connectsToEmergencyNumber() 0 4 1
B matchesEmergencyNumberHelper() 0 25 5
A isCarrierSpecificForRegion() 0 12 3
A __construct() 0 12 1
A loadMetadataFromFile() 0 19 4
A isCarrierSpecific() 0 12 2
A isSmsServiceForRegion() 0 14 3
B getRegionCodeForShortNumberFromRegionList() 0 21 6
A isPossibleShortNumber() 0 19 4
A isPossibleShortNumberForRegion() 0 15 3
A isValidShortNumber() 0 12 3
B isValidShortNumberForRegion() 0 23 4
C getExpectedCostForRegion() 0 41 8
D getExpectedCost() 0 32 9
A isEmergencyNumber() 0 4 1
A getNationalSignificantNumber() 0 13 2
A matchesPossibleNumberAndNationalNumber() 0 8 3

How to fix   Complexity   

Complex Class

Complex classes like ShortNumberInfo 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 ShortNumberInfo, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Methods for getting information about short phone numbers, such as short codes and emergency
4
 * numbers. Note that most commercial short numbers are not handled here, but by the
5
 * {@link PhoneNumberUtil}.
6
 *
7
 * @author Shaopeng Jia
8
 * @author David Yonge-Mallo
9
 * @since 5.8
10
 */
11
12
namespace libphonenumber;
13
14
class ShortNumberInfo
15
{
16
    const META_DATA_FILE_PREFIX = 'ShortNumberMetadata';
17
    /**
18
     * @var ShortNumberInfo
19
     */
20
    protected static $instance = null;
21
    /**
22
     * @var MatcherAPIInterface
23
     */
24
    protected $matcherAPI;
25
    protected $currentFilePrefix;
26
    protected $regionToMetadataMap = array();
27
    protected $countryCallingCodeToRegionCodeMap = array();
28
    protected $countryCodeToNonGeographicalMetadataMap = array();
29
    protected static $regionsWhereEmergencyNumbersMustBeExact = array(
30
        'BR',
31
        'CL',
32
        'NI',
33
    );
34
35 30
    protected function __construct(MatcherAPIInterface $matcherAPI)
36
    {
37 30
        $this->matcherAPI = $matcherAPI;
38
39
        // TODO: Create ShortNumberInfo for a given map
40 30
        $this->countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap;
41
42 30
        $this->currentFilePrefix = dirname(__FILE__) . '/data/' . static::META_DATA_FILE_PREFIX;
43
44
        // Initialise PhoneNumberUtil to make sure regex's are setup correctly
45 30
        PhoneNumberUtil::getInstance();
46 30
    }
47
48
    /**
49
     * Returns the singleton instance of ShortNumberInfo
50
     *
51
     * @return \libphonenumber\ShortNumberInfo
52
     */
53 5621
    public static function getInstance()
54
    {
55 5621
        if (null === static::$instance) {
56 30
            static::$instance = new self(RegexBasedMatcher::create());
57
        }
58
59 5621
        return static::$instance;
60
    }
61
62 29
    public static function resetInstance()
63
    {
64 29
        static::$instance = null;
65 29
    }
66
67
    /**
68
     * Returns a list with teh region codes that match the specific country calling code. For
69
     * non-geographical country calling codes, the region code 001 is returned. Also, in the case
70
     * of no region code being found, an empty list is returned.
71
     *
72
     * @param int $countryCallingCode
73
     * @return array
74
     */
75 734
    protected function getRegionCodesForCountryCode($countryCallingCode)
76
    {
77 734
        if (!array_key_exists($countryCallingCode, $this->countryCallingCodeToRegionCodeMap)) {
78 1
            $regionCodes = null;
79
        } else {
80 734
            $regionCodes = $this->countryCallingCodeToRegionCodeMap[$countryCallingCode];
81
        }
82
83 734
        return ($regionCodes === null) ? array() : $regionCodes;
84
    }
85
86
    /**
87
     * Helper method to check that the country calling code of the number matches the region it's
88
     * being dialed from.
89
     * @param PhoneNumber $number
90
     * @param string $regionDialingFrom
91
     * @return bool
92
     */
93 733
    protected function regionDialingFromMatchesNumber(PhoneNumber $number, $regionDialingFrom)
94
    {
95 733
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
96
97 733
        return in_array($regionDialingFrom, $regionCodes);
98
    }
99
100
    public function getSupportedRegions()
101
    {
102
        return ShortNumbersRegionCodeSet::$shortNumbersRegionCodeSet;
103
    }
104
105
    /**
106
     * Gets a valid short number for the specified region.
107
     *
108
     * @param $regionCode String the region for which an example short number is needed
109
     * @return string a valid short number for the specified region. Returns an empty string when the
110
     *      metadata does not contain such information.
111
     */
112 240
    public function getExampleShortNumber($regionCode)
113
    {
114 240
        $phoneMetadata = $this->getMetadataForRegion($regionCode);
115 240
        if ($phoneMetadata === null) {
116 1
            return "";
117
        }
118
119
        /** @var PhoneNumberDesc $desc */
120 240
        $desc = $phoneMetadata->getShortCode();
121 240
        if ($desc !== null && $desc->hasExampleNumber()) {
122 240
            return $desc->getExampleNumber();
123
        }
124
        return "";
125
    }
126
127
    /**
128
     * @param $regionCode
129
     * @return PhoneMetadata|null
130
     */
131 2182
    public function getMetadataForRegion($regionCode)
132
    {
133 2182
        if (!in_array($regionCode, ShortNumbersRegionCodeSet::$shortNumbersRegionCodeSet)) {
134 1
            return null;
135
        }
136
137 2182
        if (!isset($this->regionToMetadataMap[$regionCode])) {
138
            // The regionCode here will be valid and won't be '001', so we don't need to worry about
139
            // what to pass in for the country calling code.
140 261
            $this->loadMetadataFromFile($this->currentFilePrefix, $regionCode, 0);
141
        }
142
143 2182
        return isset($this->regionToMetadataMap[$regionCode]) ? $this->regionToMetadataMap[$regionCode] : null;
144
    }
145
146 261
    protected function loadMetadataFromFile($filePrefix, $regionCode, $countryCallingCode)
147
    {
148 261
        $isNonGeoRegion = PhoneNumberUtil::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode;
149 261
        $fileName = $filePrefix . '_' . ($isNonGeoRegion ? $countryCallingCode : $regionCode) . '.php';
150 261
        if (!is_readable($fileName)) {
151
            throw new \Exception('missing metadata: ' . $fileName);
152
        }
153
154 261
        $metadataLoader = new DefaultMetadataLoader();
155 261
        $data = $metadataLoader->loadMetadata($fileName);
156
157 261
        $metadata = new PhoneMetadata();
158 261
        $metadata->fromArray($data);
159 261
        if ($isNonGeoRegion) {
160
            $this->countryCodeToNonGeographicalMetadataMap[$countryCallingCode] = $metadata;
161
        } else {
162 261
            $this->regionToMetadataMap[$regionCode] = $metadata;
163
        }
164 261
    }
165
166
    /**
167
     *  Gets a valid short number for the specified cost category.
168
     *
169
     * @param string $regionCode the region for which an example short number is needed
170
     * @param int $cost the cost category of number that is needed
171
     * @return string a valid short number for the specified region and cost category. Returns an empty string
172
     * when the metadata does not contain such information, or the cost is UNKNOWN_COST.
173
     */
174 958
    public function getExampleShortNumberForCost($regionCode, $cost)
175
    {
176 958
        $phoneMetadata = $this->getMetadataForRegion($regionCode);
177 958
        if ($phoneMetadata === null) {
178
            return "";
179
        }
180
181
        /** @var PhoneNumberDesc $desc */
182 958
        $desc = null;
183
        switch ($cost) {
184 958
            case ShortNumberCost::TOLL_FREE:
185 241
                $desc = $phoneMetadata->getTollFree();
186 241
                break;
187 719
            case ShortNumberCost::STANDARD_RATE:
188 241
                $desc = $phoneMetadata->getStandardRate();
189 241
                break;
190 480
            case ShortNumberCost::PREMIUM_RATE:
191 241
                $desc = $phoneMetadata->getPremiumRate();
192 241
                break;
193
            default:
194
                // UNKNOWN_COST numbers are computed by the process of elimination from the other cost categories
195 240
                break;
196
        }
197
198 958
        if ($desc !== null && $desc->hasExampleNumber()) {
199 96
            return $desc->getExampleNumber();
200
        }
201
202 863
        return "";
203
    }
204
205
    /**
206
     * Returns true if the given number, exactly as dialed, might be used to connect to an emergency
207
     * service in the given region.
208
     * <p>
209
     * This method accepts a string, rather than a PhoneNumber, because it needs to distinguish
210
     * cases such as "+1 911" and "911", where the former may not connect to an emergency service in
211
     * all cases but the latter would. This method takes into account cases where the number might
212
     * contain formatting, or might have additional digits appended (when it is okay to do that in
213
     * the specified region).
214
     *
215
     * @param string $number the phone number to test
216
     * @param string $regionCode the region where the phone number if being dialled
217
     * @return boolean whether the number might be used to connect to an emergency service in the given region
218
     */
219 10
    public function connectsToEmergencyNumber($number, $regionCode)
220
    {
221 10
        return $this->matchesEmergencyNumberHelper($number, $regionCode, true /* allows prefix match */);
222
    }
223
224
    /**
225
     * @param string $number
226
     * @param string $regionCode
227
     * @param bool $allowPrefixMatch
228
     * @return bool
229
     */
230 263
    protected function matchesEmergencyNumberHelper($number, $regionCode, $allowPrefixMatch)
231
    {
232 263
        $number = PhoneNumberUtil::extractPossibleNumber($number);
233 263
        $matcher = new Matcher(PhoneNumberUtil::$PLUS_CHARS_PATTERN, $number);
234 263
        if ($matcher->lookingAt()) {
235
            // Returns false if the number starts with a plus sign. We don't believe dialing the country
236
            // code before emergency numbers (e.g. +1911) works, but later, if that proves to work, we can
237
            // add additional logic here to handle it.
238 2
            return false;
239
        }
240
241 261
        $metadata = $this->getMetadataForRegion($regionCode);
242 261
        if ($metadata === null || !$metadata->hasEmergency()) {
243
            return false;
244
        }
245
246 261
        $normalizedNumber = PhoneNumberUtil::normalizeDigitsOnly($number);
247 261
        $emergencyDesc = $metadata->getEmergency();
248
249 261
        $allowPrefixMatchForRegion = ($allowPrefixMatch
250 261
            && !in_array($regionCode, static::$regionsWhereEmergencyNumbersMustBeExact)
251
        );
252
253 261
        return $this->matcherAPI->matchNationalNumber($normalizedNumber, $emergencyDesc, $allowPrefixMatchForRegion);
254
    }
255
256
    /**
257
     * Given a valid short number, determines whether it is carrier-specific (however, nothing is
258
     * implied about its validity). Carrier-specific numbers may connect to a different end-point, or
259
     * not connect at all, depending on the user's carrier. If it is important that the number is
260
     * valid, then its validity must first be checked using {@link #isValidShortNumber} or
261
     * {@link #isValidShortNumberForRegion}.
262
     *
263
     * @param PhoneNumber $number the valid short number to check
264
     * @return boolean whether the short number is carrier-specific, assuming the input was a valid short
265
     *     number
266
     */
267 1
    public function isCarrierSpecific(PhoneNumber $number)
268
    {
269 1
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
270 1
        $regionCode = $this->getRegionCodeForShortNumberFromRegionList($number, $regionCodes);
271 1
        $nationalNumber = $this->getNationalSignificantNumber($number);
272 1
        $phoneMetadata = $this->getMetadataForRegion($regionCode);
273
274 1
        return ($phoneMetadata !== null) && ($this->matchesPossibleNumberAndNationalNumber(
275 1
            $nationalNumber,
276 1
            $phoneMetadata->getCarrierSpecific()
277
        ));
278
    }
279
280
    /**
281
     * Given a valid short number, determines whether it is carrier-specific when dialed from the
282
     * given region (however, nothing is implied about its validity). Carrier-specific numbers may
283
     * connect to a different end-point, or not connect at all, depending on the user's carrier. If
284
     * it is important that the number is valid, then its validity must first be checked using
285
     * {@link #isValidShortNumber} or {@link #isValidShortNumberForRegion}. Returns false if the
286
     * number doesn't match the region provided.
287
     * @param PhoneNumber $number The valid short number to check
288
     * @param string $regionDialingFrom The region from which the number is dialed
289
     * @return bool Whether the short number is carrier-specific in the provided region, assuming the
290
     *      input was a valid short number
291
     */
292 73
    public function isCarrierSpecificForRegion(PhoneNumber $number, $regionDialingFrom)
293
    {
294 73
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
295
            return false;
296
        }
297
298 73
        $nationalNumber = $this->getNationalSignificantNumber($number);
299 73
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
300
301 73
        return ($phoneMetadata !== null)
302 73
            && ($this->matchesPossibleNumberAndNationalNumber($nationalNumber, $phoneMetadata->getCarrierSpecific()));
303
    }
304
305
    /**
306
     * Given a valid short number, determines whether it is an SMS service (however, nothing is
307
     * implied about its validity). An SMS service is where the primary or only intended usage is to
308
     * receive and/or send text messages (SMSs). This includes MMS as MMS numbers downgrade to SMS if
309
     * the other party isn't MMS-capable. If it is important that the number is valid, then its
310
     * validity must first be checked using {@link #isValidShortNumber} or {@link
311
     * #isValidShortNumberForRegion}. Returns false if the number doesn't match the region provided.
312
     *
313
     * @param PhoneNumber $number The valid short number to check
314
     * @param string $regionDialingFrom The region from which the number is dialed
315
     * @return bool Whether the short number is an SMS service in the provided region, assuming the input
316
     *  was a valid short number.
317
     */
318 81
    public function isSmsServiceForRegion(PhoneNumber $number, $regionDialingFrom)
319
    {
320 81
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
321
            return false;
322
        }
323
324 81
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
325
326 81
        return ($phoneMetadata !== null)
327 81
            && $this->matchesPossibleNumberAndNationalNumber(
328 81
                $this->getNationalSignificantNumber($number),
329 81
                $phoneMetadata->getSmsServices()
330
            );
331
    }
332
333
    /**
334
     * Helper method to get the region code for a given phone number, from a list of possible region
335
     * codes. If the list contains more than one region, the first region for which the number is
336
     * valid is returned.
337
     *
338
     * @param PhoneNumber $number
339
     * @param $regionCodes
340
     * @return String|null Region Code (or null if none are found)
341
     */
342 244
    protected function getRegionCodeForShortNumberFromRegionList(PhoneNumber $number, $regionCodes)
343
    {
344 244
        if (count($regionCodes) == 0) {
345
            return null;
346 244
        } elseif (count($regionCodes) == 1) {
347 191
            return $regionCodes[0];
348
        }
349
350 54
        $nationalNumber = $this->getNationalSignificantNumber($number);
351
352 54
        foreach ($regionCodes as $regionCode) {
353 54
            $phoneMetadata = $this->getMetadataForRegion($regionCode);
354 54
            if ($phoneMetadata !== null
355 54
                && $this->matchesPossibleNumberAndNationalNumber($nationalNumber, $phoneMetadata->getShortCode())
356
            ) {
357
                // The number is valid for this region.
358 54
                return $regionCode;
359
            }
360
        }
361
        return null;
362
    }
363
364
    /**
365
     * Check whether a short number is a possible number. If a country calling code is shared by
366
     * multiple regions, this returns true if it's possible in any of them. This provides a more
367
     * lenient check than {@link #isValidShortNumber}. See {@link
368
     * #IsPossibleShortNumberForRegion(PhoneNumber, String)} for details.
369
     *
370
     * @param $number PhoneNumber the short number to check
371
     * @return boolean whether the number is a possible short number
372
     */
373 2
    public function isPossibleShortNumber(PhoneNumber $number)
374
    {
375 2
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
376 2
        $shortNumberLength = strlen($this->getNationalSignificantNumber($number));
377
378 2
        foreach ($regionCodes as $region) {
379 2
            $phoneMetadata = $this->getMetadataForRegion($region);
380
381 2
            if ($phoneMetadata === null) {
382
                continue;
383
            }
384
385 2
            if (in_array($shortNumberLength, $phoneMetadata->getGeneralDesc()->getPossibleLength())) {
386 2
                return true;
387
            }
388
        }
389
390 2
        return false;
391
    }
392
393
    /**
394
     * Check whether a short number is a possible number when dialled from a region, given the number
395
     * in the form of a string, and the region where the number is dialled from. This provides a more
396
     * lenient check than {@link #isValidShortNumber}.
397
     *
398
     * @param PhoneNumber $shortNumber The short number to check
399
     * @param string $regionDialingFrom Region dialing From
400
     * @return boolean whether the number is a possible short number
401
     */
402 393
    public function isPossibleShortNumberForRegion(PhoneNumber $shortNumber, $regionDialingFrom)
403
    {
404 393
        if (!$this->regionDialingFromMatchesNumber($shortNumber, $regionDialingFrom)) {
405 1
            return false;
406
        }
407
408 392
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
409
410 392
        if ($phoneMetadata === null) {
411
            return false;
412
        }
413
414 392
        $numberLength = strlen($this->getNationalSignificantNumber($shortNumber));
415 392
        return in_array($numberLength, $phoneMetadata->getGeneralDesc()->getPossibleLength());
416
    }
417
418
    /**
419
     * Tests whether a short number matches a valid pattern. If a country calling code is shared by
420
     * multiple regions, this returns true if it's valid in any of them. Note that this doesn't verify
421
     * the number is actually in use, which is impossible to tell by just looking at the number
422
     * itself. See {@link #isValidShortNumberForRegion(PhoneNumber, String)} for details.
423
     *
424
     * @param $number PhoneNumber the short number for which we want to test the validity
425
     * @return boolean whether the short number matches a valid pattern
426
     */
427 243
    public function isValidShortNumber(PhoneNumber $number)
428
    {
429 243
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
430 243
        $regionCode = $this->getRegionCodeForShortNumberFromRegionList($number, $regionCodes);
431 243
        if (count($regionCodes) > 1 && $regionCode !== null) {
432
            // If a matching region had been found for the phone number from among two or more regions,
433
            // then we have already implicitly verified its validity for that region.
434 53
            return true;
435
        }
436
437 191
        return $this->isValidShortNumberForRegion($number, $regionCode);
438
    }
439
440
    /**
441
     * Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify
442
     * the number is actually in use, which is impossible to tell by just looking at the number
443
     * itself.
444
     *
445
     * @param PhoneNumber $number The Short number for which we want to test the validity
446
     * @param string $regionDialingFrom the region from which the number is dialed
447
     * @return boolean whether the short number matches a valid pattern
448
     */
449 244
    public function isValidShortNumberForRegion(PhoneNumber $number, $regionDialingFrom)
450
    {
451 244
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
452 1
            return false;
453
        }
454 243
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
455
456 243
        if ($phoneMetadata === null) {
457
            return false;
458
        }
459
460 243
        $shortNumber = $this->getNationalSignificantNumber($number);
461
462 243
        $generalDesc = $phoneMetadata->getGeneralDesc();
463
464 243
        if (!$this->matchesPossibleNumberAndNationalNumber($shortNumber, $generalDesc)) {
465 1
            return false;
466
        }
467
468 243
        $shortNumberDesc = $phoneMetadata->getShortCode();
469
470 243
        return $this->matchesPossibleNumberAndNationalNumber($shortNumber, $shortNumberDesc);
471
    }
472
473
    /**
474
     * Gets the expected cost category of a short number  when dialled from a region (however, nothing is
475
     * implied about its validity). If it is important that the number is valid, then its validity
476
     * must first be checked using {@link isValidShortNumberForRegion}. Note that emergency numbers
477
     * are always considered toll-free.
478
     * Example usage:
479
     * <pre>{@code
480
     * $shortInfo = ShortNumberInfo::getInstance();
481
     * $shortNumber = PhoneNumberUtil::parse("110", "US);
482
     * $regionCode = "FR";
483
     * if ($shortInfo->isValidShortNumberForRegion($shortNumber, $regionCode)) {
484
     *     $cost = $shortInfo->getExpectedCostForRegion($shortNumber, $regionCode);
485
     *    // Do something with the cost information here.
486
     * }}</pre>
487
     *
488
     * @param PhoneNumber $number the short number for which we want to know the expected cost category,
489
     *     as a string
490
     * @param string $regionDialingFrom the region from which the number is dialed
491
     * @return int the expected cost category for that region of the short number. Returns UNKNOWN_COST if
492
     *     the number does not match a cost category. Note that an invalid number may match any cost
493
     *     category.
494
     */
495 337
    public function getExpectedCostForRegion(PhoneNumber $number, $regionDialingFrom)
496
    {
497 337
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
498 2
            return ShortNumberCost::UNKNOWN_COST;
499
        }
500
        // Note that regionDialingFrom may be null, in which case phoneMetadata will also be null.
501 336
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
502 336
        if ($phoneMetadata === null) {
503
            return ShortNumberCost::UNKNOWN_COST;
504
        }
505
506 336
        $shortNumber = $this->getNationalSignificantNumber($number);
507
508
        // The possible lengths are not present for a particular sub-type if they match the general
509
        // description; for this reason, we check the possible lengths against the general description
510
        // first to allow an early exit if possible.
511 336
        if (!in_array(strlen($shortNumber), $phoneMetadata->getGeneralDesc()->getPossibleLength())) {
512 1
            return ShortNumberCost::UNKNOWN_COST;
513
        }
514
515
        // The cost categories are tested in order of decreasing expense, since if for some reason the
516
        // patterns overlap the most expensive matching cost category should be returned.
517 336
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getPremiumRate())) {
518 24
            return ShortNumberCost::PREMIUM_RATE;
519
        }
520
521 314
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getStandardRate())) {
522 21
            return ShortNumberCost::STANDARD_RATE;
523
        }
524
525 295
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getTollFree())) {
526 61
            return ShortNumberCost::TOLL_FREE;
527
        }
528
529 237
        if ($this->isEmergencyNumber($shortNumber, $regionDialingFrom)) {
530
            // Emergency numbers are implicitly toll-free.
531 235
            return ShortNumberCost::TOLL_FREE;
532
        }
533
534 3
        return ShortNumberCost::UNKNOWN_COST;
535
    }
536
537
    /**
538
     * Gets the expected cost category of a short number (however, nothing is implied about its
539
     * validity). If the country calling code is unique to a region, this method behaves exactly the
540
     * same as {@link #getExpectedCostForRegion(PhoneNumber, String)}. However, if the country calling
541
     * code is shared by multiple regions, then it returns the highest cost in the sequence
542
     * PREMIUM_RATE, UNKNOWN_COST, STANDARD_RATE, TOLL_FREE. The reason for the position of
543
     * UNKNOWN_COST in this order is that if a number is UNKNOWN_COST in one region but STANDARD_RATE
544
     * or TOLL_FREE in another, its expected cost cannot be estimated as one of the latter since it
545
     * might be a PREMIUM_RATE number.
546
     *
547
     * <p>
548
     * For example, if a number is STANDARD_RATE in the US, but TOLL_FREE in Canada, the expected
549
     * cost returned by this method will be STANDARD_RATE, since the NANPA countries share the same
550
     * country calling code.
551
     * </p>
552
     *
553
     * Note: If the region from which the number is dialed is known, it is highly preferable to call
554
     * {@link #getExpectedCostForRegion(PhoneNumber, String)} instead.
555
     *
556
     * @param PhoneNumber $number the short number for which we want to know the expected cost category
557
     * @return int the highest expected cost category of the short number in the region(s) with the given
558
     *     country calling code
559
     */
560 3
    public function getExpectedCost(PhoneNumber $number)
561
    {
562 3
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
563 3
        if (count($regionCodes) == 0) {
564 1
            return ShortNumberCost::UNKNOWN_COST;
565
        }
566 3
        if (count($regionCodes) == 1) {
567 1
            return $this->getExpectedCostForRegion($number, $regionCodes[0]);
568
        }
569 2
        $cost = ShortNumberCost::TOLL_FREE;
570 2
        foreach ($regionCodes as $regionCode) {
571 2
            $costForRegion = $this->getExpectedCostForRegion($number, $regionCode);
572
            switch ($costForRegion) {
573 2
                case ShortNumberCost::PREMIUM_RATE:
574 1
                    return ShortNumberCost::PREMIUM_RATE;
575
576 2
                case ShortNumberCost::UNKNOWN_COST:
577 1
                    $cost = ShortNumberCost::UNKNOWN_COST;
578 1
                    break;
579
580 2
                case ShortNumberCost::STANDARD_RATE:
581 1
                    if ($cost != ShortNumberCost::UNKNOWN_COST) {
582 1
                        $cost = ShortNumberCost::STANDARD_RATE;
583
                    }
584 1
                    break;
585 2
                case ShortNumberCost::TOLL_FREE:
586
                    // Do nothing
587 2
                    break;
588
            }
589
        }
590 2
        return $cost;
591
    }
592
593
    /**
594
     * Returns true if the given number exactly matches an emergency service number in the given
595
     * region.
596
     * <p>
597
     * This method takes into account cases where the number might contain formatting, but doesn't
598
     * allow additional digits to be appended. Note that {@code isEmergencyNumber(number, region)}
599
     * implies {@code connectsToEmergencyNumber(number, region)}.
600
     *
601
     * @param string $number the phone number to test
602
     * @param string $regionCode the region where the phone number is being dialled
603
     * @return boolean whether the number exactly matches an emergency services number in the given region
604
     */
605 253
    public function isEmergencyNumber($number, $regionCode)
606
    {
607 253
        return $this->matchesEmergencyNumberHelper($number, $regionCode, false /* doesn't allow prefix match */);
608
    }
609
610
    /**
611
     * Gets the national significant number of the a phone number. Note a national significant number
612
     * doesn't contain a national prefix or any formatting.
613
     * <p>
614
     * This is a temporary duplicate of the {@code getNationalSignificantNumber} method from
615
     * {@code PhoneNumberUtil}. Ultimately a canonical static version should exist in a separate
616
     * utility class (to prevent {@code ShortNumberInfo} needing to depend on PhoneNumberUtil).
617
     *
618
     * @param PhoneNumber $number the phone number for which the national significant number is needed
619
     * @return string the national significant number of the PhoneNumber object passed in
620
     */
621 733
    protected function getNationalSignificantNumber(PhoneNumber $number)
622
    {
623
        // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
624 733
        $nationalNumber = '';
625 733
        if ($number->isItalianLeadingZero()) {
626 11
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
627 11
            $nationalNumber .= $zeros;
628
        }
629
630 733
        $nationalNumber .= $number->getNationalNumber();
631
632 733
        return $nationalNumber;
633
    }
634
635
    /**
636
     * TODO: Once we have benchmarked ShortnumberInfo, consider if it is worth keeping
637
     * this performance optimization.
638
     * @param string $number
639
     * @param PhoneNumberDesc $numberDesc
640
     * @return bool
641
     */
642 730
    protected function matchesPossibleNumberAndNationalNumber($number, PhoneNumberDesc $numberDesc)
643
    {
644 730
        if (count($numberDesc->getPossibleLength()) > 0 && !in_array(strlen($number), $numberDesc->getPossibleLength())) {
645 301
            return false;
646
        }
647
648 514
        return $this->matcherAPI->matchNationalNumber($number, $numberDesc, false);
649
    }
650
}
651