1 | <?php |
||
17 | class StringyExtension extends \Twig_Extension |
||
18 | { |
||
19 | const EXCLUDE_FUNCTIONS = ['__construct', '__toString', 'create']; |
||
20 | |||
21 | /** |
||
22 | * @var \Twig_Environment |
||
23 | */ |
||
24 | protected $environment; |
||
25 | |||
26 | /** |
||
27 | * @var array |
||
28 | */ |
||
29 | protected $functions = []; |
||
30 | |||
31 | /** |
||
32 | * @var array |
||
33 | */ |
||
34 | protected $filters = []; |
||
35 | |||
36 | 83 | public function __construct(\Twig_Environment $environment) |
|
40 | |||
41 | /** |
||
42 | * {@inheritdoc} |
||
43 | */ |
||
44 | 11 | public function getFilters() |
|
50 | |||
51 | /** |
||
52 | * {@inheritdoc} |
||
53 | */ |
||
54 | 11 | public function getFunctions() |
|
60 | |||
61 | /** |
||
62 | * Initializes arrays of filters and functions. |
||
63 | */ |
||
64 | 11 | private function lazyInit() |
|
65 | { |
||
66 | 11 | $stringyClass = new \ReflectionClass('Stringy\Stringy'); |
|
67 | 11 | $methods = $stringyClass->getMethods(\ReflectionMethod::IS_PUBLIC); |
|
68 | $names = array_map(function ($value) { |
||
69 | 11 | return $value->getName(); |
|
70 | 11 | }, $methods); |
|
71 | |||
72 | 11 | foreach ($names as $name) { |
|
73 | 11 | if (in_array($name, self::EXCLUDE_FUNCTIONS)) { |
|
74 | 11 | continue; |
|
75 | } |
||
76 | |||
77 | 11 | $method = $stringyClass->getMethod($name); |
|
78 | |||
79 | // Get the return type from the doc comment |
||
80 | 11 | $doc = $method->getDocComment(); |
|
81 | 11 | if (strpos($doc, '@return bool')) { |
|
82 | // Don't add functions which have the same name as any already in the environment |
||
83 | 11 | if ($this->environment->getFunction($name)) { |
|
84 | continue; |
||
85 | } |
||
86 | $this->functions[$name] = new \Twig_SimpleFunction($name, function () use ($name) { |
||
87 | 2 | return call_user_func_array(['Stringy\StaticStringy', $name], func_get_args()); |
|
88 | 11 | }); |
|
89 | } else { |
||
90 | // Don't add filters which have the same name as any already in the environment |
||
91 | 11 | if ($this->environment->getFilter($name)) { |
|
92 | 11 | continue; |
|
93 | } |
||
94 | 11 | $this->filters[$name] = new \Twig_SimpleFilter($name, function () use ($name) { |
|
95 | 3 | return call_user_func_array(['Stringy\StaticStringy', $name], func_get_args()); |
|
96 | 11 | }); |
|
97 | } |
||
98 | } |
||
99 | 11 | } |
|
100 | |||
101 | /** |
||
102 | * {@inheritdoc} |
||
103 | */ |
||
104 | 83 | public function getName() |
|
108 | } |
||
109 |