Passed
Push — master ( fe64ef...2e5fa1 )
by Ivan
02:01
created

AddBlocks   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
dl 0
loc 48
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getBlocks() 0 3 2
A add() 0 5 1
A __construct() 0 6 2
A mutate() 0 13 3
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
        foreach ($blocksToRender as $id) {
33
            $this->defaultBlocks[] = new Block($id);
34
        }
35
    }
36
37
    public function mutate(Handler $ajax): Handler
38
    {
39
        foreach ($this->getBlocks() as $block) {
40
            try {
41
                $blockId = str_replace('-', '_', $block->getId());
42
                $html = $this->renderBlock->render($this->view, $blockId, $this->parameters);
43
                $ajax->container(sprintf('#%s', $block->getId()))->html($html);
44
            } catch (AjaxcomException $exception) {
45
                continue;
46
            }
47
        }
48
49
        return $ajax;
50
    }
51
52
    public function add(string $id): self
53
    {
54
        $this->blocks[] = new Block($id);
55
56
        return $this;
57
    }
58
59
    /**
60
     * @return Block[]
61
     */
62
    private function getBlocks(): array
63
    {
64
        return empty($this->blocks) ? $this->defaultBlocks : $this->blocks;
65
    }
66
}
67