Passed
Push — master ( 3d191d...b6a6e2 )
by Ivan
02:46
created

AddBlocks::mutate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Everlution\AjaxcomBundle\Mutation;
6
7
use Everlution\Ajaxcom\Handler;
8
use Everlution\AjaxcomBundle\AjaxcomException;
9
use Everlution\AjaxcomBundle\DataObject\Block;
10
use Everlution\AjaxcomBundle\Service\RenderBlock;
11
12
/**
13
 * Class AddBlocks.
14
 *
15
 * @author Ivan Barlog <[email protected]>
16
 */
17
class AddBlocks implements MutatorInterface, RenderableInterface
18
{
19
    use RenderableTrait;
20
21
    /** @var RenderBlock */
22
    private $renderBlock;
23
    /** @var Block[] */
24
    private $blocks = [];
25
    /** @var Block[] */
26
    private $defaultBlocks = [];
27
28
    public function __construct(RenderBlock $renderBlock, array $blocksToRender = [])
29
    {
30
        $this->renderBlock = $renderBlock;
31
32
        $this->defaultBlocks = array_map(
33
            function (array $data) {
34
                $block = new Block($data['id']);
35
                if ($data['refresh']) {
36
                    $block->refresh();
37
                }
38
39
                return $block;
40
            },
41
            $blocksToRender
42
        );
43
    }
44
45
    public function mutate(Handler $ajax): Handler
46
    {
47
        foreach ($this->getBlocks() as $block) {
48
            try {
49
                $html = $this->renderBlock->render($block, $this->view, $this->parameters);
50
            } catch (AjaxcomException $exception) {
51
                continue;
52
            }
53
54
            $ajax->container(sprintf('#%s', $block->getId()))->html($html);
55
        }
56
57
        return $ajax;
58
    }
59
60
    public function add(string $id): self
61
    {
62
        $this->blocks[$id] = new Block($id);
63
64
        return $this;
65
    }
66
67
    public function refresh(string $id): self
68
    {
69
        if (false === array_key_exists($id, $this->blocks)) {
70
            throw new BlockDoesNotExist($id);
71
        }
72
73
        $this->defaultBlocks[$id]->refresh();
74
75
        return $this;
76
    }
77
78
    /**
79
     * @return Block[]
80
     */
81
    private function getBlocks(): array
82
    {
83
        return empty($this->blocks) ? $this->defaultBlocks : $this->blocks;
84
    }
85
}
86