DemoExtension.php 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Acme\DemoBundle\Twig\Extension;
  3. use Symfony\Component\HttpKernel\KernelInterface;
  4. use Symfony\Bundle\TwigBundle\Loader\FilesystemLoader;
  5. class DemoExtension extends \Twig_Extension
  6. {
  7. protected $loader;
  8. protected $controller;
  9. public function __construct(FilesystemLoader $loader)
  10. {
  11. $this->loader = $loader;
  12. }
  13. public function setController($controller)
  14. {
  15. $this->controller = $controller;
  16. }
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public function getFunctions()
  21. {
  22. return array(
  23. 'code' => new \Twig_Function_Method($this, 'getCode', array('is_safe' => array('html'))),
  24. );
  25. }
  26. public function getCode($template)
  27. {
  28. $controller = htmlspecialchars($this->getControllerCode(), ENT_QUOTES, 'UTF-8');
  29. $template = htmlspecialchars($this->getTemplateCode($template), ENT_QUOTES, 'UTF-8');
  30. // remove the code block
  31. $template = str_replace('{% set code = code(_self) %}', '', $template);
  32. return <<<EOF
  33. <p><strong>Controller Code</strong></p>
  34. <pre>$controller</pre>
  35. <p><strong>Template Code</strong></p>
  36. <pre>$template</pre>
  37. EOF;
  38. }
  39. protected function getControllerCode()
  40. {
  41. $r = new \ReflectionClass($this->controller[0]);
  42. $m = $r->getMethod($this->controller[1]);
  43. $code = file($r->getFilename());
  44. return ' '.$m->getDocComment()."\n".implode('', array_slice($code, $m->getStartline() - 1, $m->getEndLine() - $m->getStartline() + 1));
  45. }
  46. protected function getTemplateCode($template)
  47. {
  48. return $this->loader->getSource($template->getTemplateName());
  49. }
  50. /**
  51. * Returns the name of the extension.
  52. *
  53. * @return string The extension name
  54. */
  55. public function getName()
  56. {
  57. return 'demo';
  58. }
  59. }