TypeCaster::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Larapie\DataTransferObject\Casters;
4
5
use Larapie\DataTransferObject\DataTransferObject;
6
use Larapie\DataTransferObject\Property\PropertyType;
7
8
class TypeCaster
9
{
10
    /**
11
     * @var PropertyType
12
     */
13
    protected $type;
14
15
    /**
16
     * TypeCaster constructor.
17
     * @param PropertyType $type
18
     */
19 41
    public function __construct(PropertyType $type)
20
    {
21 41
        $this->type = $type;
22 41
    }
23
24 41
    public function cast($value)
25
    {
26 41
        $value = $this->castDto($value);
27
28 41
        if (is_array($value)) {
29 7
            $value = $this->shouldBeCastToCollection($value) ? $this->castCollection($value) : $this->castDto($value);
30
        }
31
32 41
        return $value;
33
    }
34
35 41
    protected function castDto($value)
36
    {
37 41
        foreach ($this->type->getTypes() as $type) {
38 40
            if (is_subclass_of($type, DataTransferObject::class)) {
39 6
                if (is_array($value)) {
40 40
                    return new $type($value);
41
                }
42
            }
43
        }
44
45 40
        return $value;
46
    }
47
48 2
    protected function castCollection(array $values)
49
    {
50 2
        $castTo = null;
51
52 2
        foreach ($this->type->getArrayTypes() as $type) {
53 2
            if (! is_subclass_of($type, DataTransferObject::class)) {
54
                continue;
55
            }
56
57 2
            $castTo = $type;
58
59 2
            break;
60
        }
61
62 2
        if (! $castTo) {
63
            return $values;
64
        }
65
66 2
        $casts = [];
67
68 2
        foreach ($values as $value) {
69 2
            $casts[] = new $castTo($value);
70
        }
71
72 2
        return $casts;
73
    }
74
75 7
    protected function shouldBeCastToCollection(array $values): bool
76
    {
77 7
        if (empty($values)) {
78 1
            return false;
79
        }
80
81 6
        foreach ($values as $key => $value) {
82 6
            if (is_string($key)) {
83
                return false;
84
            }
85
86 6
            if (! is_array($value)) {
87 6
                return false;
88
            }
89
        }
90
91 2
        return true;
92
    }
93
}
94