1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the rybakit/twig-deferred-extension package. |
5
|
|
|
* |
6
|
|
|
* (c) Eugene Leonovich <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Twig\DeferredExtension; |
15
|
|
|
|
16
|
|
|
use Twig\Extension\AbstractExtension; |
17
|
|
|
use Twig\Template; |
18
|
|
|
|
19
|
|
|
final class DeferredExtension extends AbstractExtension |
20
|
|
|
{ |
21
|
|
|
private $blocks = []; |
22
|
|
|
private $clearBlocksOnBufferCleanup = true; |
23
|
|
|
|
24
|
|
|
public function getTokenParsers() : array |
25
|
|
|
{ |
26
|
|
|
return [new DeferredTokenParser()]; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function getNodeVisitors() : array |
30
|
|
|
{ |
31
|
|
|
return [new DeferredNodeVisitor()]; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function defer(Template $template, string $blockName) : void |
35
|
|
|
{ |
36
|
|
|
$templateName = $template->getTemplateName(); |
37
|
|
|
$this->blocks[$templateName][] = $blockName; |
38
|
|
|
$index = \count($this->blocks[$templateName]) - 1; |
39
|
|
|
|
40
|
|
|
\ob_start(function (string $buffer) use ($index, $templateName) { |
41
|
|
|
if ($this->clearBlocksOnBufferCleanup) { |
42
|
|
|
unset($this->blocks[$templateName][$index]); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return $buffer; |
46
|
|
|
}); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function resolve(Template $template, array $context, array $blocks) : void |
50
|
|
|
{ |
51
|
|
|
$templateName = $template->getTemplateName(); |
52
|
|
|
if (empty($this->blocks[$templateName])) { |
53
|
|
|
return; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
while ($blockName = \array_pop($this->blocks[$templateName])) { |
57
|
|
|
$this->clearBlocksOnBufferCleanup = false; |
58
|
|
|
$buffer = \ob_get_clean(); |
59
|
|
|
$this->clearBlocksOnBufferCleanup = true; |
60
|
|
|
|
61
|
|
|
$blocks[$blockName] = [$template, 'block_'.$blockName.'_deferred']; |
62
|
|
|
$template->displayBlock($blockName, $context, $blocks); |
63
|
|
|
|
64
|
|
|
echo $buffer; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if ($parent = $template->getParent($context)) { |
68
|
|
|
$this->resolve($parent, $context, $blocks); |
|
|
|
|
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|