Scheme   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 80
rs 10
c 0
b 0
f 0
wmc 12

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B cast() 0 20 6
B parseConfig() 0 18 5
1
<?php
2
3
namespace Mvkasatkin\typecast\type;
4
5
class Scheme implements CastInterface
6
{
7
    /**
8
     * @var CastInterface[]
9
     */
10
    protected $config = [];
11
    /**
12
     * @var Factory
13
     */
14
    protected $factory;
15
    /**
16
     * @var bool
17
     */
18
    protected $strict;
19
20
    /**
21
     * @param array $config
22
     * @param Factory|null $factory
23
     * @param bool $strict
24
     *
25
     * @throws \Mvkasatkin\typecast\Exception
26
     */
27
    public function __construct(array $config = [], Factory $factory = null, bool $strict = false)
28
    {
29
        $this->factory = $factory ?? new Factory();
30
        $this->strict = $strict;
31
        $this->config = $this->parseConfig($config);
32
    }
33
34
    /**
35
     * @param array $config
36
     *
37
     * @return array
38
     * @throws \Mvkasatkin\typecast\Exception
39
     */
40
    protected function parseConfig(array $config): array
41
    {
42
        $result = [];
43
        foreach ($config as $key => $type) {
44
            if (\is_array($type)) {
45
                if ($arrayOfType = $this->factory->checkArrayOfType($type)) {
46
                    $result[$key] = $arrayOfType;
47
                } else {
48
                    $result[$key] = new self($type, $this->factory, $this->strict);
49
                }
50
            } elseif ($type instanceof CastInterface) {
51
                $result[$key] = $type;
52
            } else {
53
                $result[$key] = $this->factory->createType($type);
54
            }
55
        }
56
57
        return $result;
58
    }
59
60
    /**
61
     * @param $value
62
     *
63
     * @return array
64
     */
65
    public function cast($value): array
66
    {
67
        $result = [];
68
        $config = $this->config;
69
        foreach ((array)$value as $key => $itemValue) {
70
            if (isset($config[$key])) {
71
                $result[$key] = $config[$key]->cast($itemValue);
72
                unset($config[$key]);
73
            } elseif (!$this->strict) {
74
                $result[$key] = $itemValue;
75
            }
76
        }
77
78
        if ($this->strict) {
79
            foreach ($config as $key => $type) {
80
                $result[$key] = $type->cast(null);
81
            }
82
        }
83
84
        return $result;
85
    }
86
}
87