Completed
Push — dev-v3 ( 0f682d )
by Propa
02:36
created

ParsesFormats::loadFormats()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
ccs 0
cts 6
cp 0
crap 6
rs 9.4285
1
<?php namespace Propaganistas\LaravelPhone\Traits;
2
3
use Illuminate\Support\Arr;
4
use libphonenumber\PhoneNumberFormat;
5
use ReflectionClass;
6
7
trait ParsesFormats
8
{
9
    /**
10
     * Array of available phone formats.
11
     *
12
     * @var array
13
     */
14
    protected static $formats;
15
16
    /**
17
     * Determine whether the given format is valid.
18
     *
19
     * @param string $format
20
     * @return bool
21
     */
22
    public static function isFormat($format)
23
    {
24
        return ! is_null(static::parseFormat($format));
25
    }
26
27
    /**
28
     * Parse a phone format.
29
     *
30
     * @param string $format
31
     * @return string
32
     */
33
    protected static function parseFormat($format)
34
    {
35
        static::loadFormats();
36
37
        // If the format equals a constant's value, just return it.
38
        if (in_array($format, static::$formats)) {
39
            return $format;
40
        }
41
42
        // Otherwise we'll assume the format is the constant's name.
43
        return Arr::get(static::$formats, strtoupper($format));
44
    }
45
46
    /**
47
     * Load all available formats once.
48
     */
49
    private static function loadFormats()
50
    {
51
        if (! static::$formats) {
52
            static::$formats = with(new ReflectionClass(PhoneNumberFormat::class))->getConstants();
53
        }
54
    }
55
}