RenderCellCollectionTrait   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
c 0
b 0
f 0
lcom 1
cbo 3
dl 0
loc 55
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addRenderer() 0 5 1
A addRendererFunction() 0 5 1
A renderCell() 0 18 3
1
<?php
2
namespace Consolidation\OutputFormatters\StructuredData;
3
4
use Consolidation\OutputFormatters\Options\FormatterOptions;
5
use Consolidation\OutputFormatters\Formatters\FormatterAwareInterface;
6
use Consolidation\OutputFormatters\Formatters\FormatterAwareTrait;
7
8
trait RenderCellCollectionTrait
9
{
10
    use FormatterAwareTrait;
11
12
    /** @var RenderCellInterface[] */
13
    protected $rendererList = [
14
        RenderCellCollectionInterface::PRIORITY_FIRST => [],
15
        RenderCellCollectionInterface::PRIORITY_NORMAL => [],
16
        RenderCellCollectionInterface::PRIORITY_FALLBACK => [],
17
    ];
18
19
    /**
20
     * Add a renderer
21
     *
22
     * @return $this
23
     */
24
    public function addRenderer(RenderCellInterface $renderer, $priority = RenderCellCollectionInterface::PRIORITY_NORMAL)
25
    {
26
        $this->rendererList[$priority][] = $renderer;
27
        return $this;
28
    }
29
30
    /**
31
     * Add a callable as a renderer
32
     *
33
     * @return $this
34
     */
35
    public function addRendererFunction(callable $rendererFn, $priority = RenderCellCollectionInterface::PRIORITY_NORMAL)
36
    {
37
        $renderer = new CallableRenderer($rendererFn);
38
        return $this->addRenderer($renderer, $priority);
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function renderCell($key, $cellData, FormatterOptions $options, $rowData)
45
    {
46
        $flattenedRendererList = array_reduce(
47
            $this->rendererList,
48
            function ($carry, $item) {
49
                return array_merge($carry, $item);
50
            },
51
            []
52
        );
53
54
        foreach ($flattenedRendererList as $renderer) {
55
            if ($renderer instanceof FormatterAwareInterface) {
56
                $renderer->setFormatter($this->getFormatter());
57
            }
58
            $cellData = $renderer->renderCell($key, $cellData, $options, $rowData);
59
        }
60
        return $cellData;
61
    }
62
}
63