Parser::parseDefinition()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Cerbero\LaravelEnum;
4
5
use Illuminate\Support\Str;
6
7
/**
8
 * The enums parser.
9
 *
10
 */
11
class Parser
12
{
13
    const SEPARATOR_ENUM = '|';
14
    const SEPARATOR_PART = '=';
15
16
    /**
17
     * Parse the enums definition
18
     *
19
     * @param string $definition
20
     * @return array
21
     */
22 27
    public function parseDefinition(string $definition) : array
23
    {
24 27
        $enums = explode(static::SEPARATOR_ENUM, $definition);
25
26
        return array_map(function (string $enum) {
27 27
            $parts = explode(static::SEPARATOR_PART, $enum);
28
29 27
            return $this->hydrateEnumDefinition($parts);
30 27
        }, $enums);
31
    }
32
33
    /**
34
     * Retrieve the hydrated enum definition
35
     *
36
     * @param array $parts
37
     * @return EnumDefinition
38
     */
39 27
    private function hydrateEnumDefinition(array $parts) : EnumDefinition
40
    {
41
        return tap(new EnumDefinition, function ($enumDefinition) use ($parts) {
42 27
            $enumDefinition->name = $parts[0];
43 27
            $enumDefinition->key = isset($parts[1]) ? $this->parseValue($parts[1]) : Str::lower($parts[0]);
44 27
            $enumDefinition->value = isset($parts[2]) ? $this->parseValue($parts[2]) : null;
45 27
        });
46
    }
47
48
    /**
49
     * Parse the given variable to retrieve its actual value
50
     *
51
     * @param mixed $value
52
     * @return mixed
53
     */
54 27
    public function parseValue($value)
55
    {
56 27
        if ($value === null || $value === '') {
57 3
            return null;
58
        }
59
60
        // Return floats, integers, booleans or arrays if possible
61 24
        if (null !== $decoded = json_decode($value, true)) {
62 21
            return $decoded;
63
        }
64
65 3
        return $value;
66
    }
67
}
68