|
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 $first = null; |
|
22
|
|
|
private $blocks = []; |
|
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 markIfFirst(Template $template): void |
|
35
|
|
|
{ |
|
36
|
|
|
if ($this->first === null) { |
|
37
|
|
|
$this->first = $template; |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function defer(Template $template, string $blockName) : void |
|
42
|
|
|
{ |
|
43
|
|
|
$this->blocks[] = [$template, $blockName]; |
|
44
|
|
|
$key = \array_key_last($this->blocks); |
|
45
|
|
|
\ob_start(function (string $buffer) use ($key) { |
|
46
|
|
|
unset($this->blocks[$key]); |
|
47
|
|
|
return $buffer; |
|
48
|
|
|
}); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function resolve(Template $template, array $context, array $blocks) : void |
|
52
|
|
|
{ |
|
53
|
|
|
if ($this->first !== $template || empty($this->blocks)) { |
|
54
|
|
|
return; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
// We don't use array_pop() here because it doesn't preserve keys, and we need it for the buffer callback |
|
58
|
|
|
while (!empty($this->blocks)) { |
|
59
|
|
|
$key = \array_key_last($this->blocks); |
|
60
|
|
|
[$blockTemplate, $blockName] = $this->blocks[$key]; |
|
61
|
|
|
unset($this->blocks[$key]); |
|
62
|
|
|
|
|
63
|
|
|
$buffer = \ob_get_clean(); |
|
64
|
|
|
|
|
65
|
|
|
$blocks[$blockName] = [$blockTemplate, 'block_'.$blockName.'_deferred']; |
|
66
|
|
|
$template->displayBlock($blockName, $context, $blocks); |
|
67
|
|
|
|
|
68
|
|
|
echo $buffer; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|