|
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 remove(string $id): self |
|
68
|
|
|
{ |
|
69
|
|
|
unset($this->blocks[$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
|
|
|
|