|
1
|
|
|
<?php namespace Propaganistas\LaravelPhone\Traits; |
|
2
|
|
|
|
|
3
|
|
|
use Illuminate\Support\Arr; |
|
4
|
|
|
use Illuminate\Support\Collection; |
|
5
|
|
|
use libphonenumber\PhoneNumberType; |
|
6
|
|
|
use ReflectionClass; |
|
7
|
|
|
|
|
8
|
|
|
trait ParsesTypes |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* Array of available phone types. |
|
12
|
|
|
* |
|
13
|
|
|
* @var array |
|
14
|
|
|
*/ |
|
15
|
|
|
protected static $resolvedTypes; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Determine whether the given type is valid. |
|
19
|
|
|
* |
|
20
|
|
|
* @param string $type |
|
21
|
|
|
* @return bool |
|
22
|
|
|
*/ |
|
23
|
33 |
|
public static function isValidType($type) |
|
24
|
|
|
{ |
|
25
|
33 |
|
return ! empty(static::parseTypes($type)); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Parse a phone type into constant's value. |
|
30
|
|
|
* |
|
31
|
|
|
* @param string|array $types |
|
32
|
|
|
* @return array |
|
33
|
|
|
*/ |
|
34
|
63 |
|
protected static function parseTypes($types) |
|
35
|
|
|
{ |
|
36
|
63 |
|
static::loadTypes(); |
|
37
|
|
|
|
|
38
|
63 |
|
return Collection::make(is_array($types) ? $types : func_get_args()) |
|
39
|
|
|
->map(function ($type) { |
|
40
|
|
|
// If the type equals a constant's value, just return it. |
|
41
|
63 |
|
if (is_numeric($type) && in_array($type, static::$resolvedTypes)) { |
|
42
|
39 |
|
return (int) $type; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
// Otherwise we'll assume the type is the constant's name. |
|
46
|
60 |
|
return Arr::get(static::$resolvedTypes, strtoupper($type)); |
|
47
|
63 |
|
}) |
|
48
|
|
|
->reject(function ($value) { |
|
49
|
63 |
|
return is_null($value) || $value === false; |
|
50
|
63 |
|
})->toArray(); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Parse a phone type into its string representation. |
|
55
|
|
|
* |
|
56
|
|
|
* @param string|array $types |
|
57
|
|
|
* @return array |
|
58
|
|
|
*/ |
|
59
|
3 |
|
protected static function parseTypesAsStrings($types) |
|
60
|
|
|
{ |
|
61
|
3 |
|
static::loadTypes(); |
|
62
|
|
|
|
|
63
|
3 |
|
return array_keys( |
|
64
|
|
|
array_intersect( |
|
65
|
3 |
|
static::$resolvedTypes, |
|
66
|
3 |
|
static::parseTypes($types) |
|
67
|
|
|
) |
|
68
|
|
|
); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Load all available formats once. |
|
73
|
|
|
*/ |
|
74
|
63 |
|
private static function loadTypes() |
|
75
|
|
|
{ |
|
76
|
63 |
|
if (! static::$resolvedTypes) { |
|
77
|
9 |
|
static::$resolvedTypes = with(new ReflectionClass(PhoneNumberType::class))->getConstants(); |
|
78
|
|
|
} |
|
79
|
63 |
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|