Passed
Push — master ( e129d0...0eb352 )
by Ivan
03:19
created

AddBlocks::refresh()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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