Completed
Pull Request — 3.1 (#348)
by Piotr
09:36 queued 07:40
created

Collection   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 45
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B format() 0 25 6
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\Property\Formatter;
13
14
use FSi\Bundle\AdminBundle\Display\Property\ValueFormatter;
15
16
class Collection implements ValueFormatter
17
{
18
    /**
19
     * @var ValueFormatter[]
20
     */
21
    private $formatters;
22
23
    /**
24
     * @param ValueFormatter[] $formatters
25
     */
26
    public function __construct(array $formatters)
27
    {
28
        $this->formatters = $formatters;
29
    }
30
31
    /**
32
     * @param iterable $value
33
     * @return array|mixed
34
     */
35
    public function format($value)
36
    {
37
        if (empty($value)) {
38
            return $value;
39
        }
40
41
        if (!is_iterable($value)) {
42
            throw new \InvalidArgumentException(sprintf(
43
                'Collection formatter requires value to be iterable, %s given',
44
                is_object($value) ? get_class($value) : gettype($value)
45
            ));
46
        }
47
48
        $formatted = [];
49
        foreach ($value as $key => $val) {
50
            $formattedValue = $val;
51
            foreach ($this->formatters as $formatter) {
52
                $formattedValue = $formatter->format($formattedValue);
53
            }
54
55
            $formatted[$key] = $formattedValue;
56
        }
57
58
        return $formatted;
59
    }
60
}
61