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