DemoExtension.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Acme\DemoBundle\Twig\Extension;
  3. use CG\Core\ClassUtils;
  4. class DemoExtension extends \Twig_Extension
  5. {
  6. protected $loader;
  7. protected $controller;
  8. public function __construct(\Twig_LoaderInterface $loader)
  9. {
  10. $this->loader = $loader;
  11. }
  12. public function setController($controller)
  13. {
  14. $this->controller = $controller;
  15. }
  16. /**
  17. * {@inheritdoc}
  18. */
  19. public function getFunctions()
  20. {
  21. return array(
  22. 'code' => new \Twig_Function_Method($this, 'getCode', array('is_safe' => array('html'))),
  23. );
  24. }
  25. public function getCode($template)
  26. {
  27. // highlight_string highlights php code only if '<?php' tag is present.
  28. $controller = highlight_string("<?php" . $this->getControllerCode(), true);
  29. $controller = str_replace('<span style="color: #0000BB">&lt;?php&nbsp;&nbsp;&nbsp;&nbsp;</span>', '&nbsp;&nbsp;&nbsp;&nbsp;', $controller);
  30. $template = htmlspecialchars($this->getTemplateCode($template), ENT_QUOTES, 'UTF-8');
  31. // remove the code block
  32. $template = str_replace('{% set code = code(_self) %}', '', $template);
  33. return <<<EOF
  34. <p><strong>Controller Code</strong></p>
  35. <pre>$controller</pre>
  36. <p><strong>Template Code</strong></p>
  37. <pre>$template</pre>
  38. EOF;
  39. }
  40. protected function getControllerCode()
  41. {
  42. $class = get_class($this->controller[0]);
  43. if (class_exists('CG\Core\ClassUtils')) {
  44. $class = ClassUtils::getUserClass($class);
  45. }
  46. $r = new \ReflectionClass($class);
  47. $m = $r->getMethod($this->controller[1]);
  48. $code = file($r->getFilename());
  49. return ' '.$m->getDocComment()."\n".implode('', array_slice($code, $m->getStartline() - 1, $m->getEndLine() - $m->getStartline() + 1));
  50. }
  51. protected function getTemplateCode($template)
  52. {
  53. return $this->loader->getSource($template->getTemplateName());
  54. }
  55. /**
  56. * Returns the name of the extension.
  57. *
  58. * @return string The extension name
  59. */
  60. public function getName()
  61. {
  62. return 'demo';
  63. }
  64. }