Passed
Push — develop ( 355f63...51016a )
by Mathieu
02:23
created

ArrayAnnotationTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 19
dl 0
loc 71
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setArrayProperty() 0 4 1
A __get() 0 12 2
A __set() 0 15 4
1
<?php
2
3
namespace Neimheadh\SonataAnnotationBundle\Annotation;
4
5
use Psr\Log\InvalidArgumentException;
6
use ReflectionException;
7
use ReflectionProperty;
8
9
/**
10
 * Trait for annotation having only one array property.
11
 */
12
trait ArrayAnnotationTrait
13
{
14
15
    /**
16
     * Annotation repository name.
17
     *
18
     * @var ReflectionProperty
19
     */
20
    private ReflectionProperty $property;
21
22
    /**
23
     * Set the annotation array property.
24
     *
25
     * @param string $name Property name.
26
     * @param        $value
27
     *
28
     * @return void
29
     * @throws ReflectionException
30
     */
31
    private function setArrayProperty(string $name, $value): void
32
    {
33
        $this->property = new ReflectionProperty($this, $name);
34
        $this->__set($name, $value['value'] ?? $value[$name] ?? $value);
35
    }
36
37
38
    /**
39
     * Set class property.
40
     *
41
     * @param string $name  Property name.
42
     * @param mixed  $value Value.
43
     *
44
     * @return void
45
     */
46
    public function __set(string $name, $value)
47
    {
48
        if ($name !== $this->property->getName()) {
49
            throw new InvalidArgumentException(
50
                sprintf(
51
                    'Unknown property "%s".',
52
                    $name
53
                )
54
            );
55
        }
56
57
        if (is_array($value)) {
58
            $this->$name = $value;
59
        } else {
60
            $this->$name = is_null($value) ? [] : [$value];
61
        }
62
    }
63
64
    /**
65
     * Get class property.
66
     *
67
     * @param string $name Property name.
68
     *
69
     * @return mixed
70
     */
71
    public function __get(string $name)
72
    {
73
        if ($name !== $this->property->getName()) {
74
            throw new InvalidArgumentException(
75
                sprintf(
76
                    'Unknown property "%s".',
77
                    $name
78
                )
79
            );
80
        }
81
82
        return $this->$name;
83
    }
84
85
}