PropertyAccessDisplay::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
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
declare(strict_types=1);
11
12
namespace FSi\Bundle\AdminBundle\Display;
13
14
use InvalidArgumentException;
15
use Symfony\Component\PropertyAccess\PropertyAccess;
16
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
17
18
class PropertyAccessDisplay implements Display
19
{
20
    /**
21
     * @var Property[]
22
     */
23
    private $data = [];
24
25
    /**
26
     * @var object|array
27
     */
28
    private $object;
29
30
    /**
31
     * @var PropertyAccessorInterface
32
     */
33
    private $accessor;
34
35
    /**
36
     * @param object|array $object
37
     */
38
    public function __construct($object)
39
    {
40
        $this->validateObject($object);
41
42
        $this->object = $object;
43
        $this->accessor = $this->createPropertyAccessor();
44
    }
45
46
    public function add($path, ?string $label = null, array $valueFormatters = []): Display
47
    {
48
        $this->data[] = new Property(
49
            $this->accessor->getValue($this->object, $path),
50
            $label,
51
            $valueFormatters
52
        );
53
54
        return $this;
55
    }
56
57
    public function getData(): array
58
    {
59
        return $this->data;
60
    }
61
62
    private function validateObject($object): void
63
    {
64
        if (!is_object($object) && !is_array($object)) {
65
            throw new InvalidArgumentException(sprintf(
66
                'Argument used to create "%s" must be an object or an array, got "%s" instead.',
67
                get_class($this),
68
                gettype($object)
69
            ));
70
        }
71
    }
72
73
    private function createPropertyAccessor(): PropertyAccessorInterface
74
    {
75
        $accessorBuilder = PropertyAccess::createPropertyAccessorBuilder();
76
        $accessorBuilder->enableMagicCall();
77
78
        return $accessorBuilder->getPropertyAccessor();
79
    }
80
}
81