Enum::hydrate()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 4
nop 2
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Igni\Storage\Mapping\Strategy;
4
5
use Igni\Storage\Exception\MappingException;
6
use Igni\Storage\Mapping\MappingStrategy;
7
8
final class Enum implements MappingStrategy, DefaultAttributesProvider
9
{
10 9
    public static function hydrate(&$value, array $attributes = []): void
11
    {
12 9
        if ($value === null) {
13 1
            return;
14
        }
15
16 8
        $values = $attributes['values'];
17
18 8
        if (is_string($values) && class_exists($values)) {
19 2
            $value = new $values($value);
20 2
            return;
21
        }
22
23 6
        if (is_array($values) && !empty($values)) {
24 4
            $value = $values[$value];
25 4
            return;
26
        }
27
28 2
        throw MappingException::forInvalidAttributeValue('values', $values, 'Is not valid class name or available value list.');
29
    }
30
31 5
    public static function extract(&$value, array $attributes = []): void
32
    {
33 5
        if ($value instanceof \Igni\Storage\Enum) {
34 2
            $value = $value->getValue();
35 2
            return;
36
        }
37
38 3
        $values = $attributes['values'];
39
40 3
        if (!is_array($values)) {
41 1
            throw MappingException::forInvalidAttributeValue('values', $values, 'Is not valid class name or available value list.');
42
        }
43
44 2
        $value = array_search($value, $attributes['values']);
45 2
    }
46
47 1
    public static function getDefaultAttributes(): array
48
    {
49
        return [
50 1
            'values' => [],
51
        ];
52
    }
53
}
54