4 * This file is part of Twig.
6 * (c) 2009 Fabien Potencier
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
13 * Stores the Twig configuration.
15 * @author Fabien Potencier <fabien@symfony.com>
17 class Twig_Environment
19 const VERSION
= '1.13.2';
24 protected $autoReload;
29 protected $baseTemplateClass;
30 protected $extensions;
37 protected $runtimeInitialized;
38 protected $extensionInitialized;
39 protected $loadedTemplates;
40 protected $strictVariables;
41 protected $unaryOperators;
42 protected $binaryOperators;
43 protected $templateClassPrefix = '__TwigTemplate_';
44 protected $functionCallbacks;
45 protected $filterCallbacks;
53 * * debug: When set to true, it automatically set "auto_reload" to true as
54 * well (default to false).
56 * * charset: The charset used by the templates (default to UTF-8).
58 * * base_template_class: The base template class to use for generated
59 * templates (default to Twig_Template).
61 * * cache: An absolute path where to store the compiled templates, or
62 * false to disable compilation cache (default).
64 * * auto_reload: Whether to reload the template is the original source changed.
65 * If you don't provide the auto_reload option, it will be
66 * determined automatically base on the debug value.
68 * * strict_variables: Whether to ignore invalid variables in templates
71 * * autoescape: Whether to enable auto-escaping (default to html):
72 * * false: disable auto-escaping
73 * * true: equivalent to html
74 * * html, js: set the autoescaping to one of the supported strategies
75 * * PHP callback: a PHP callback that returns an escaping strategy based on the template "filename"
77 * * optimizations: A flag that indicates which optimizations to apply
78 * (default to -1 which means that all optimizations are enabled;
79 * set it to 0 to disable).
81 * @param Twig_LoaderInterface $loader A Twig_LoaderInterface instance
82 * @param array $options An array of options
84 public function __construct(Twig_LoaderInterface
$loader = null, $options = array())
86 if (null !== $loader) {
87 $this->setLoader($loader);
90 $options = array_merge(array(
93 'base_template_class' => 'Twig_Template',
94 'strict_variables' => false,
95 'autoescape' => 'html',
97 'auto_reload' => null,
98 'optimizations' => -1,
101 $this->debug
= (bool) $options['debug'];
102 $this->charset
= strtoupper($options['charset']);
103 $this->baseTemplateClass
= $options['base_template_class'];
104 $this->autoReload
= null === $options['auto_reload'] ? $this->debug
: (bool) $options['auto_reload'];
105 $this->strictVariables
= (bool) $options['strict_variables'];
106 $this->runtimeInitialized
= false;
107 $this->setCache($options['cache']);
108 $this->functionCallbacks
= array();
109 $this->filterCallbacks
= array();
111 $this->addExtension(new Twig_Extension_Core());
112 $this->addExtension(new Twig_Extension_Escaper($options['autoescape']));
113 $this->addExtension(new Twig_Extension_Optimizer($options['optimizations']));
114 $this->extensionInitialized
= false;
115 $this->staging
= new Twig_Extension_Staging();
119 * Gets the base template class for compiled templates.
121 * @return string The base template class name
123 public function getBaseTemplateClass()
125 return $this->baseTemplateClass
;
129 * Sets the base template class for compiled templates.
131 * @param string $class The base template class name
133 public function setBaseTemplateClass($class)
135 $this->baseTemplateClass
= $class;
139 * Enables debugging mode.
141 public function enableDebug()
147 * Disables debugging mode.
149 public function disableDebug()
151 $this->debug
= false;
155 * Checks if debug mode is enabled.
157 * @return Boolean true if debug mode is enabled, false otherwise
159 public function isDebug()
165 * Enables the auto_reload option.
167 public function enableAutoReload()
169 $this->autoReload
= true;
173 * Disables the auto_reload option.
175 public function disableAutoReload()
177 $this->autoReload
= false;
181 * Checks if the auto_reload option is enabled.
183 * @return Boolean true if auto_reload is enabled, false otherwise
185 public function isAutoReload()
187 return $this->autoReload
;
191 * Enables the strict_variables option.
193 public function enableStrictVariables()
195 $this->strictVariables
= true;
199 * Disables the strict_variables option.
201 public function disableStrictVariables()
203 $this->strictVariables
= false;
207 * Checks if the strict_variables option is enabled.
209 * @return Boolean true if strict_variables is enabled, false otherwise
211 public function isStrictVariables()
213 return $this->strictVariables
;
217 * Gets the cache directory or false if cache is disabled.
219 * @return string|false
221 public function getCache()
227 * Sets the cache directory or false if cache is disabled.
229 * @param string|false $cache The absolute path to the compiled templates,
230 * or false to disable cache
232 public function setCache($cache)
234 $this->cache
= $cache ? $cache : false;
238 * Gets the cache filename for a given template.
240 * @param string $name The template name
242 * @return string The cache file name
244 public function getCacheFilename($name)
246 if (false === $this->cache
) {
250 $class = substr($this->getTemplateClass($name), strlen($this->templateClassPrefix
));
252 return $this->getCache().'/'.substr($class, 0, 2).'/'.substr($class, 2, 2).'/'.substr($class, 4).'.php';
256 * Gets the template class associated with the given string.
258 * @param string $name The name for which to calculate the template class name
259 * @param integer $index The index if it is an embedded template
261 * @return string The template class name
263 public function getTemplateClass($name, $index = null)
265 return $this->templateClassPrefix
.md5($this->getLoader()->getCacheKey($name)).(null === $index ? '' : '_'.$index);
269 * Gets the template class prefix.
271 * @return string The template class prefix
273 public function getTemplateClassPrefix()
275 return $this->templateClassPrefix
;
279 * Renders a template.
281 * @param string $name The template name
282 * @param array $context An array of parameters to pass to the template
284 * @return string The rendered template
286 public function render($name, array $context = array())
288 return $this->loadTemplate($name)->render($context);
292 * Displays a template.
294 * @param string $name The template name
295 * @param array $context An array of parameters to pass to the template
297 public function display($name, array $context = array())
299 $this->loadTemplate($name)->display($context);
303 * Loads a template by name.
305 * @param string $name The template name
306 * @param integer $index The index if it is an embedded template
308 * @return Twig_TemplateInterface A template instance representing the given template name
310 public function loadTemplate($name, $index = null)
312 $cls = $this->getTemplateClass($name, $index);
314 if (isset($this->loadedTemplates
[$cls])) {
315 return $this->loadedTemplates
[$cls];
318 if (!class_exists($cls, false)) {
319 if (false === $cache = $this->getCacheFilename($name)) {
320 eval('?>'.$this->compileSource($this->getLoader()->getSource($name), $name));
322 if (!is_file($cache) || ($this->isAutoReload() && !$this->isTemplateFresh($name, filemtime($cache)))) {
323 $this->writeCacheFile($cache, $this->compileSource($this->getLoader()->getSource($name), $name));
330 if (!$this->runtimeInitialized
) {
331 $this->initRuntime();
334 return $this->loadedTemplates
[$cls] = new $cls($this);
338 * Returns true if the template is still fresh.
340 * Besides checking the loader for freshness information,
341 * this method also checks if the enabled extensions have
344 * @param string $name The template name
345 * @param timestamp $time The last modification time of the cached template
347 * @return Boolean true if the template is fresh, false otherwise
349 public function isTemplateFresh($name, $time)
351 foreach ($this->extensions
as $extension) {
352 $r = new ReflectionObject($extension);
353 if (filemtime($r->getFileName()) > $time) {
358 return $this->getLoader()->isFresh($name, $time);
361 public function resolveTemplate($names)
363 if (!is_array($names)) {
364 $names = array($names);
367 foreach ($names as $name) {
368 if ($name instanceof Twig_Template
) {
373 return $this->loadTemplate($name);
374 } catch (Twig_Error_Loader
$e) {
378 if (1 === count($names)) {
382 throw new Twig_Error_Loader(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
386 * Clears the internal template cache.
388 public function clearTemplateCache()
390 $this->loadedTemplates
= array();
394 * Clears the template cache files on the filesystem.
396 public function clearCacheFiles()
398 if (false === $this->cache
) {
402 foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->cache
), RecursiveIteratorIterator
::LEAVES_ONLY
) as $file) {
403 if ($file->isFile()) {
404 @unlink($file->getPathname());
410 * Gets the Lexer instance.
412 * @return Twig_LexerInterface A Twig_LexerInterface instance
414 public function getLexer()
416 if (null === $this->lexer
) {
417 $this->lexer
= new Twig_Lexer($this);
424 * Sets the Lexer instance.
426 * @param Twig_LexerInterface A Twig_LexerInterface instance
428 public function setLexer(Twig_LexerInterface
$lexer)
430 $this->lexer
= $lexer;
434 * Tokenizes a source code.
436 * @param string $source The template source code
437 * @param string $name The template name
439 * @return Twig_TokenStream A Twig_TokenStream instance
441 public function tokenize($source, $name = null)
443 return $this->getLexer()->tokenize($source, $name);
447 * Gets the Parser instance.
449 * @return Twig_ParserInterface A Twig_ParserInterface instance
451 public function getParser()
453 if (null === $this->parser
) {
454 $this->parser
= new Twig_Parser($this);
457 return $this->parser
;
461 * Sets the Parser instance.
463 * @param Twig_ParserInterface A Twig_ParserInterface instance
465 public function setParser(Twig_ParserInterface
$parser)
467 $this->parser
= $parser;
471 * Parses a token stream.
473 * @param Twig_TokenStream $tokens A Twig_TokenStream instance
475 * @return Twig_Node_Module A Node tree
477 public function parse(Twig_TokenStream
$tokens)
479 return $this->getParser()->parse($tokens);
483 * Gets the Compiler instance.
485 * @return Twig_CompilerInterface A Twig_CompilerInterface instance
487 public function getCompiler()
489 if (null === $this->compiler
) {
490 $this->compiler
= new Twig_Compiler($this);
493 return $this->compiler
;
497 * Sets the Compiler instance.
499 * @param Twig_CompilerInterface $compiler A Twig_CompilerInterface instance
501 public function setCompiler(Twig_CompilerInterface
$compiler)
503 $this->compiler
= $compiler;
509 * @param Twig_NodeInterface $node A Twig_NodeInterface instance
511 * @return string The compiled PHP source code
513 public function compile(Twig_NodeInterface
$node)
515 return $this->getCompiler()->compile($node)->getSource();
519 * Compiles a template source code.
521 * @param string $source The template source code
522 * @param string $name The template name
524 * @return string The compiled PHP source code
526 public function compileSource($source, $name = null)
529 return $this->compile($this->parse($this->tokenize($source, $name)));
530 } catch (Twig_Error
$e) {
531 $e->setTemplateFile($name);
533 } catch (Exception
$e) {
534 throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $name, $e);
539 * Sets the Loader instance.
541 * @param Twig_LoaderInterface $loader A Twig_LoaderInterface instance
543 public function setLoader(Twig_LoaderInterface
$loader)
545 $this->loader
= $loader;
549 * Gets the Loader instance.
551 * @return Twig_LoaderInterface A Twig_LoaderInterface instance
553 public function getLoader()
555 if (null === $this->loader
) {
556 throw new LogicException('You must set a loader first.');
559 return $this->loader
;
563 * Sets the default template charset.
565 * @param string $charset The default charset
567 public function setCharset($charset)
569 $this->charset
= strtoupper($charset);
573 * Gets the default template charset.
575 * @return string The default charset
577 public function getCharset()
579 return $this->charset
;
583 * Initializes the runtime environment.
585 public function initRuntime()
587 $this->runtimeInitialized
= true;
589 foreach ($this->getExtensions() as $extension) {
590 $extension->initRuntime($this);
595 * Returns true if the given extension is registered.
597 * @param string $name The extension name
599 * @return Boolean Whether the extension is registered or not
601 public function hasExtension($name)
603 return isset($this->extensions
[$name]);
607 * Gets an extension by name.
609 * @param string $name The extension name
611 * @return Twig_ExtensionInterface A Twig_ExtensionInterface instance
613 public function getExtension($name)
615 if (!isset($this->extensions
[$name])) {
616 throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $name));
619 return $this->extensions
[$name];
623 * Registers an extension.
625 * @param Twig_ExtensionInterface $extension A Twig_ExtensionInterface instance
627 public function addExtension(Twig_ExtensionInterface
$extension)
629 if ($this->extensionInitialized
) {
630 throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $extension->getName()));
633 $this->extensions
[$extension->getName()] = $extension;
637 * Removes an extension by name.
639 * This method is deprecated and you should not use it.
641 * @param string $name The extension name
643 * @deprecated since 1.12 (to be removed in 2.0)
645 public function removeExtension($name)
647 if ($this->extensionInitialized
) {
648 throw new LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name));
651 unset($this->extensions
[$name]);
655 * Registers an array of extensions.
657 * @param array $extensions An array of extensions
659 public function setExtensions(array $extensions)
661 foreach ($extensions as $extension) {
662 $this->addExtension($extension);
667 * Returns all registered extensions.
669 * @return array An array of extensions
671 public function getExtensions()
673 return $this->extensions
;
677 * Registers a Token Parser.
679 * @param Twig_TokenParserInterface $parser A Twig_TokenParserInterface instance
681 public function addTokenParser(Twig_TokenParserInterface
$parser)
683 if ($this->extensionInitialized
) {
684 throw new LogicException('Unable to add a token parser as extensions have already been initialized.');
687 $this->staging
->addTokenParser($parser);
691 * Gets the registered Token Parsers.
693 * @return Twig_TokenParserBrokerInterface A broker containing token parsers
695 public function getTokenParsers()
697 if (!$this->extensionInitialized
) {
698 $this->initExtensions();
701 return $this->parsers
;
705 * Gets registered tags.
707 * Be warned that this method cannot return tags defined by Twig_TokenParserBrokerInterface classes.
709 * @return Twig_TokenParserInterface[] An array of Twig_TokenParserInterface instances
711 public function getTags()
714 foreach ($this->getTokenParsers()->getParsers() as $parser) {
715 if ($parser instanceof Twig_TokenParserInterface
) {
716 $tags[$parser->getTag()] = $parser;
724 * Registers a Node Visitor.
726 * @param Twig_NodeVisitorInterface $visitor A Twig_NodeVisitorInterface instance
728 public function addNodeVisitor(Twig_NodeVisitorInterface
$visitor)
730 if ($this->extensionInitialized
) {
731 throw new LogicException('Unable to add a node visitor as extensions have already been initialized.');
734 $this->staging
->addNodeVisitor($visitor);
738 * Gets the registered Node Visitors.
740 * @return Twig_NodeVisitorInterface[] An array of Twig_NodeVisitorInterface instances
742 public function getNodeVisitors()
744 if (!$this->extensionInitialized
) {
745 $this->initExtensions();
748 return $this->visitors
;
752 * Registers a Filter.
754 * @param string|Twig_SimpleFilter $name The filter name or a Twig_SimpleFilter instance
755 * @param Twig_FilterInterface|Twig_SimpleFilter $filter A Twig_FilterInterface instance or a Twig_SimpleFilter instance
757 public function addFilter($name, $filter = null)
759 if (!$name instanceof Twig_SimpleFilter
&& !($filter instanceof Twig_SimpleFilter
|| $filter instanceof Twig_FilterInterface
)) {
760 throw new LogicException('A filter must be an instance of Twig_FilterInterface or Twig_SimpleFilter');
763 if ($name instanceof Twig_SimpleFilter
) {
765 $name = $filter->getName();
768 if ($this->extensionInitialized
) {
769 throw new LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $name));
772 $this->staging
->addFilter($name, $filter);
776 * Get a filter by name.
778 * Subclasses may override this method and load filters differently;
779 * so no list of filters is available.
781 * @param string $name The filter name
783 * @return Twig_Filter|false A Twig_Filter instance or false if the filter does not exist
785 public function getFilter($name)
787 if (!$this->extensionInitialized
) {
788 $this->initExtensions();
791 if (isset($this->filters
[$name])) {
792 return $this->filters
[$name];
795 foreach ($this->filters
as $pattern => $filter) {
796 $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count);
799 if (preg_match('#^'.$pattern.'$#', $name, $matches)) {
800 array_shift($matches);
801 $filter->setArguments($matches);
808 foreach ($this->filterCallbacks
as $callback) {
809 if (false !== $filter = call_user_func($callback, $name)) {
817 public function registerUndefinedFilterCallback($callable)
819 $this->filterCallbacks
[] = $callable;
823 * Gets the registered Filters.
825 * Be warned that this method cannot return filters defined with registerUndefinedFunctionCallback.
827 * @return Twig_FilterInterface[] An array of Twig_FilterInterface instances
829 * @see registerUndefinedFilterCallback
831 public function getFilters()
833 if (!$this->extensionInitialized
) {
834 $this->initExtensions();
837 return $this->filters
;
843 * @param string|Twig_SimpleTest $name The test name or a Twig_SimpleTest instance
844 * @param Twig_TestInterface|Twig_SimpleTest $test A Twig_TestInterface instance or a Twig_SimpleTest instance
846 public function addTest($name, $test = null)
848 if (!$name instanceof Twig_SimpleTest
&& !($test instanceof Twig_SimpleTest
|| $test instanceof Twig_TestInterface
)) {
849 throw new LogicException('A test must be an instance of Twig_TestInterface or Twig_SimpleTest');
852 if ($name instanceof Twig_SimpleTest
) {
854 $name = $test->getName();
857 if ($this->extensionInitialized
) {
858 throw new LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $name));
861 $this->staging
->addTest($name, $test);
865 * Gets the registered Tests.
867 * @return Twig_TestInterface[] An array of Twig_TestInterface instances
869 public function getTests()
871 if (!$this->extensionInitialized
) {
872 $this->initExtensions();
879 * Gets a test by name.
881 * @param string $name The test name
883 * @return Twig_Test|false A Twig_Test instance or false if the test does not exist
885 public function getTest($name)
887 if (!$this->extensionInitialized
) {
888 $this->initExtensions();
891 if (isset($this->tests
[$name])) {
892 return $this->tests
[$name];
899 * Registers a Function.
901 * @param string|Twig_SimpleFunction $name The function name or a Twig_SimpleFunction instance
902 * @param Twig_FunctionInterface|Twig_SimpleFunction $function A Twig_FunctionInterface instance or a Twig_SimpleFunction instance
904 public function addFunction($name, $function = null)
906 if (!$name instanceof Twig_SimpleFunction
&& !($function instanceof Twig_SimpleFunction
|| $function instanceof Twig_FunctionInterface
)) {
907 throw new LogicException('A function must be an instance of Twig_FunctionInterface or Twig_SimpleFunction');
910 if ($name instanceof Twig_SimpleFunction
) {
912 $name = $function->getName();
915 if ($this->extensionInitialized
) {
916 throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $name));
919 $this->staging
->addFunction($name, $function);
923 * Get a function by name.
925 * Subclasses may override this method and load functions differently;
926 * so no list of functions is available.
928 * @param string $name function name
930 * @return Twig_Function|false A Twig_Function instance or false if the function does not exist
932 public function getFunction($name)
934 if (!$this->extensionInitialized
) {
935 $this->initExtensions();
938 if (isset($this->functions
[$name])) {
939 return $this->functions
[$name];
942 foreach ($this->functions
as $pattern => $function) {
943 $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count);
946 if (preg_match('#^'.$pattern.'$#', $name, $matches)) {
947 array_shift($matches);
948 $function->setArguments($matches);
955 foreach ($this->functionCallbacks
as $callback) {
956 if (false !== $function = call_user_func($callback, $name)) {
964 public function registerUndefinedFunctionCallback($callable)
966 $this->functionCallbacks
[] = $callable;
970 * Gets registered functions.
972 * Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback.
974 * @return Twig_FunctionInterface[] An array of Twig_FunctionInterface instances
976 * @see registerUndefinedFunctionCallback
978 public function getFunctions()
980 if (!$this->extensionInitialized
) {
981 $this->initExtensions();
984 return $this->functions
;
988 * Registers a Global.
990 * New globals can be added before compiling or rendering a template;
991 * but after, you can only update existing globals.
993 * @param string $name The global name
994 * @param mixed $value The global value
996 public function addGlobal($name, $value)
998 if ($this->extensionInitialized
|| $this->runtimeInitialized
) {
999 if (null === $this->globals
) {
1000 $this->globals
= $this->initGlobals();
1003 /* This condition must be uncommented in Twig 2.0
1004 if (!array_key_exists($name, $this->globals)) {
1005 throw new LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
1010 if ($this->extensionInitialized
|| $this->runtimeInitialized
) {
1012 $this->globals
[$name] = $value;
1014 $this->staging
->addGlobal($name, $value);
1019 * Gets the registered Globals.
1021 * @return array An array of globals
1023 public function getGlobals()
1025 if (!$this->runtimeInitialized
&& !$this->extensionInitialized
) {
1026 return $this->initGlobals();
1029 if (null === $this->globals
) {
1030 $this->globals
= $this->initGlobals();
1033 return $this->globals
;
1037 * Merges a context with the defined globals.
1039 * @param array $context An array representing the context
1041 * @return array The context merged with the globals
1043 public function mergeGlobals(array $context)
1045 // we don't use array_merge as the context being generally
1046 // bigger than globals, this code is faster.
1047 foreach ($this->getGlobals() as $key => $value) {
1048 if (!array_key_exists($key, $context)) {
1049 $context[$key] = $value;
1057 * Gets the registered unary Operators.
1059 * @return array An array of unary operators
1061 public function getUnaryOperators()
1063 if (!$this->extensionInitialized
) {
1064 $this->initExtensions();
1067 return $this->unaryOperators
;
1071 * Gets the registered binary Operators.
1073 * @return array An array of binary operators
1075 public function getBinaryOperators()
1077 if (!$this->extensionInitialized
) {
1078 $this->initExtensions();
1081 return $this->binaryOperators
;
1084 public function computeAlternatives($name, $items)
1086 $alternatives = array();
1087 foreach ($items as $item) {
1088 $lev = levenshtein($name, $item);
1089 if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
1090 $alternatives[$item] = $lev;
1093 asort($alternatives);
1095 return array_keys($alternatives);
1098 protected function initGlobals()
1101 foreach ($this->extensions
as $extension) {
1102 $extGlob = $extension->getGlobals();
1103 if (!is_array($extGlob)) {
1104 throw new UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', get_class($extension)));
1107 $globals[] = $extGlob;
1110 $globals[] = $this->staging
->getGlobals();
1112 return call_user_func_array('array_merge', $globals);
1115 protected function initExtensions()
1117 if ($this->extensionInitialized
) {
1121 $this->extensionInitialized
= true;
1122 $this->parsers
= new Twig_TokenParserBroker();
1123 $this->filters
= array();
1124 $this->functions
= array();
1125 $this->tests
= array();
1126 $this->visitors
= array();
1127 $this->unaryOperators
= array();
1128 $this->binaryOperators
= array();
1130 foreach ($this->extensions
as $extension) {
1131 $this->initExtension($extension);
1133 $this->initExtension($this->staging
);
1136 protected function initExtension(Twig_ExtensionInterface
$extension)
1139 foreach ($extension->getFilters() as $name => $filter) {
1140 if ($name instanceof Twig_SimpleFilter
) {
1142 $name = $filter->getName();
1143 } elseif ($filter instanceof Twig_SimpleFilter
) {
1144 $name = $filter->getName();
1147 $this->filters
[$name] = $filter;
1151 foreach ($extension->getFunctions() as $name => $function) {
1152 if ($name instanceof Twig_SimpleFunction
) {
1154 $name = $function->getName();
1155 } elseif ($function instanceof Twig_SimpleFunction
) {
1156 $name = $function->getName();
1159 $this->functions
[$name] = $function;
1163 foreach ($extension->getTests() as $name => $test) {
1164 if ($name instanceof Twig_SimpleTest
) {
1166 $name = $test->getName();
1167 } elseif ($test instanceof Twig_SimpleTest
) {
1168 $name = $test->getName();
1171 $this->tests
[$name] = $test;
1175 foreach ($extension->getTokenParsers() as $parser) {
1176 if ($parser instanceof Twig_TokenParserInterface
) {
1177 $this->parsers
->addTokenParser($parser);
1178 } elseif ($parser instanceof Twig_TokenParserBrokerInterface
) {
1179 $this->parsers
->addTokenParserBroker($parser);
1181 throw new LogicException('getTokenParsers() must return an array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances');
1186 foreach ($extension->getNodeVisitors() as $visitor) {
1187 $this->visitors
[] = $visitor;
1191 if ($operators = $extension->getOperators()) {
1192 if (2 !== count($operators)) {
1193 throw new InvalidArgumentException(sprintf('"%s::getOperators()" does not return a valid operators array.', get_class($extension)));
1196 $this->unaryOperators
= array_merge($this->unaryOperators
, $operators[0]);
1197 $this->binaryOperators
= array_merge($this->binaryOperators
, $operators[1]);
1201 protected function writeCacheFile($file, $content)
1203 $dir = dirname($file);
1204 if (!is_dir($dir)) {
1205 if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
1206 throw new RuntimeException(sprintf("Unable to create the cache directory (%s).", $dir));
1208 } elseif (!is_writable($dir)) {
1209 throw new RuntimeException(sprintf("Unable to write in the cache directory (%s).", $dir));
1212 $tmpFile = tempnam(dirname($file), basename($file));
1213 if (false !== @file_put_contents($tmpFile, $content)) {
1214 // rename does not work on Win32 before 5.2.6
1215 if (@rename($tmpFile, $file) || (@copy($tmpFile, $file) && unlink($tmpFile))) {
1216 @chmod($file, 0666 & ~
umask());
1222 throw new RuntimeException(sprintf('Failed to write cache file "%s".', $file));