Property::__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 3
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 FSi\Bundle\AdminBundle\Display\Property\ValueFormatter;
15
use InvalidArgumentException;
16
17
class Property
18
{
19
    /**
20
     * @var mixed
21
     */
22
    private $value;
23
24
    /**
25
     * @var string|null
26
     */
27
    private $label;
28
29
    /**
30
     * @param mixed $value
31
     * @param string $label
32
     * @param ValueFormatter[] $valueFormatters
33
     */
34
    public function __construct($value, ?string $label = null, array $valueFormatters = [])
35
    {
36
        $this->validateFormatters($valueFormatters);
37
38
        $this->value = $this->formatValue($value, $valueFormatters);
39
        $this->label = $label;
40
    }
41
42
    public function getLabel(): ?string
43
    {
44
        return $this->label;
45
    }
46
47
    /**
48
     * @return mixed
49
     */
50
    public function getValue()
51
    {
52
        return $this->value;
53
    }
54
55
    /**
56
     * @param mixed $value
57
     * @param ValueFormatter[] $valueFormatters
58
     * @return mixed
59
     */
60
    private function formatValue($value, array $valueFormatters)
61
    {
62
        foreach ($valueFormatters as $formatter) {
63
            $value = $formatter->format($value);
64
        }
65
66
        return $value;
67
    }
68
69
    private function validateFormatters(array $valueFormatters): void
70
    {
71
        foreach ($valueFormatters as $formatter) {
72
            if (!$formatter instanceof ValueFormatter) {
73
                throw new InvalidArgumentException(sprintf(
74
                    'Expected property formatter to be an instance of'
75
                    . ' FSi\Bundle\AdminBundle\Display\Property\ValueFormatter,'
76
                    . ' got "%s" instead',
77
                    is_object($formatter) ? get_class($formatter) : gettype($formatter)
78
                ));
79
            }
80
        }
81
    }
82
}
83