DeferredExtension.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. // Fix too many ob_get_clean() calls when exception is thrown inside the template.
  3. namespace Phive\Twig\Extensions\Deferred;
  4. class DeferredExtension extends \Twig_Extension
  5. {
  6. /**
  7. * @var array
  8. */
  9. private $blocks = array();
  10. /**
  11. * {@inheritdoc}
  12. */
  13. public function getTokenParsers()
  14. {
  15. return array(new DeferredTokenParser());
  16. }
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public function getNodeVisitors()
  21. {
  22. return array(new DeferredNodeVisitor());
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function getName()
  28. {
  29. return 'deferred';
  30. }
  31. public function defer(\Twig_Template $template, $blockName)
  32. {
  33. ob_start();
  34. $templateName = $template->getTemplateName();
  35. $this->blocks[$templateName][] = [ob_get_level(), $blockName];
  36. }
  37. public function resolve(\Twig_Template $template, array $context, array $blocks)
  38. {
  39. $templateName = $template->getTemplateName();
  40. if (empty($this->blocks[$templateName])) {
  41. return;
  42. }
  43. while ($block = array_pop($this->blocks[$templateName])) {
  44. [$level, $blockName] = $block;
  45. if (ob_get_level() !== $level) {
  46. continue;
  47. }
  48. $buffer = ob_get_clean();
  49. $blocks[$blockName] = array($template, 'block_'.$blockName.'_deferred');
  50. $template->displayBlock($blockName, $context, $blocks);
  51. echo $buffer;
  52. }
  53. if ($parent = $template->getParent($context)) {
  54. $this->resolve($parent, $context, $blocks);
  55. }
  56. }
  57. }