Completed
Push — master ( a291e8...e660b5 )
by Propa
03:46
created

ParsesTypes::parseTypes()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 1
nop 1
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
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 $types;
16
17
    /**
18
     * Determine whether the given type is valid.
19
     *
20
     * @param string $type
21
     * @return bool
22
     */
23 26
    public static function isValidType($type)
24
    {
25 26
        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 47
    protected static function parseTypes($types)
35
    {
36 47
        static::loadTypes();
37
38 47
        return Collection::make(is_array($types) ? $types : func_get_args())
39 47
                         ->map(function ($type) {
40
                             // If the type equals a constant's value, just return it.
41 47
                             if (is_numeric($type) && in_array($type, static::$types)) {
42 20
                                 return (int) $type;
43
                             }
44
45
                             // Otherwise we'll assume the type is the constant's name.
46 44
                             return Arr::get(static::$types, strtoupper($type));
47 47
                         })
48 47
                         ->reject(function ($value) {
49 47
                             return is_null($value) || $value === false;
50 47
                         })->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 3
            array_intersect(
65 3
                static::$types,
66 3
                static::parseTypes($types)
67
            )
68
        );
69
    }
70
71
    /**
72
     * Load all available formats once.
73
     */
74 47
    private static function loadTypes()
75
    {
76 47
        if (! static::$types) {
77 6
            static::$types = with(new ReflectionClass(PhoneNumberType::class))->getConstants();
78
        }
79
    }
80
}