Passed
Push — master ( 1fe033...85608f )
by Joshua
08:13
created

ShortNumberInfo::getExpectedCost()   D

Complexity

Conditions 9
Paths 9

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 21
nc 9
nop 1
dl 0
loc 31
ccs 3
cts 3
cp 1
crap 9
rs 4.909
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 = 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 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 5373
    public static function getInstance()
54
    {
55 5373
        if (null === static::$instance) {
56 29
            static::$instance = new self(RegexBasedMatcher::create());
57
        }
58
59 5373
        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 641
    protected function getRegionCodesForCountryCode($countryCallingCode)
76
    {
77 641
        if (!array_key_exists($countryCallingCode, $this->countryCallingCodeToRegionCodeMap)) {
78 1
            $regionCodes = null;
79
        } else {
80 641
            $regionCodes = $this->countryCallingCodeToRegionCodeMap[$countryCallingCode];
81
        }
82
83 641
        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 640
    protected function regionDialingFromMatchesNumber(PhoneNumber $number, $regionDialingFrom)
94
    {
95 640
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
96
97 640
        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 239
    public function getExampleShortNumber($regionCode)
113
    {
114 239
        $phoneMetadata = $this->getMetadataForRegion($regionCode);
115 239
        if ($phoneMetadata === null) {
116 1
            return "";
117
        }
118
119
        /** @var PhoneNumberDesc $desc */
120 239
        $desc = $phoneMetadata->getShortCode();
121 239
        if ($desc !== null && $desc->hasExampleNumber()) {
122 239
            return $desc->getExampleNumber();
123
        }
124
        return "";
125
    }
126
127
    /**
128
     * @param $regionCode
129
     * @return PhoneMetadata|null
130
     */
131 1934
    public function getMetadataForRegion($regionCode)
132
    {
133 1934
        if (!in_array($regionCode, ShortNumbersRegionCodeSet::$shortNumbersRegionCodeSet)) {
134 1
            return null;
135
        }
136
137 1934
        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 259
            $this->loadMetadataFromFile($this->currentFilePrefix, $regionCode, 0);
141
        }
142
143 1934
        return isset($this->regionToMetadataMap[$regionCode]) ? $this->regionToMetadataMap[$regionCode] : null;
144
    }
145
146 259
    protected function loadMetadataFromFile($filePrefix, $regionCode, $countryCallingCode)
147
    {
148 259
        $isNonGeoRegion = PhoneNumberUtil::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode;
149 259
        $fileName = $filePrefix . '_' . ($isNonGeoRegion ? $countryCallingCode : $regionCode) . '.php';
150 259
        if (!is_readable($fileName)) {
151
            throw new \Exception('missing metadata: ' . $fileName);
152
        }
153
154 259
        $metadataLoader = new DefaultMetadataLoader();
155 259
        $data = $metadataLoader->loadMetadata($fileName);
156
157 259
        $metadata = new PhoneMetadata();
158 259
        $metadata->fromArray($data);
159 259
        if ($isNonGeoRegion) {
160
            $this->countryCodeToNonGeographicalMetadataMap[$countryCallingCode] = $metadata;
161
        } else {
162 259
            $this->regionToMetadataMap[$regionCode] = $metadata;
163
        }
164 259
    }
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 954
    public function getExampleShortNumberForCost($regionCode, $cost)
175
    {
176 954
        $phoneMetadata = $this->getMetadataForRegion($regionCode);
177 954
        if ($phoneMetadata === null) {
178
            return "";
179
        }
180
181
        /** @var PhoneNumberDesc $desc */
182 954
        $desc = null;
183
        switch ($cost) {
184 954
            case ShortNumberCost::TOLL_FREE:
185 240
                $desc = $phoneMetadata->getTollFree();
186 240
                break;
187 716
            case ShortNumberCost::STANDARD_RATE:
188 240
                $desc = $phoneMetadata->getStandardRate();
189 240
                break;
190 478
            case ShortNumberCost::PREMIUM_RATE:
191 240
                $desc = $phoneMetadata->getPremiumRate();
192 240
                break;
193
            default:
194
                // UNKNOWN_COST numbers are computed by the process of elimination from the other cost categories
195 239
                break;
196
        }
197
198 954
        if ($desc !== null && $desc->hasExampleNumber()) {
199 90
            return $desc->getExampleNumber();
200
        }
201
202 865
        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 262
    protected function matchesEmergencyNumberHelper($number, $regionCode, $allowPrefixMatch)
231
    {
232 262
        $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 262
        $matcher = new Matcher(PhoneNumberUtil::$PLUS_CHARS_PATTERN, $number);
234 262
        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 260
        $metadata = $this->getMetadataForRegion($regionCode);
242 260
        if ($metadata === null || !$metadata->hasEmergency()) {
243
            return false;
244
        }
245
246 260
        $normalizedNumber = PhoneNumberUtil::normalizeDigitsOnly($number);
247 260
        $emergencyDesc = $metadata->getEmergency();
248
249 260
        $allowPrefixMatchForRegion = ($allowPrefixMatch
250 260
            && !in_array($regionCode, static::$regionsWhereEmergencyNumbersMustBeExact)
251
        );
252
253 260
        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
            $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 69
    public function isCarrierSpecificForRegion(PhoneNumber $number, $regionDialingFrom)
293
    {
294 69
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
295
            return false;
296
        }
297
298 69
        $nationalNumber = $this->getNationalSignificantNumber($number);
299 69
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
300
301 69
        return ($phoneMetadata !== null)
302 69
            && ($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 243
     * @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 243
     *  was a valid short number.
317
     */
318 243
    public function isSmsServiceForRegion(PhoneNumber $number, $regionDialingFrom)
319 190
    {
320
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
321
            return false;
322 54
        }
323
324 54
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
325 54
326 54
        return ($phoneMetadata !== null)
327 54
            && $this->matchesPossibleNumberAndNationalNumber(
328
                $this->getNationalSignificantNumber($number),
329
                $phoneMetadata->getSmsServices()
330 54
            );
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
    protected function getRegionCodeForShortNumberFromRegionList(PhoneNumber $number, $regionCodes)
343
    {
344
        if (count($regionCodes) == 0) {
345 2
            return null;
346
        } elseif (count($regionCodes) == 1) {
347 2
            return $regionCodes[0];
348 2
        }
349
350 2
        $nationalNumber = $this->getNationalSignificantNumber($number);
351 2
352
        foreach ($regionCodes as $regionCode) {
353 2
            $phoneMetadata = $this->getMetadataForRegion($regionCode);
354
            if ($phoneMetadata !== null
355
                && $this->matchesPossibleNumberAndNationalNumber($nationalNumber, $phoneMetadata->getShortCode())
356
            ) {
357 2
                // The number is valid for this region.
358 2
                return $regionCode;
359
            }
360
        }
361
        return null;
362 2
    }
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
    public function isPossibleShortNumber(PhoneNumber $number)
374 308
    {
375
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
376 308
        $shortNumberLength = strlen($this->getNationalSignificantNumber($number));
377 1
378
        foreach ($regionCodes as $region) {
379
            $phoneMetadata = $this->getMetadataForRegion($region);
380 307
381
            if ($phoneMetadata === null) {
382 307
                continue;
383
            }
384
385
            if (in_array($shortNumberLength, $phoneMetadata->getGeneralDesc()->getPossibleLength())) {
386 307
                return true;
387 307
            }
388
        }
389
390
        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 242
     * @param string $regionDialingFrom Region dialing From
400
     * @return boolean whether the number is a possible short number
401 242
     */
402 242
    public function isPossibleShortNumberForRegion(PhoneNumber $shortNumber, $regionDialingFrom)
403 242
    {
404
        if (!$this->regionDialingFromMatchesNumber($shortNumber, $regionDialingFrom)) {
405
            return false;
406 53
        }
407
408
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
409 190
410
        if ($phoneMetadata === null) {
411
            return false;
412
        }
413
414
        $numberLength = strlen($this->getNationalSignificantNumber($shortNumber));
415
        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 243
     * 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 243
     *
424 1
     * @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 242
     */
427
    public function isValidShortNumber(PhoneNumber $number)
428 242
    {
429
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
430
        $regionCode = $this->getRegionCodeForShortNumberFromRegionList($number, $regionCodes);
431
        if (count($regionCodes) > 1 && $regionCode !== null) {
432 242
            // 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 242
            return true;
435
        }
436 242
437 1
        return $this->isValidShortNumberForRegion($number, $regionCode);
438
    }
439
440 242
    /**
441
     * Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify
442 242
     * 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
    public function isValidShortNumberForRegion(PhoneNumber $number, $regionDialingFrom)
450
    {
451
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
452
            return false;
453
        }
454
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
455
456
        if ($phoneMetadata === null) {
457
            return false;
458
        }
459
460
        $shortNumber = $this->getNationalSignificantNumber($number);
461
462
        $generalDesc = $phoneMetadata->getGeneralDesc();
463
464
        if (!$this->matchesPossibleNumberAndNationalNumber($shortNumber, $generalDesc)) {
465
            return false;
466
        }
467 330
468
        $shortNumberDesc = $phoneMetadata->getShortCode();
469 330
470 2
        return $this->matchesPossibleNumberAndNationalNumber($shortNumber, $shortNumberDesc);
471
    }
472
473 329
    /**
474 329
     * 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 329
     * Example usage:
479
     * <pre>{@code
480
     * $shortInfo = ShortNumberInfo::getInstance();
481
     * $shortNumber = PhoneNumberUtil::parse("110", "US);
482
     * $regionCode = "FR";
483 329
     * if ($shortInfo->isValidShortNumberForRegion($shortNumber, $regionCode)) {
484 1
     *     $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 329
     *     as a string
490 21
     * @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 310
     *     category.
494 21
     */
495
    public function getExpectedCostForRegion(PhoneNumber $number, $regionDialingFrom)
496
    {
497 291
        if (!$this->regionDialingFromMatchesNumber($number, $regionDialingFrom)) {
498 56
            return ShortNumberCost::UNKNOWN_COST;
499
        }
500
        // Note that regionDialingFrom may be null, in which case phoneMetadata will also be null.
501 238
        $phoneMetadata = $this->getMetadataForRegion($regionDialingFrom);
502
        if ($phoneMetadata === null) {
503 236
            return ShortNumberCost::UNKNOWN_COST;
504
        }
505
506 3
        $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
        if (!in_array(strlen($shortNumber), $phoneMetadata->getGeneralDesc()->getPossibleLength())) {
512
            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
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getPremiumRate())) {
518
            return ShortNumberCost::PREMIUM_RATE;
519
        }
520
521
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getStandardRate())) {
522
            return ShortNumberCost::STANDARD_RATE;
523
        }
524
525
        if ($this->matchesPossibleNumberAndNationalNumber($shortNumber, $phoneMetadata->getTollFree())) {
526
            return ShortNumberCost::TOLL_FREE;
527
        }
528
529
        if ($this->isEmergencyNumber($shortNumber, $regionDialingFrom)) {
530
            // Emergency numbers are implicitly toll-free.
531
            return ShortNumberCost::TOLL_FREE;
532 3
        }
533
534 3
        return ShortNumberCost::UNKNOWN_COST;
535 3
    }
536 1
537
    /**
538 3
     * Gets the expected cost category of a short number (however, nothing is implied about its
539 1
     * 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 2
     * code is shared by multiple regions, then it returns the highest cost in the sequence
542 2
     * PREMIUM_RATE, UNKNOWN_COST, STANDARD_RATE, TOLL_FREE. The reason for the position of
543 2
     * 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 2
     * might be a PREMIUM_RATE number.
546 1
     *
547
     * <p>
548 2
     * For example, if a number is STANDARD_RATE in the US, but TOLL_FREE in Canada, the expected
549 1
     * cost returned by this method will be STANDARD_RATE, since the NANPA countries share the same
550 1
     * country calling code.
551
     * </p>
552 2
     *
553 1
     * Note: If the region from which the number is dialed is known, it is highly preferable to call
554 1
     * {@link #getExpectedCostForRegion(PhoneNumber, String)} instead.
555
     *
556 1
     * @param PhoneNumber $number the short number for which we want to know the expected cost category
557 2
     * @return int the highest expected cost category of the short number in the region(s) with the given
558
     *     country calling code
559 2
     */
560
    public function getExpectedCost(PhoneNumber $number)
561
    {
562 2
        $regionCodes = $this->getRegionCodesForCountryCode($number->getCountryCode());
563
        if (count($regionCodes) == 0) {
564
            return ShortNumberCost::UNKNOWN_COST;
565
        }
566
        if (count($regionCodes) == 1) {
567
            return $this->getExpectedCostForRegion($number, $regionCodes[0]);
568
        }
569
        $cost = ShortNumberCost::TOLL_FREE;
570
        foreach ($regionCodes as $regionCode) {
571
            $costForRegion = $this->getExpectedCostForRegion($number, $regionCode);
572
            switch ($costForRegion) {
573
                case ShortNumberCost::PREMIUM_RATE:
574
                    return ShortNumberCost::PREMIUM_RATE;
575
576
                case ShortNumberCost::UNKNOWN_COST:
577 252
                    $cost = ShortNumberCost::UNKNOWN_COST;
578
                    break;
579 252
580
                case ShortNumberCost::STANDARD_RATE:
581
                    if ($cost != ShortNumberCost::UNKNOWN_COST) {
582
                        $cost = ShortNumberCost::STANDARD_RATE;
583
                    }
584
                    break;
585
                case ShortNumberCost::TOLL_FREE:
586
                    // Do nothing
587
                    break;
588
            }
589
        }
590
        return $cost;
591
    }
592
593 640
    /**
594
     * Returns true if the given number exactly matches an emergency service number in the given
595
     * region.
596 640
     * <p>
597 640
     * This method takes into account cases where the number might contain formatting, but doesn't
598 11
     * allow additional digits to be appended. Note that {@code isEmergencyNumber(number, region)}
599 11
     * implies {@code connectsToEmergencyNumber(number, region)}.
600
     *
601
     * @param string $number the phone number to test
602 640
     * @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 640
     */
605
    public function isEmergencyNumber($number, $regionCode)
606
    {
607
        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 637
     * 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 637
     * utility class (to prevent {@code ShortNumberInfo} needing to depend on PhoneNumberUtil).
617 297
     *
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 419
     */
621
    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
        $nationalNumber = '';
625
        if ($number->isItalianLeadingZero()) {
626
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
627
            $nationalNumber .= $zeros;
628
        }
629
630
        $nationalNumber .= $number->getNationalNumber();
631
632
        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
    protected function matchesPossibleNumberAndNationalNumber($number, PhoneNumberDesc $numberDesc)
643
    {
644
        if (count($numberDesc->getPossibleLength()) > 0 && !in_array(strlen($number), $numberDesc->getPossibleLength())) {
645
            return false;
646
        }
647
648
        return $this->matcherAPI->matchNationalNumber($number, $numberDesc, false);
649
    }
650
}
651