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