-
Notifications
You must be signed in to change notification settings - Fork 470
/
Copy pathMultiFileMetadataSourceImpl.php
90 lines (71 loc) · 2.88 KB
/
MultiFileMetadataSourceImpl.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
declare(strict_types=1);
/**
* @author joshuag
* @created: 04/08/2015 09:03
* @project libphonenumber-for-php
*/
namespace libphonenumber;
use RuntimeException;
/**
* @internal
*/
class MultiFileMetadataSourceImpl implements MetadataSourceInterface
{
/**
* A mapping from a region code to the PhoneMetadata for that region.
* @var PhoneMetadata[]
*/
protected array $regionToMetadataMap = [];
/**
* A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
* that country calling code. Examples of the country calling codes include 800 (International
* Toll Free Service) and 808 (International Shared Cost Service).
* @var PhoneMetadata[]
*/
protected array $countryCodeToNonGeographicalMetadataMap = [];
/**
* @param string $currentFilePrefix The prefix of the metadata class names from which region data is loaded
*/
public function __construct(
protected readonly string $currentFilePrefix = __NAMESPACE__ . '\data\PhoneNumberMetadata_'
) {}
public function getMetadataForRegion(string $regionCode): PhoneMetadata
{
$regionCode = strtoupper($regionCode);
if (!isset($this->regionToMetadataMap[$regionCode])) {
// The regionCode here will be valid and won't be '001', so we don't need to worry about
// what to pass in for the country calling code.
$this->loadMetadataFromFile($this->currentFilePrefix, $regionCode, 0);
}
return $this->regionToMetadataMap[$regionCode];
}
public function getMetadataForNonGeographicalRegion(int $countryCallingCode): PhoneMetadata
{
if (!isset($this->countryCodeToNonGeographicalMetadataMap[$countryCallingCode])) {
$this->loadMetadataFromFile($this->currentFilePrefix, PhoneNumberUtil::REGION_CODE_FOR_NON_GEO_ENTITY, $countryCallingCode);
}
return $this->countryCodeToNonGeographicalMetadataMap[$countryCallingCode];
}
/**
* @throws RuntimeException
*/
public function loadMetadataFromFile(string $filePrefix, string $regionCode, int $countryCallingCode): void
{
$regionCode = strtoupper($regionCode);
$isNonGeoRegion = PhoneNumberUtil::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode;
$class = $filePrefix . ($isNonGeoRegion ? $countryCallingCode : ucfirst($regionCode));
if (!class_exists($class)) {
throw new RuntimeException('missing metadata: ' . $class);
}
$metadata = new $class();
if (!$metadata instanceof PhoneMetadata) {
throw new RuntimeException('invalid metadata: ' . $class);
}
if ($isNonGeoRegion) {
$this->countryCodeToNonGeographicalMetadataMap[$countryCallingCode] = $metadata;
} else {
$this->regionToMetadataMap[$regionCode] = $metadata;
}
}
}