Completed
Push — master ( 61149e...b529ec )
by Jarek
11s
created

PropertyAccessDisplay::validateObject()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 6
nc 2
nop 1
1
<?php
2
3
/**
4
 * (c) FSi sp. z o.o. <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace FSi\Bundle\AdminBundle\Display;
11
12
use InvalidArgumentException;
13
use Symfony\Component\PropertyAccess\PropertyAccess;
14
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
15
16
class PropertyAccessDisplay implements Display
17
{
18
    /**
19
     * @var Property[]
20
     */
21
    private $data = [];
22
23
    /**
24
     * @var object|array
25
     */
26
    private $object;
27
28
    /**
29
     * @var PropertyAccessorInterface
30
     */
31
    private $accessor;
32
33
    /**
34
     * @param object|array $object
35
     */
36
    public function __construct($object)
37
    {
38
        $this->validateObject($object);
39
40
        $this->object = $object;
41
        $this->accessor = $this->createPropertyAccessor();
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function add($path, $label, array $valueFormatters = array())
48
    {
49
        $this->data[] = new Property(
50
            $this->accessor->getValue($this->object, $path),
51
            $label,
52
            $valueFormatters
53
        );
54
55
        return $this;
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function getData()
62
    {
63
        return $this->data;
64
    }
65
66
    /**
67
     * @param object|array $object
68
     * @throws InvalidArgumentException
69
     */
70
    private function validateObject($object)
71
    {
72
        if (!is_object($object) && !is_array($object)) {
73
            throw new InvalidArgumentException(sprintf(
74
                'Argument used to create "%s" must be an object or an array, got "%s" instead.',
75
                get_class($this),
76
                gettype($object)
77
            ));
78
        }
79
    }
80
81
    /**
82
     * @return PropertyAccessorInterface
83
     */
84
    private function createPropertyAccessor()
85
    {
86
        $accessorBuilder = PropertyAccess::createPropertyAccessorBuilder();
87
        $accessorBuilder->enableMagicCall();
88
89
        return $accessorBuilder->getPropertyAccessor();
90
    }
91
}
92