Passed
Push — upstream-8.11.0 ( 4431ea )
by Joshua
03:25
created

ShortNumberInfo::isValidShortNumber()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 3
rs 10
c 0
b 0
f 0
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;
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 29
    protected function __construct(MatcherAPIInterface $matcherAPI)
36
    {
37 29
        $this->matcherAPI = $matcherAPI;
38
39
        // TODO: Create ShortNumberInfo for a given map
40 29
        $this->countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap;
41
42 29
        $this->currentFilePrefix = dirname(__FILE__) . '/data/' . static::META_DATA_FILE_PREFIX;
43
44
        // Initialise PhoneNumberUtil to make sure regex's are setup correctly
45 29
        PhoneNumberUtil::getInstance();
46 29
    }
47
48
    /**
49
     * Returns the singleton instance of ShortNumberInfo
50
     *
51
     * @return \libphonenumber\ShortNumberInfo
52
     */
53 5643
    public static function getInstance()
54
    {
55 5643
        if (null === static::$instance) {
56 29
            static::$instance = new self(RegexBasedMatcher::create());
57 29
        }
58
59 5643
        return static::$instance;
60
    }
61
62 28
    public static function resetInstance()
63
    {
64 28
        static::$instance = null;
65 28
    }
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 942
    protected function getRegionCodesForCountryCode($countryCallingCode)
76
    {
77 942
        if (!array_key_exists($countryCallingCode, $this->countryCallingCodeToRegionCodeMap)) {
78 1
            $regionCodes = null;
79 1
        } else {
80 942
            $regionCodes = $this->countryCallingCodeToRegionCodeMap[$countryCallingCode];
81
        }
82
83 942
        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 941
    protected function regionDialingFromMatchesNumber(PhoneNumber $number, $regionDialingFrom)
94
    {
95 941
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
96
97 941
        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 241
    public function getExampleShortNumber($regionCode)
113
    {
114 241
        $phoneMetadata = $this->getMetadataForRegion($regionCode);
115 241
        if ($phoneMetadata === null) {
116 1
            return '';
117
        }
118
119
        /** @var PhoneNumberDesc $desc */
120 241
        $desc = $phoneMetadata->getShortCode();
121 241
        if ($desc !== null && $desc->hasExampleNumber()) {
122 241
            return $desc->getExampleNumber();
123
        }
124
        return '';
125
    }
126
127
    /**
128
     * @param $regionCode
129
     * @return PhoneMetadata|null
130
     */
131 2190
    public function getMetadataForRegion($regionCode)
132
    {
133 2190
        if (!in_array($regionCode, ShortNumbersRegionCodeSet::$shortNumbersRegionCodeSet)) {
134 1
            return null;
135
        }
136
137 2190
        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 261
        }
142
143 2190
        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 961
    public function getExampleShortNumberForCost($regionCode, $cost)
175
    {
176 961
        $phoneMetadata = $this->getMetadataForRegion($regionCode);
177 961
        if ($phoneMetadata === null) {
178
            return '';
179
        }
180
181
        /** @var PhoneNumberDesc $desc */
182 961
        $desc = null;
183
        switch ($cost) {
184 961
            case ShortNumberCost::TOLL_FREE:
185 241
                $desc = $phoneMetadata->getTollFree();
186 241
                break;
187 721
            case ShortNumberCost::STANDARD_RATE:
188 241
                $desc = $phoneMetadata->getStandardRate();
189 241
                break;
190 481
            case ShortNumberCost::PREMIUM_RATE:
191 241
                $desc = $phoneMetadata->getPremiumRate();
192 241
                break;
193 240
            default:
194
                // UNKNOWN_COST numbers are computed by the process of elimination from the other cost categories
195 240
                break;
196 240
        }
197
198 961
        if ($desc !== null && $desc->hasExampleNumber()) {
199 292
            return $desc->getExampleNumber();
200
        }
201
202 669
        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 264
    protected function matchesEmergencyNumberHelper($number, $regionCode, $allowPrefixMatch)
231
    {
232 264
        $number = PhoneNumberUtil::extractPossibleNumber($number);
0 ignored issues
show
Bug introduced by
$number of type string is incompatible with the type integer expected by parameter $number of libphonenumber\PhoneNumb...extractPossibleNumber(). ( Ignorable by Annotation )

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

232
        $number = PhoneNumberUtil::extractPossibleNumber(/** @scrutinizer ignore-type */ $number);
Loading history...
233 264
        $matcher = new Matcher(PhoneNumberUtil::$PLUS_CHARS_PATTERN, $number);
234 264
        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 262
        $metadata = $this->getMetadataForRegion($regionCode);
242 262
        if ($metadata === null || !$metadata->hasEmergency()) {
243
            return false;
244
        }
245
246 262
        $normalizedNumber = PhoneNumberUtil::normalizeDigitsOnly($number);
247 262
        $emergencyDesc = $metadata->getEmergency();
248
249
        $allowPrefixMatchForRegion = ($allowPrefixMatch
250 262
            && !in_array($regionCode, static::$regionsWhereEmergencyNumbersMustBeExact)
251 262
        );
252
253 262
        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 1
        );
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 81
    public function isCarrierSpecificForRegion(PhoneNumber $number, $regionDialingFrom)
293
    {
294 81
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
295
            return false;
296
        }
297
298 81
        $nationalNumber = $this->getNationalSignificantNumber($number);
299 81
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
300
301 81
        return ($phoneMetadata !== null)
302 81
            && $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 82
    public function isSmsServiceForRegion(PhoneNumber $number, $regionDialingFrom)
319
    {
320 82
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
321
            return false;
322
        }
323
324 82
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
325
326 82
        return ($phoneMetadata !== null)
327 82
            && $this->matchesPossibleNumberAndNationalNumber(
328 82
                $this->getNationalSignificantNumber($number),
329 82
                $phoneMetadata->getSmsServices()
330 82
            );
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 245
    protected function getRegionCodeForShortNumberFromRegionList(PhoneNumber $number, $regionCodes)
343
    {
344 245
        if (count($regionCodes) == 0) {
345
            return null;
346
        }
347
348 245
        if (count($regionCodes) == 1) {
349 192
            return $regionCodes[0];
350
        }
351
352 54
        $nationalNumber = $this->getNationalSignificantNumber($number);
353
354 54
        foreach ($regionCodes as $regionCode) {
355 54
            $phoneMetadata = $this->getMetadataForRegion($regionCode);
356
            if ($phoneMetadata !== null
357 54
                && $this->matchesPossibleNumberAndNationalNumber($nationalNumber, $phoneMetadata->getShortCode())
358 54
            ) {
359
                // The number is valid for this region.
360 54
                return $regionCode;
361
            }
362 9
        }
363
        return null;
364
    }
365
366
    /**
367
     * Check whether a short number is a possible number. If a country calling code is shared by
368
     * multiple regions, this returns true if it's possible in any of them. This provides a more
369
     * lenient check than {@link #isValidShortNumber}. See {@link
370
     * #IsPossibleShortNumberForRegion(PhoneNumber, String)} for details.
371
     *
372
     * @param $number PhoneNumber the short number to check
373
     * @return boolean whether the number is a possible short number
374
     */
375 2
    public function isPossibleShortNumber(PhoneNumber $number)
376
    {
377 2
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
378 2
        $shortNumberLength = strlen($this->getNationalSignificantNumber($number));
379
380 2
        foreach ($regionCodes as $region) {
381 2
            $phoneMetadata = $this->getMetadataForRegion($region);
382
383 2
            if ($phoneMetadata === null) {
384
                continue;
385
            }
386
387 2
            if (in_array($shortNumberLength, $phoneMetadata->getGeneralDesc()->getPossibleLength())) {
388 1
                return true;
389
            }
390 2
        }
391
392 2
        return false;
393
    }
394
395
    /**
396
     * Check whether a short number is a possible number when dialled from a region, given the number
397
     * in the form of a string, and the region where the number is dialled from. This provides a more
398
     * lenient check than {@link #isValidShortNumber}.
399
     *
400
     * @param PhoneNumber $shortNumber The short number to check
401
     * @param string $regionDialingFrom Region dialing From
402
     * @return boolean whether the number is a possible short number
403
     */
404 403
    public function isPossibleShortNumberForRegion(PhoneNumber $shortNumber, $regionDialingFrom)
405
    {
406 403
        if (!$this->regionDialingFromMatchesNumber($shortNumber, $regionDialingFrom)) {
407 1
            return false;
408
        }
409
410 402
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
411
412 402
        if ($phoneMetadata === null) {
413
            return false;
414
        }
415
416 402
        $numberLength = strlen($this->getNationalSignificantNumber($shortNumber));
417 402
        return in_array($numberLength, $phoneMetadata->getGeneralDesc()->getPossibleLength());
418
    }
419
420
    /**
421
     * Tests whether a short number matches a valid pattern. If a country calling code is shared by
422
     * multiple regions, this returns true if it's valid in any of them. Note that this doesn't verify
423
     * the number is actually in use, which is impossible to tell by just looking at the number
424
     * itself. See {@link #isValidShortNumberForRegion(PhoneNumber, String)} for details.
425
     *
426
     * @param $number PhoneNumber the short number for which we want to test the validity
427
     * @return boolean whether the short number matches a valid pattern
428
     */
429 244
    public function isValidShortNumber(PhoneNumber $number)
430
    {
431 244
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
432 244
        $regionCode = $this->getRegionCodeForShortNumberFromRegionList($number, $regionCodes);
433 244
        if (count($regionCodes) > 1 && $regionCode !== null) {
434
            // If a matching region had been found for the phone number from among two or more regions,
435
            // then we have already implicitly verified its validity for that region.
436 53
            return true;
437
        }
438
439 192
        return $this->isValidShortNumberForRegion($number, $regionCode);
440
    }
441
442
    /**
443
     * Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify
444
     * the number is actually in use, which is impossible to tell by just looking at the number
445
     * itself.
446
     *
447
     * @param PhoneNumber $number The Short number for which we want to test the validity
448
     * @param string $regionDialingFrom the region from which the number is dialed
449
     * @return boolean whether the short number matches a valid pattern
450
     */
451 245
    public function isValidShortNumberForRegion(PhoneNumber $number, $regionDialingFrom)
452
    {
453 245
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
454 1
            return false;
455
        }
456 244
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
457
458 244
        if ($phoneMetadata === null) {
459
            return false;
460
        }
461
462 244
        $shortNumber = $this->getNationalSignificantNumber($number);
463
464 244
        $generalDesc = $phoneMetadata->getGeneralDesc();
465
466 244
        if (!$this->matchesPossibleNumberAndNationalNumber($shortNumber, $generalDesc)) {
467 1
            return false;
468
        }
469
470 244
        $shortNumberDesc = $phoneMetadata->getShortCode();
471
472 244
        return $this->matchesPossibleNumberAndNationalNumber($shortNumber, $shortNumberDesc);
473
    }
474
475
    /**
476
     * Gets the expected cost category of a short number  when dialled from a region (however, nothing is
477
     * implied about its validity). If it is important that the number is valid, then its validity
478
     * must first be checked using {@link isValidShortNumberForRegion}. Note that emergency numbers
479
     * are always considered toll-free.
480
     * Example usage:
481
     * <pre>{@code
482
     * $shortInfo = ShortNumberInfo::getInstance();
483
     * $shortNumber = PhoneNumberUtil::parse("110", "US);
484
     * $regionCode = "FR";
485
     * if ($shortInfo->isValidShortNumberForRegion($shortNumber, $regionCode)) {
486
     *     $cost = $shortInfo->getExpectedCostForRegion($shortNumber, $regionCode);
487
     *    // Do something with the cost information here.
488
     * }}</pre>
489
     *
490
     * @param PhoneNumber $number the short number for which we want to know the expected cost category,
491
     *     as a string
492
     * @param string $regionDialingFrom the region from which the number is dialed
493
     * @return int the expected cost category for that region of the short number. Returns UNKNOWN_COST if
494
     *     the number does not match a cost category. Note that an invalid number may match any cost
495
     *     category.
496
     */
497 535
    public function getExpectedCostForRegion(PhoneNumber $number, $regionDialingFrom)
498
    {
499 535
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
500 2
            return ShortNumberCost::UNKNOWN_COST;
501
        }
502
        // Note that regionDialingFrom may be null, in which case phoneMetadata will also be null.
503 534
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
504 534
        if ($phoneMetadata === null) {
505
            return ShortNumberCost::UNKNOWN_COST;
506
        }
507
508 534
        $shortNumber = $this->getNationalSignificantNumber($number);
509
510
        // The possible lengths are not present for a particular sub-type if they match the general
511
        // description; for this reason, we check the possible lengths against the general description
512
        // first to allow an early exit if possible.
513 534
        if (!in_array(strlen($shortNumber), $phoneMetadata->getGeneralDesc()->getPossibleLength())) {
514 1
            return ShortNumberCost::UNKNOWN_COST;
515
        }
516
517
        // The cost categories are tested in order of decreasing expense, since if for some reason the
518
        // patterns overlap the most expensive matching cost category should be returned.
519 534
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getPremiumRate())) {
520 29
            return ShortNumberCost::PREMIUM_RATE;
521
        }
522
523 507
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getStandardRate())) {
524 27
            return ShortNumberCost::STANDARD_RATE;
525
        }
526
527 482
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getTollFree())) {
528 482
            return ShortNumberCost::TOLL_FREE;
529
        }
530
531 3
        if ($this->isEmergencyNumber($shortNumber, $regionDialingFrom)) {
532
            // Emergency numbers are implicitly toll-free.
533
            return ShortNumberCost::TOLL_FREE;
534
        }
535
536 3
        return ShortNumberCost::UNKNOWN_COST;
537
    }
538
539
    /**
540
     * Gets the expected cost category of a short number (however, nothing is implied about its
541
     * validity). If the country calling code is unique to a region, this method behaves exactly the
542
     * same as {@link #getExpectedCostForRegion(PhoneNumber, String)}. However, if the country calling
543
     * code is shared by multiple regions, then it returns the highest cost in the sequence
544
     * PREMIUM_RATE, UNKNOWN_COST, STANDARD_RATE, TOLL_FREE. The reason for the position of
545
     * UNKNOWN_COST in this order is that if a number is UNKNOWN_COST in one region but STANDARD_RATE
546
     * or TOLL_FREE in another, its expected cost cannot be estimated as one of the latter since it
547
     * might be a PREMIUM_RATE number.
548
     *
549
     * <p>
550
     * For example, if a number is STANDARD_RATE in the US, but TOLL_FREE in Canada, the expected
551
     * cost returned by this method will be STANDARD_RATE, since the NANPA countries share the same
552
     * country calling code.
553
     * </p>
554
     *
555
     * Note: If the region from which the number is dialed is known, it is highly preferable to call
556
     * {@link #getExpectedCostForRegion(PhoneNumber, String)} instead.
557
     *
558
     * @param PhoneNumber $number the short number for which we want to know the expected cost category
559
     * @return int the highest expected cost category of the short number in the region(s) with the given
560
     *     country calling code
561
     */
562 3
    public function getExpectedCost(PhoneNumber $number)
563
    {
564 3
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
565 3
        if (count($regionCodes) == 0) {
566 1
            return ShortNumberCost::UNKNOWN_COST;
567
        }
568 3
        if (count($regionCodes) == 1) {
569 1
            return $this->getExpectedCostForRegion($number, $regionCodes[0]);
570
        }
571 2
        $cost = ShortNumberCost::TOLL_FREE;
572 2
        foreach ($regionCodes as $regionCode) {
573 2
            $costForRegion = $this->getExpectedCostForRegion($number, $regionCode);
574
            switch ($costForRegion) {
575 2
                case ShortNumberCost::PREMIUM_RATE:
576 1
                    return ShortNumberCost::PREMIUM_RATE;
577
578 2
                case ShortNumberCost::UNKNOWN_COST:
579 1
                    $cost = ShortNumberCost::UNKNOWN_COST;
580 1
                    break;
581
582 2
                case ShortNumberCost::STANDARD_RATE:
583 1
                    if ($cost != ShortNumberCost::UNKNOWN_COST) {
584 1
                        $cost = ShortNumberCost::STANDARD_RATE;
585 1
                    }
586 1
                    break;
587 2
                case ShortNumberCost::TOLL_FREE:
588
                    // Do nothing
589 2
                    break;
590
            }
591 2
        }
592 2
        return $cost;
593
    }
594
595
    /**
596
     * Returns true if the given number exactly matches an emergency service number in the given
597
     * region.
598
     * <p>
599
     * This method takes into account cases where the number might contain formatting, but doesn't
600
     * allow additional digits to be appended. Note that {@code isEmergencyNumber(number, region)}
601
     * implies {@code connectsToEmergencyNumber(number, region)}.
602
     *
603
     * @param string $number the phone number to test
604
     * @param string $regionCode the region where the phone number is being dialled
605
     * @return boolean whether the number exactly matches an emergency services number in the given region
606
     */
607 254
    public function isEmergencyNumber($number, $regionCode)
608
    {
609 254
        return $this->matchesEmergencyNumberHelper($number, $regionCode, false /* doesn't allow prefix match */);
610
    }
611
612
    /**
613
     * Gets the national significant number of the a phone number. Note a national significant number
614
     * doesn't contain a national prefix or any formatting.
615
     * <p>
616
     * This is a temporary duplicate of the {@code getNationalSignificantNumber} method from
617
     * {@code PhoneNumberUtil}. Ultimately a canonical static version should exist in a separate
618
     * utility class (to prevent {@code ShortNumberInfo} needing to depend on PhoneNumberUtil).
619
     *
620
     * @param PhoneNumber $number the phone number for which the national significant number is needed
621
     * @return string the national significant number of the PhoneNumber object passed in
622
     */
623 941
    protected function getNationalSignificantNumber(PhoneNumber $number)
624
    {
625
        // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
626 941
        $nationalNumber = '';
627 941
        if ($number->isItalianLeadingZero()) {
628 48
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
629 48
            $nationalNumber .= $zeros;
630 48
        }
631
632 941
        $nationalNumber .= $number->getNationalNumber();
633
634 941
        return $nationalNumber;
635
    }
636
637
    /**
638
     * TODO: Once we have benchmarked ShortnumberInfo, consider if it is worth keeping
639
     * this performance optimization.
640
     * @param string $number
641
     * @param PhoneNumberDesc $numberDesc
642
     * @return bool
643
     */
644 938
    protected function matchesPossibleNumberAndNationalNumber($number, PhoneNumberDesc $numberDesc)
645
    {
646 938
        if (count($numberDesc->getPossibleLength()) > 0 && !in_array(strlen($number), $numberDesc->getPossibleLength())) {
647 491
            return false;
648
        }
649
650 938
        return $this->matcherAPI->matchNationalNumber($number, $numberDesc, false);
651
    }
652
}
653