Completed
Push — master ( 5b0125...766181 )
by Svilen
01:05 queued 10s
created

Property::hasCast()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace CodeBooth\DataTransferObject;
6
7
use ReflectionProperty;
8
9
class Property extends ReflectionProperty
10
{
11
    /**
12
     * @var \CodeBooth\DataTransferObject\DataTransferObject
13
     */
14
    protected $dto;
15
16
    /**
17
     * Property constructor.
18
     *
19
     * @param \CodeBooth\DataTransferObject\DataTransferObject $object
20
     * @param \ReflectionProperty $reflectionProperty
21
     *
22
     * @throws \ReflectionException
23
     */
24
    public function __construct(DataTransferObject $object, ReflectionProperty $reflectionProperty)
25
    {
26
        parent::__construct($reflectionProperty->class, $reflectionProperty->getName());
27
28
        $this->dto = $object;
29
    }
30
31
    /**
32
     * @param mixed $value
33
     */
34
    public function value($value)
35
    {
36
        $property = $this->getName();
37
38
        if ($this->hasCast($property)) {
39
            $value = $this->cast($value);
40
        }
41
42
        $this->dto->{$this->getName()} = $value;
43
    }
44
45
    /**
46
     * Check if the attribute's value needs to cast.
47
     *
48
     * @param string $attribute
49
     *
50
     * @return bool
51
     */
52
    protected function hasCast(string $attribute)
53
    {
54
        return array_key_exists($attribute, $this->dto->casts);
55
    }
56
57
    /**
58
     * Cast an attribute to a native PHP type.
59
     *
60
     * @param mixed $value
61
     *
62
     * @return mixed
63
     */
64
    protected function cast($value)
65
    {
66
        if (is_null($value)) {
67
            return $value;
68
        }
69
70
        switch ($this->getCastType($this->getName())) {
71
            case 'int':
72
            case 'integer':
73
                return (int) $value;
74
75
            case 'real':
76
            case 'float':
77
            case 'double':
78
                return (float) $value;
79
80
            default:
81
                $value;
82
        }
83
    }
84
85
    /**
86
     * Get the type of cast for attribute.
87
     *
88
     * @param string $attribute
89
     *
90
     * @return string
91
     */
92
    protected function getCastType(string $attribute)
93
    {
94
        return trim(strtolower($this->dto->casts[$attribute]));
95
    }
96
}
97