Project

General

Profile

1
<?php
2

    
3
/*
4
 * This file is part of Twig.
5
 *
6
 * (c) 2009 Fabien Potencier
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

    
12
/**
13
 * Stores the Twig configuration.
14
 *
15
 * @author Fabien Potencier <fabien@symfony.com>
16
 */
17
class Twig_Environment
18
{
19
    const VERSION = '1.24.0';
20

    
21
    protected $charset;
22
    protected $loader;
23
    protected $debug;
24
    protected $autoReload;
25
    protected $cache;
26
    protected $lexer;
27
    protected $parser;
28
    protected $compiler;
29
    protected $baseTemplateClass;
30
    protected $extensions;
31
    protected $parsers;
32
    protected $visitors;
33
    protected $filters;
34
    protected $tests;
35
    protected $functions;
36
    protected $globals;
37
    protected $runtimeInitialized = false;
38
    protected $extensionInitialized = false;
39
    protected $loadedTemplates;
40
    protected $strictVariables;
41
    protected $unaryOperators;
42
    protected $binaryOperators;
43
    protected $templateClassPrefix = '__TwigTemplate_';
44
    protected $functionCallbacks = array();
45
    protected $filterCallbacks = array();
46
    protected $staging;
47

    
48
    private $originalCache;
49
    private $bcWriteCacheFile = false;
50
    private $bcGetCacheFilename = false;
51
    private $lastModifiedExtension = 0;
52

    
53
    /**
54
     * Constructor.
55
     *
56
     * Available options:
57
     *
58
     *  * debug: When set to true, it automatically set "auto_reload" to true as
59
     *           well (default to false).
60
     *
61
     *  * charset: The charset used by the templates (default to UTF-8).
62
     *
63
     *  * base_template_class: The base template class to use for generated
64
     *                         templates (default to Twig_Template).
65
     *
66
     *  * cache: An absolute path where to store the compiled templates,
67
     *           a Twig_Cache_Interface implementation,
68
     *           or false to disable compilation cache (default).
69
     *
70
     *  * auto_reload: Whether to reload the template if the original source changed.
71
     *                 If you don't provide the auto_reload option, it will be
72
     *                 determined automatically based on the debug value.
73
     *
74
     *  * strict_variables: Whether to ignore invalid variables in templates
75
     *                      (default to false).
76
     *
77
     *  * autoescape: Whether to enable auto-escaping (default to html):
78
     *                  * false: disable auto-escaping
79
     *                  * true: equivalent to html
80
     *                  * html, js: set the autoescaping to one of the supported strategies
81
     *                  * filename: set the autoescaping strategy based on the template filename extension
82
     *                  * PHP callback: a PHP callback that returns an escaping strategy based on the template "filename"
83
     *
84
     *  * optimizations: A flag that indicates which optimizations to apply
85
     *                   (default to -1 which means that all optimizations are enabled;
86
     *                   set it to 0 to disable).
87
     *
88
     * @param Twig_LoaderInterface $loader  A Twig_LoaderInterface instance
89
     * @param array                $options An array of options
90
     */
91
    public function __construct(Twig_LoaderInterface $loader = null, $options = array())
92
    {
93
        if (null !== $loader) {
94
            $this->setLoader($loader);
95
        } else {
96
            @trigger_error('Not passing a Twig_LoaderInterface as the first constructor argument of Twig_Environment is deprecated since version 1.21.', E_USER_DEPRECATED);
97
        }
98

    
99
        $options = array_merge(array(
100
            'debug' => false,
101
            'charset' => 'UTF-8',
102
            'base_template_class' => 'Twig_Template',
103
            'strict_variables' => false,
104
            'autoescape' => 'html',
105
            'cache' => false,
106
            'auto_reload' => null,
107
            'optimizations' => -1,
108
        ), $options);
109

    
110
        $this->debug = (bool) $options['debug'];
111
        $this->charset = strtoupper($options['charset']);
112
        $this->baseTemplateClass = $options['base_template_class'];
113
        $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload'];
114
        $this->strictVariables = (bool) $options['strict_variables'];
115
        $this->setCache($options['cache']);
116

    
117
        $this->addExtension(new Twig_Extension_Core());
118
        $this->addExtension(new Twig_Extension_Escaper($options['autoescape']));
119
        $this->addExtension(new Twig_Extension_Optimizer($options['optimizations']));
120
        $this->staging = new Twig_Extension_Staging();
121

    
122
        // For BC
123
        if (is_string($this->originalCache)) {
124
            $r = new ReflectionMethod($this, 'writeCacheFile');
125
            if ($r->getDeclaringClass()->getName() !== __CLASS__) {
126
                @trigger_error('The Twig_Environment::writeCacheFile method is deprecated since version 1.22 and will be removed in Twig 2.0.', E_USER_DEPRECATED);
127

    
128
                $this->bcWriteCacheFile = true;
129
            }
130

    
131
            $r = new ReflectionMethod($this, 'getCacheFilename');
132
            if ($r->getDeclaringClass()->getName() !== __CLASS__) {
133
                @trigger_error('The Twig_Environment::getCacheFilename method is deprecated since version 1.22 and will be removed in Twig 2.0.', E_USER_DEPRECATED);
134

    
135
                $this->bcGetCacheFilename = true;
136
            }
137
        }
138
    }
139

    
140
    /**
141
     * Gets the base template class for compiled templates.
142
     *
143
     * @return string The base template class name
144
     */
145
    public function getBaseTemplateClass()
146
    {
147
        return $this->baseTemplateClass;
148
    }
149

    
150
    /**
151
     * Sets the base template class for compiled templates.
152
     *
153
     * @param string $class The base template class name
154
     */
155
    public function setBaseTemplateClass($class)
156
    {
157
        $this->baseTemplateClass = $class;
158
    }
159

    
160
    /**
161
     * Enables debugging mode.
162
     */
163
    public function enableDebug()
164
    {
165
        $this->debug = true;
166
    }
167

    
168
    /**
169
     * Disables debugging mode.
170
     */
171
    public function disableDebug()
172
    {
173
        $this->debug = false;
174
    }
175

    
176
    /**
177
     * Checks if debug mode is enabled.
178
     *
179
     * @return bool true if debug mode is enabled, false otherwise
180
     */
181
    public function isDebug()
182
    {
183
        return $this->debug;
184
    }
185

    
186
    /**
187
     * Enables the auto_reload option.
188
     */
189
    public function enableAutoReload()
190
    {
191
        $this->autoReload = true;
192
    }
193

    
194
    /**
195
     * Disables the auto_reload option.
196
     */
197
    public function disableAutoReload()
198
    {
199
        $this->autoReload = false;
200
    }
201

    
202
    /**
203
     * Checks if the auto_reload option is enabled.
204
     *
205
     * @return bool true if auto_reload is enabled, false otherwise
206
     */
207
    public function isAutoReload()
208
    {
209
        return $this->autoReload;
210
    }
211

    
212
    /**
213
     * Enables the strict_variables option.
214
     */
215
    public function enableStrictVariables()
216
    {
217
        $this->strictVariables = true;
218
    }
219

    
220
    /**
221
     * Disables the strict_variables option.
222
     */
223
    public function disableStrictVariables()
224
    {
225
        $this->strictVariables = false;
226
    }
227

    
228
    /**
229
     * Checks if the strict_variables option is enabled.
230
     *
231
     * @return bool true if strict_variables is enabled, false otherwise
232
     */
233
    public function isStrictVariables()
234
    {
235
        return $this->strictVariables;
236
    }
237

    
238
    /**
239
     * Gets the current cache implementation.
240
     *
241
     * @param bool $original Whether to return the original cache option or the real cache instance
242
     *
243
     * @return Twig_CacheInterface|string|false A Twig_CacheInterface implementation,
244
     *                                          an absolute path to the compiled templates,
245
     *                                          or false to disable cache
246
     */
247
    public function getCache($original = true)
248
    {
249
        return $original ? $this->originalCache : $this->cache;
250
    }
251

    
252
    /**
253
     * Sets the current cache implementation.
254
     *
255
     * @param Twig_CacheInterface|string|false $cache A Twig_CacheInterface implementation,
256
     *                                                an absolute path to the compiled templates,
257
     *                                                or false to disable cache
258
     */
259
    public function setCache($cache)
260
    {
261
        if (is_string($cache)) {
262
            $this->originalCache = $cache;
263
            $this->cache = new Twig_Cache_Filesystem($cache);
264
        } elseif (false === $cache) {
265
            $this->originalCache = $cache;
266
            $this->cache = new Twig_Cache_Null();
267
        } elseif (null === $cache) {
268
            @trigger_error('Using "null" as the cache strategy is deprecated since version 1.23 and will be removed in Twig 2.0.', E_USER_DEPRECATED);
269
            $this->originalCache = false;
270
            $this->cache = new Twig_Cache_Null();
271
        } elseif ($cache instanceof Twig_CacheInterface) {
272
            $this->originalCache = $this->cache = $cache;
273
        } else {
274
            throw new LogicException(sprintf('Cache can only be a string, false, or a Twig_CacheInterface implementation.'));
275
        }
276
    }
277

    
278
    /**
279
     * Gets the cache filename for a given template.
280
     *
281
     * @param string $name The template name
282
     *
283
     * @return string|false The cache file name or false when caching is disabled
284
     *
285
     * @deprecated since 1.22 (to be removed in 2.0)
286
     */
287
    public function getCacheFilename($name)
288
    {
289
        @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
290

    
291
        $key = $this->cache->generateKey($name, $this->getTemplateClass($name));
292

    
293
        return !$key ? false : $key;
294
    }
295

    
296
    /**
297
     * Gets the template class associated with the given string.
298
     *
299
     * The generated template class is based on the following parameters:
300
     *
301
     *  * The cache key for the given template;
302
     *  * The currently enabled extensions;
303
     *  * Whether the Twig C extension is available or not.
304
     *
305
     * @param string   $name  The name for which to calculate the template class name
306
     * @param int|null $index The index if it is an embedded template
307
     *
308
     * @return string The template class name
309
     */
310
    public function getTemplateClass($name, $index = null)
311
    {
312
        $key = $this->getLoader()->getCacheKey($name);
313
        $key .= json_encode(array_keys($this->extensions));
314
        $key .= function_exists('twig_template_get_attributes');
315

    
316
        return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '_'.$index);
317
    }
318

    
319
    /**
320
     * Gets the template class prefix.
321
     *
322
     * @return string The template class prefix
323
     *
324
     * @deprecated since 1.22 (to be removed in 2.0)
325
     */
326
    public function getTemplateClassPrefix()
327
    {
328
        @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
329

    
330
        return $this->templateClassPrefix;
331
    }
332

    
333
    /**
334
     * Renders a template.
335
     *
336
     * @param string $name    The template name
337
     * @param array  $context An array of parameters to pass to the template
338
     *
339
     * @return string The rendered template
340
     *
341
     * @throws Twig_Error_Loader  When the template cannot be found
342
     * @throws Twig_Error_Syntax  When an error occurred during compilation
343
     * @throws Twig_Error_Runtime When an error occurred during rendering
344
     */
345
    public function render($name, array $context = array())
346
    {
347
        return $this->loadTemplate($name)->render($context);
348
    }
349

    
350
    /**
351
     * Displays a template.
352
     *
353
     * @param string $name    The template name
354
     * @param array  $context An array of parameters to pass to the template
355
     *
356
     * @throws Twig_Error_Loader  When the template cannot be found
357
     * @throws Twig_Error_Syntax  When an error occurred during compilation
358
     * @throws Twig_Error_Runtime When an error occurred during rendering
359
     */
360
    public function display($name, array $context = array())
361
    {
362
        $this->loadTemplate($name)->display($context);
363
    }
364

    
365
    /**
366
     * Loads a template by name.
367
     *
368
     * @param string $name  The template name
369
     * @param int    $index The index if it is an embedded template
370
     *
371
     * @return Twig_TemplateInterface A template instance representing the given template name
372
     *
373
     * @throws Twig_Error_Loader When the template cannot be found
374
     * @throws Twig_Error_Syntax When an error occurred during compilation
375
     */
376
    public function loadTemplate($name, $index = null)
377
    {
378
        $cls = $this->getTemplateClass($name, $index);
379

    
380
        if (isset($this->loadedTemplates[$cls])) {
381
            return $this->loadedTemplates[$cls];
382
        }
383

    
384
        if (!class_exists($cls, false)) {
385
            if ($this->bcGetCacheFilename) {
386
                $key = $this->getCacheFilename($name);
387
            } else {
388
                $key = $this->cache->generateKey($name, $cls);
389
            }
390

    
391
            if (!$this->isAutoReload() || $this->isTemplateFresh($name, $this->cache->getTimestamp($key))) {
392
                $this->cache->load($key);
393
            }
394

    
395
            if (!class_exists($cls, false)) {
396
                $content = $this->compileSource($this->getLoader()->getSource($name), $name);
397
                if ($this->bcWriteCacheFile) {
398
                    $this->writeCacheFile($key, $content);
399
                } else {
400
                    $this->cache->write($key, $content);
401
                }
402

    
403
                eval('?>'.$content);
404
            }
405
        }
406

    
407
        if (!$this->runtimeInitialized) {
408
            $this->initRuntime();
409
        }
410

    
411
        return $this->loadedTemplates[$cls] = new $cls($this);
412
    }
413

    
414
    /**
415
     * Creates a template from source.
416
     *
417
     * This method should not be used as a generic way to load templates.
418
     *
419
     * @param string $template The template name
420
     *
421
     * @return Twig_Template A template instance representing the given template name
422
     *
423
     * @throws Twig_Error_Loader When the template cannot be found
424
     * @throws Twig_Error_Syntax When an error occurred during compilation
425
     */
426
    public function createTemplate($template)
427
    {
428
        $name = sprintf('__string_template__%s', hash('sha256', uniqid(mt_rand(), true), false));
429

    
430
        $loader = new Twig_Loader_Chain(array(
431
            new Twig_Loader_Array(array($name => $template)),
432
            $current = $this->getLoader(),
433
        ));
434

    
435
        $this->setLoader($loader);
436
        try {
437
            $template = $this->loadTemplate($name);
438
        } catch (Exception $e) {
439
            $this->setLoader($current);
440

    
441
            throw $e;
442
        }
443
        $this->setLoader($current);
444

    
445
        return $template;
446
    }
447

    
448
    /**
449
     * Returns true if the template is still fresh.
450
     *
451
     * Besides checking the loader for freshness information,
452
     * this method also checks if the enabled extensions have
453
     * not changed.
454
     *
455
     * @param string $name The template name
456
     * @param int    $time The last modification time of the cached template
457
     *
458
     * @return bool true if the template is fresh, false otherwise
459
     */
460
    public function isTemplateFresh($name, $time)
461
    {
462
        if (0 === $this->lastModifiedExtension) {
463
            foreach ($this->extensions as $extension) {
464
                $r = new ReflectionObject($extension);
465
                if (file_exists($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModifiedExtension) {
466
                    $this->lastModifiedExtension = $extensionTime;
467
                }
468
            }
469
        }
470

    
471
        return $this->lastModifiedExtension <= $time && $this->getLoader()->isFresh($name, $time);
472
    }
473

    
474
    /**
475
     * Tries to load a template consecutively from an array.
476
     *
477
     * Similar to loadTemplate() but it also accepts Twig_TemplateInterface instances and an array
478
     * of templates where each is tried to be loaded.
479
     *
480
     * @param string|Twig_Template|array $names A template or an array of templates to try consecutively
481
     *
482
     * @return Twig_Template
483
     *
484
     * @throws Twig_Error_Loader When none of the templates can be found
485
     * @throws Twig_Error_Syntax When an error occurred during compilation
486
     */
487
    public function resolveTemplate($names)
488
    {
489
        if (!is_array($names)) {
490
            $names = array($names);
491
        }
492

    
493
        foreach ($names as $name) {
494
            if ($name instanceof Twig_Template) {
495
                return $name;
496
            }
497

    
498
            try {
499
                return $this->loadTemplate($name);
500
            } catch (Twig_Error_Loader $e) {
501
            }
502
        }
503

    
504
        if (1 === count($names)) {
505
            throw $e;
506
        }
507

    
508
        throw new Twig_Error_Loader(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
509
    }
510

    
511
    /**
512
     * Clears the internal template cache.
513
     *
514
     * @deprecated since 1.18.3 (to be removed in 2.0)
515
     */
516
    public function clearTemplateCache()
517
    {
518
        @trigger_error(sprintf('The %s method is deprecated since version 1.18.3 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
519

    
520
        $this->loadedTemplates = array();
521
    }
522

    
523
    /**
524
     * Clears the template cache files on the filesystem.
525
     *
526
     * @deprecated since 1.22 (to be removed in 2.0)
527
     */
528
    public function clearCacheFiles()
529
    {
530
        @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
531

    
532
        if (is_string($this->originalCache)) {
533
            foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->originalCache), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
534
                if ($file->isFile()) {
535
                    @unlink($file->getPathname());
536
                }
537
            }
538
        }
539
    }
540

    
541
    /**
542
     * Gets the Lexer instance.
543
     *
544
     * @return Twig_LexerInterface A Twig_LexerInterface instance
545
     */
546
    public function getLexer()
547
    {
548
        if (null === $this->lexer) {
549
            $this->lexer = new Twig_Lexer($this);
550
        }
551

    
552
        return $this->lexer;
553
    }
554

    
555
    /**
556
     * Sets the Lexer instance.
557
     *
558
     * @param Twig_LexerInterface $lexer A Twig_LexerInterface instance
559
     */
560
    public function setLexer(Twig_LexerInterface $lexer)
561
    {
562
        $this->lexer = $lexer;
563
    }
564

    
565
    /**
566
     * Tokenizes a source code.
567
     *
568
     * @param string $source The template source code
569
     * @param string $name   The template name
570
     *
571
     * @return Twig_TokenStream A Twig_TokenStream instance
572
     *
573
     * @throws Twig_Error_Syntax When the code is syntactically wrong
574
     */
575
    public function tokenize($source, $name = null)
576
    {
577
        return $this->getLexer()->tokenize($source, $name);
578
    }
579

    
580
    /**
581
     * Gets the Parser instance.
582
     *
583
     * @return Twig_ParserInterface A Twig_ParserInterface instance
584
     */
585
    public function getParser()
586
    {
587
        if (null === $this->parser) {
588
            $this->parser = new Twig_Parser($this);
589
        }
590

    
591
        return $this->parser;
592
    }
593

    
594
    /**
595
     * Sets the Parser instance.
596
     *
597
     * @param Twig_ParserInterface $parser A Twig_ParserInterface instance
598
     */
599
    public function setParser(Twig_ParserInterface $parser)
600
    {
601
        $this->parser = $parser;
602
    }
603

    
604
    /**
605
     * Converts a token stream to a node tree.
606
     *
607
     * @param Twig_TokenStream $stream A token stream instance
608
     *
609
     * @return Twig_Node_Module A node tree
610
     *
611
     * @throws Twig_Error_Syntax When the token stream is syntactically or semantically wrong
612
     */
613
    public function parse(Twig_TokenStream $stream)
614
    {
615
        return $this->getParser()->parse($stream);
616
    }
617

    
618
    /**
619
     * Gets the Compiler instance.
620
     *
621
     * @return Twig_CompilerInterface A Twig_CompilerInterface instance
622
     */
623
    public function getCompiler()
624
    {
625
        if (null === $this->compiler) {
626
            $this->compiler = new Twig_Compiler($this);
627
        }
628

    
629
        return $this->compiler;
630
    }
631

    
632
    /**
633
     * Sets the Compiler instance.
634
     *
635
     * @param Twig_CompilerInterface $compiler A Twig_CompilerInterface instance
636
     */
637
    public function setCompiler(Twig_CompilerInterface $compiler)
638
    {
639
        $this->compiler = $compiler;
640
    }
641

    
642
    /**
643
     * Compiles a node and returns the PHP code.
644
     *
645
     * @param Twig_NodeInterface $node A Twig_NodeInterface instance
646
     *
647
     * @return string The compiled PHP source code
648
     */
649
    public function compile(Twig_NodeInterface $node)
650
    {
651
        return $this->getCompiler()->compile($node)->getSource();
652
    }
653

    
654
    /**
655
     * Compiles a template source code.
656
     *
657
     * @param string $source The template source code
658
     * @param string $name   The template name
659
     *
660
     * @return string The compiled PHP source code
661
     *
662
     * @throws Twig_Error_Syntax When there was an error during tokenizing, parsing or compiling
663
     */
664
    public function compileSource($source, $name = null)
665
    {
666
        try {
667
            $compiled = $this->compile($this->parse($this->tokenize($source, $name)), $source);
668

    
669
            if (isset($source[0])) {
670
                $compiled .= '/* '.str_replace(array('*/', "\r\n", "\r", "\n"), array('*//* ', "\n", "\n", "*/\n/* "), $source)."*/\n";
671
            }
672

    
673
            return $compiled;
674
        } catch (Twig_Error $e) {
675
            $e->setTemplateFile($name);
676
            throw $e;
677
        } catch (Exception $e) {
678
            throw new Twig_Error_Syntax(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $name, $e);
679
        }
680
    }
681

    
682
    /**
683
     * Sets the Loader instance.
684
     *
685
     * @param Twig_LoaderInterface $loader A Twig_LoaderInterface instance
686
     */
687
    public function setLoader(Twig_LoaderInterface $loader)
688
    {
689
        $this->loader = $loader;
690
    }
691

    
692
    /**
693
     * Gets the Loader instance.
694
     *
695
     * @return Twig_LoaderInterface A Twig_LoaderInterface instance
696
     */
697
    public function getLoader()
698
    {
699
        if (null === $this->loader) {
700
            throw new LogicException('You must set a loader first.');
701
        }
702

    
703
        return $this->loader;
704
    }
705

    
706
    /**
707
     * Sets the default template charset.
708
     *
709
     * @param string $charset The default charset
710
     */
711
    public function setCharset($charset)
712
    {
713
        $this->charset = strtoupper($charset);
714
    }
715

    
716
    /**
717
     * Gets the default template charset.
718
     *
719
     * @return string The default charset
720
     */
721
    public function getCharset()
722
    {
723
        return $this->charset;
724
    }
725

    
726
    /**
727
     * Initializes the runtime environment.
728
     *
729
     * @deprecated since 1.23 (to be removed in 2.0)
730
     */
731
    public function initRuntime()
732
    {
733
        $this->runtimeInitialized = true;
734

    
735
        foreach ($this->getExtensions() as $name => $extension) {
736
            if (!$extension instanceof Twig_Extension_InitRuntimeInterface) {
737
                $m = new ReflectionMethod($extension, 'initRuntime');
738

    
739
                if ('Twig_Extension' !== $m->getDeclaringClass()->getName()) {
740
                    @trigger_error(sprintf('Defining the initRuntime() method in the "%s" extension is deprecated since version 1.23. Use the `needs_environment` option to get the Twig_Environment instance in filters, functions, or tests; or explicitly implement Twig_Extension_InitRuntimeInterface if needed (not recommended).', $name), E_USER_DEPRECATED);
741
                }
742
            }
743

    
744
            $extension->initRuntime($this);
745
        }
746
    }
747

    
748
    /**
749
     * Returns true if the given extension is registered.
750
     *
751
     * @param string $name The extension name
752
     *
753
     * @return bool Whether the extension is registered or not
754
     */
755
    public function hasExtension($name)
756
    {
757
        return isset($this->extensions[$name]);
758
    }
759

    
760
    /**
761
     * Gets an extension by name.
762
     *
763
     * @param string $name The extension name
764
     *
765
     * @return Twig_ExtensionInterface A Twig_ExtensionInterface instance
766
     */
767
    public function getExtension($name)
768
    {
769
        if (!isset($this->extensions[$name])) {
770
            throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $name));
771
        }
772

    
773
        return $this->extensions[$name];
774
    }
775

    
776
    /**
777
     * Registers an extension.
778
     *
779
     * @param Twig_ExtensionInterface $extension A Twig_ExtensionInterface instance
780
     */
781
    public function addExtension(Twig_ExtensionInterface $extension)
782
    {
783
        $name = $extension->getName();
784

    
785
        if ($this->extensionInitialized) {
786
            throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $name));
787
        }
788

    
789
        if (isset($this->extensions[$name])) {
790
            @trigger_error(sprintf('The possibility to register the same extension twice ("%s") is deprecated since version 1.23 and will be removed in Twig 2.0. Use proper PHP inheritance instead.', $name), E_USER_DEPRECATED);
791
        }
792

    
793
        $this->lastModifiedExtension = 0;
794

    
795
        $this->extensions[$name] = $extension;
796
    }
797

    
798
    /**
799
     * Removes an extension by name.
800
     *
801
     * This method is deprecated and you should not use it.
802
     *
803
     * @param string $name The extension name
804
     *
805
     * @deprecated since 1.12 (to be removed in 2.0)
806
     */
807
    public function removeExtension($name)
808
    {
809
        @trigger_error(sprintf('The %s method is deprecated since version 1.12 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
810

    
811
        if ($this->extensionInitialized) {
812
            throw new LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name));
813
        }
814

    
815
        unset($this->extensions[$name]);
816
    }
817

    
818
    /**
819
     * Registers an array of extensions.
820
     *
821
     * @param array $extensions An array of extensions
822
     */
823
    public function setExtensions(array $extensions)
824
    {
825
        foreach ($extensions as $extension) {
826
            $this->addExtension($extension);
827
        }
828
    }
829

    
830
    /**
831
     * Returns all registered extensions.
832
     *
833
     * @return array An array of extensions
834
     */
835
    public function getExtensions()
836
    {
837
        return $this->extensions;
838
    }
839

    
840
    /**
841
     * Registers a Token Parser.
842
     *
843
     * @param Twig_TokenParserInterface $parser A Twig_TokenParserInterface instance
844
     */
845
    public function addTokenParser(Twig_TokenParserInterface $parser)
846
    {
847
        if ($this->extensionInitialized) {
848
            throw new LogicException('Unable to add a token parser as extensions have already been initialized.');
849
        }
850

    
851
        $this->staging->addTokenParser($parser);
852
    }
853

    
854
    /**
855
     * Gets the registered Token Parsers.
856
     *
857
     * @return Twig_TokenParserBrokerInterface A broker containing token parsers
858
     */
859
    public function getTokenParsers()
860
    {
861
        if (!$this->extensionInitialized) {
862
            $this->initExtensions();
863
        }
864

    
865
        return $this->parsers;
866
    }
867

    
868
    /**
869
     * Gets registered tags.
870
     *
871
     * Be warned that this method cannot return tags defined by Twig_TokenParserBrokerInterface classes.
872
     *
873
     * @return Twig_TokenParserInterface[] An array of Twig_TokenParserInterface instances
874
     */
875
    public function getTags()
876
    {
877
        $tags = array();
878
        foreach ($this->getTokenParsers()->getParsers() as $parser) {
879
            if ($parser instanceof Twig_TokenParserInterface) {
880
                $tags[$parser->getTag()] = $parser;
881
            }
882
        }
883

    
884
        return $tags;
885
    }
886

    
887
    /**
888
     * Registers a Node Visitor.
889
     *
890
     * @param Twig_NodeVisitorInterface $visitor A Twig_NodeVisitorInterface instance
891
     */
892
    public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
893
    {
894
        if ($this->extensionInitialized) {
895
            throw new LogicException('Unable to add a node visitor as extensions have already been initialized.');
896
        }
897

    
898
        $this->staging->addNodeVisitor($visitor);
899
    }
900

    
901
    /**
902
     * Gets the registered Node Visitors.
903
     *
904
     * @return Twig_NodeVisitorInterface[] An array of Twig_NodeVisitorInterface instances
905
     */
906
    public function getNodeVisitors()
907
    {
908
        if (!$this->extensionInitialized) {
909
            $this->initExtensions();
910
        }
911

    
912
        return $this->visitors;
913
    }
914

    
915
    /**
916
     * Registers a Filter.
917
     *
918
     * @param string|Twig_SimpleFilter               $name   The filter name or a Twig_SimpleFilter instance
919
     * @param Twig_FilterInterface|Twig_SimpleFilter $filter A Twig_FilterInterface instance or a Twig_SimpleFilter instance
920
     */
921
    public function addFilter($name, $filter = null)
922
    {
923
        if (!$name instanceof Twig_SimpleFilter && !($filter instanceof Twig_SimpleFilter || $filter instanceof Twig_FilterInterface)) {
924
            throw new LogicException('A filter must be an instance of Twig_FilterInterface or Twig_SimpleFilter');
925
        }
926

    
927
        if ($name instanceof Twig_SimpleFilter) {
928
            $filter = $name;
929
            $name = $filter->getName();
930
        } else {
931
            @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleFilter" instead when defining filter "%s".', __METHOD__, $name), E_USER_DEPRECATED);
932
        }
933

    
934
        if ($this->extensionInitialized) {
935
            throw new LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $name));
936
        }
937

    
938
        $this->staging->addFilter($name, $filter);
939
    }
940

    
941
    /**
942
     * Get a filter by name.
943
     *
944
     * Subclasses may override this method and load filters differently;
945
     * so no list of filters is available.
946
     *
947
     * @param string $name The filter name
948
     *
949
     * @return Twig_Filter|false A Twig_Filter instance or false if the filter does not exist
950
     */
951
    public function getFilter($name)
952
    {
953
        if (!$this->extensionInitialized) {
954
            $this->initExtensions();
955
        }
956

    
957
        if (isset($this->filters[$name])) {
958
            return $this->filters[$name];
959
        }
960

    
961
        foreach ($this->filters as $pattern => $filter) {
962
            $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count);
963

    
964
            if ($count) {
965
                if (preg_match('#^'.$pattern.'$#', $name, $matches)) {
966
                    array_shift($matches);
967
                    $filter->setArguments($matches);
968

    
969
                    return $filter;
970
                }
971
            }
972
        }
973

    
974
        foreach ($this->filterCallbacks as $callback) {
975
            if (false !== $filter = call_user_func($callback, $name)) {
976
                return $filter;
977
            }
978
        }
979

    
980
        return false;
981
    }
982

    
983
    public function registerUndefinedFilterCallback($callable)
984
    {
985
        $this->filterCallbacks[] = $callable;
986
    }
987

    
988
    /**
989
     * Gets the registered Filters.
990
     *
991
     * Be warned that this method cannot return filters defined with registerUndefinedFilterCallback.
992
     *
993
     * @return Twig_FilterInterface[] An array of Twig_FilterInterface instances
994
     *
995
     * @see registerUndefinedFilterCallback
996
     */
997
    public function getFilters()
998
    {
999
        if (!$this->extensionInitialized) {
1000
            $this->initExtensions();
1001
        }
1002

    
1003
        return $this->filters;
1004
    }
1005

    
1006
    /**
1007
     * Registers a Test.
1008
     *
1009
     * @param string|Twig_SimpleTest             $name The test name or a Twig_SimpleTest instance
1010
     * @param Twig_TestInterface|Twig_SimpleTest $test A Twig_TestInterface instance or a Twig_SimpleTest instance
1011
     */
1012
    public function addTest($name, $test = null)
1013
    {
1014
        if (!$name instanceof Twig_SimpleTest && !($test instanceof Twig_SimpleTest || $test instanceof Twig_TestInterface)) {
1015
            throw new LogicException('A test must be an instance of Twig_TestInterface or Twig_SimpleTest');
1016
        }
1017

    
1018
        if ($name instanceof Twig_SimpleTest) {
1019
            $test = $name;
1020
            $name = $test->getName();
1021
        } else {
1022
            @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleTest" instead when defining test "%s".', __METHOD__, $name), E_USER_DEPRECATED);
1023
        }
1024

    
1025
        if ($this->extensionInitialized) {
1026
            throw new LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $name));
1027
        }
1028

    
1029
        $this->staging->addTest($name, $test);
1030
    }
1031

    
1032
    /**
1033
     * Gets the registered Tests.
1034
     *
1035
     * @return Twig_TestInterface[] An array of Twig_TestInterface instances
1036
     */
1037
    public function getTests()
1038
    {
1039
        if (!$this->extensionInitialized) {
1040
            $this->initExtensions();
1041
        }
1042

    
1043
        return $this->tests;
1044
    }
1045

    
1046
    /**
1047
     * Gets a test by name.
1048
     *
1049
     * @param string $name The test name
1050
     *
1051
     * @return Twig_Test|false A Twig_Test instance or false if the test does not exist
1052
     */
1053
    public function getTest($name)
1054
    {
1055
        if (!$this->extensionInitialized) {
1056
            $this->initExtensions();
1057
        }
1058

    
1059
        if (isset($this->tests[$name])) {
1060
            return $this->tests[$name];
1061
        }
1062

    
1063
        return false;
1064
    }
1065

    
1066
    /**
1067
     * Registers a Function.
1068
     *
1069
     * @param string|Twig_SimpleFunction                 $name     The function name or a Twig_SimpleFunction instance
1070
     * @param Twig_FunctionInterface|Twig_SimpleFunction $function A Twig_FunctionInterface instance or a Twig_SimpleFunction instance
1071
     */
1072
    public function addFunction($name, $function = null)
1073
    {
1074
        if (!$name instanceof Twig_SimpleFunction && !($function instanceof Twig_SimpleFunction || $function instanceof Twig_FunctionInterface)) {
1075
            throw new LogicException('A function must be an instance of Twig_FunctionInterface or Twig_SimpleFunction');
1076
        }
1077

    
1078
        if ($name instanceof Twig_SimpleFunction) {
1079
            $function = $name;
1080
            $name = $function->getName();
1081
        } else {
1082
            @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleFunction" instead when defining function "%s".', __METHOD__, $name), E_USER_DEPRECATED);
1083
        }
1084

    
1085
        if ($this->extensionInitialized) {
1086
            throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $name));
1087
        }
1088

    
1089
        $this->staging->addFunction($name, $function);
1090
    }
1091

    
1092
    /**
1093
     * Get a function by name.
1094
     *
1095
     * Subclasses may override this method and load functions differently;
1096
     * so no list of functions is available.
1097
     *
1098
     * @param string $name function name
1099
     *
1100
     * @return Twig_Function|false A Twig_Function instance or false if the function does not exist
1101
     */
1102
    public function getFunction($name)
1103
    {
1104
        if (!$this->extensionInitialized) {
1105
            $this->initExtensions();
1106
        }
1107

    
1108
        if (isset($this->functions[$name])) {
1109
            return $this->functions[$name];
1110
        }
1111

    
1112
        foreach ($this->functions as $pattern => $function) {
1113
            $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count);
1114

    
1115
            if ($count) {
1116
                if (preg_match('#^'.$pattern.'$#', $name, $matches)) {
1117
                    array_shift($matches);
1118
                    $function->setArguments($matches);
1119

    
1120
                    return $function;
1121
                }
1122
            }
1123
        }
1124

    
1125
        foreach ($this->functionCallbacks as $callback) {
1126
            if (false !== $function = call_user_func($callback, $name)) {
1127
                return $function;
1128
            }
1129
        }
1130

    
1131
        return false;
1132
    }
1133

    
1134
    public function registerUndefinedFunctionCallback($callable)
1135
    {
1136
        $this->functionCallbacks[] = $callable;
1137
    }
1138

    
1139
    /**
1140
     * Gets registered functions.
1141
     *
1142
     * Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback.
1143
     *
1144
     * @return Twig_FunctionInterface[] An array of Twig_FunctionInterface instances
1145
     *
1146
     * @see registerUndefinedFunctionCallback
1147
     */
1148
    public function getFunctions()
1149
    {
1150
        if (!$this->extensionInitialized) {
1151
            $this->initExtensions();
1152
        }
1153

    
1154
        return $this->functions;
1155
    }
1156

    
1157
    /**
1158
     * Registers a Global.
1159
     *
1160
     * New globals can be added before compiling or rendering a template;
1161
     * but after, you can only update existing globals.
1162
     *
1163
     * @param string $name  The global name
1164
     * @param mixed  $value The global value
1165
     */
1166
    public function addGlobal($name, $value)
1167
    {
1168
        if ($this->extensionInitialized || $this->runtimeInitialized) {
1169
            if (null === $this->globals) {
1170
                $this->globals = $this->initGlobals();
1171
            }
1172

    
1173
            if (!array_key_exists($name, $this->globals)) {
1174
                // The deprecation notice must be turned into the following exception in Twig 2.0
1175
                @trigger_error(sprintf('Registering global variable "%s" at runtime or when the extensions have already been initialized is deprecated since version 1.21.', $name), E_USER_DEPRECATED);
1176
                //throw new LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
1177
            }
1178
        }
1179

    
1180
        if ($this->extensionInitialized || $this->runtimeInitialized) {
1181
            // update the value
1182
            $this->globals[$name] = $value;
1183
        } else {
1184
            $this->staging->addGlobal($name, $value);
1185
        }
1186
    }
1187

    
1188
    /**
1189
     * Gets the registered Globals.
1190
     *
1191
     * @return array An array of globals
1192
     */
1193
    public function getGlobals()
1194
    {
1195
        if (!$this->runtimeInitialized && !$this->extensionInitialized) {
1196
            return $this->initGlobals();
1197
        }
1198

    
1199
        if (null === $this->globals) {
1200
            $this->globals = $this->initGlobals();
1201
        }
1202

    
1203
        return $this->globals;
1204
    }
1205

    
1206
    /**
1207
     * Merges a context with the defined globals.
1208
     *
1209
     * @param array $context An array representing the context
1210
     *
1211
     * @return array The context merged with the globals
1212
     */
1213
    public function mergeGlobals(array $context)
1214
    {
1215
        // we don't use array_merge as the context being generally
1216
        // bigger than globals, this code is faster.
1217
        foreach ($this->getGlobals() as $key => $value) {
1218
            if (!array_key_exists($key, $context)) {
1219
                $context[$key] = $value;
1220
            }
1221
        }
1222

    
1223
        return $context;
1224
    }
1225

    
1226
    /**
1227
     * Gets the registered unary Operators.
1228
     *
1229
     * @return array An array of unary operators
1230
     */
1231
    public function getUnaryOperators()
1232
    {
1233
        if (!$this->extensionInitialized) {
1234
            $this->initExtensions();
1235
        }
1236

    
1237
        return $this->unaryOperators;
1238
    }
1239

    
1240
    /**
1241
     * Gets the registered binary Operators.
1242
     *
1243
     * @return array An array of binary operators
1244
     */
1245
    public function getBinaryOperators()
1246
    {
1247
        if (!$this->extensionInitialized) {
1248
            $this->initExtensions();
1249
        }
1250

    
1251
        return $this->binaryOperators;
1252
    }
1253

    
1254
    /**
1255
     * @deprecated since 1.23 (to be removed in 2.0)
1256
     */
1257
    public function computeAlternatives($name, $items)
1258
    {
1259
        @trigger_error(sprintf('The %s method is deprecated since version 1.23 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
1260

    
1261
        return Twig_Error_Syntax::computeAlternatives($name, $items);
1262
    }
1263

    
1264
    protected function initGlobals()
1265
    {
1266
        $globals = array();
1267
        foreach ($this->extensions as $name => $extension) {
1268
            if (!$extension instanceof Twig_Extension_GlobalsInterface) {
1269
                $m = new ReflectionMethod($extension, 'getGlobals');
1270

    
1271
                if ('Twig_Extension' !== $m->getDeclaringClass()->getName()) {
1272
                    @trigger_error(sprintf('Defining the getGlobals() method in the "%s" extension without explicitly implementing Twig_Extension_GlobalsInterface is deprecated since version 1.23.', $name), E_USER_DEPRECATED);
1273
                }
1274
            }
1275

    
1276
            $extGlob = $extension->getGlobals();
1277
            if (!is_array($extGlob)) {
1278
                throw new UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', get_class($extension)));
1279
            }
1280

    
1281
            $globals[] = $extGlob;
1282
        }
1283

    
1284
        $globals[] = $this->staging->getGlobals();
1285

    
1286
        return call_user_func_array('array_merge', $globals);
1287
    }
1288

    
1289
    protected function initExtensions()
1290
    {
1291
        if ($this->extensionInitialized) {
1292
            return;
1293
        }
1294

    
1295
        $this->extensionInitialized = true;
1296
        $this->parsers = new Twig_TokenParserBroker(array(), array(), false);
1297
        $this->filters = array();
1298
        $this->functions = array();
1299
        $this->tests = array();
1300
        $this->visitors = array();
1301
        $this->unaryOperators = array();
1302
        $this->binaryOperators = array();
1303

    
1304
        foreach ($this->extensions as $extension) {
1305
            $this->initExtension($extension);
1306
        }
1307
        $this->initExtension($this->staging);
1308
    }
1309

    
1310
    protected function initExtension(Twig_ExtensionInterface $extension)
1311
    {
1312
        // filters
1313
        foreach ($extension->getFilters() as $name => $filter) {
1314
            if ($filter instanceof Twig_SimpleFilter) {
1315
                $name = $filter->getName();
1316
            } else {
1317
                @trigger_error(sprintf('Using an instance of "%s" for filter "%s" is deprecated since version 1.21. Use Twig_SimpleFilter instead.', get_class($filter), $name), E_USER_DEPRECATED);
1318
            }
1319

    
1320
            $this->filters[$name] = $filter;
1321
        }
1322

    
1323
        // functions
1324
        foreach ($extension->getFunctions() as $name => $function) {
1325
            if ($function instanceof Twig_SimpleFunction) {
1326
                $name = $function->getName();
1327
            } else {
1328
                @trigger_error(sprintf('Using an instance of "%s" for function "%s" is deprecated since version 1.21. Use Twig_SimpleFunction instead.', get_class($function), $name), E_USER_DEPRECATED);
1329
            }
1330

    
1331
            $this->functions[$name] = $function;
1332
        }
1333

    
1334
        // tests
1335
        foreach ($extension->getTests() as $name => $test) {
1336
            if ($test instanceof Twig_SimpleTest) {
1337
                $name = $test->getName();
1338
            } else {
1339
                @trigger_error(sprintf('Using an instance of "%s" for test "%s" is deprecated since version 1.21. Use Twig_SimpleTest instead.', get_class($test), $name), E_USER_DEPRECATED);
1340
            }
1341

    
1342
            $this->tests[$name] = $test;
1343
        }
1344

    
1345
        // token parsers
1346
        foreach ($extension->getTokenParsers() as $parser) {
1347
            if ($parser instanceof Twig_TokenParserInterface) {
1348
                $this->parsers->addTokenParser($parser);
1349
            } elseif ($parser instanceof Twig_TokenParserBrokerInterface) {
1350
                @trigger_error('Registering a Twig_TokenParserBrokerInterface instance is deprecated since version 1.21.', E_USER_DEPRECATED);
1351

    
1352
                $this->parsers->addTokenParserBroker($parser);
1353
            } else {
1354
                throw new LogicException('getTokenParsers() must return an array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances');
1355
            }
1356
        }
1357

    
1358
        // node visitors
1359
        foreach ($extension->getNodeVisitors() as $visitor) {
1360
            $this->visitors[] = $visitor;
1361
        }
1362

    
1363
        // operators
1364
        if ($operators = $extension->getOperators()) {
1365
            if (2 !== count($operators)) {
1366
                throw new InvalidArgumentException(sprintf('"%s::getOperators()" does not return a valid operators array.', get_class($extension)));
1367
            }
1368

    
1369
            $this->unaryOperators = array_merge($this->unaryOperators, $operators[0]);
1370
            $this->binaryOperators = array_merge($this->binaryOperators, $operators[1]);
1371
        }
1372
    }
1373

    
1374
    /**
1375
     * @deprecated since 1.22 (to be removed in 2.0)
1376
     */
1377
    protected function writeCacheFile($file, $content)
1378
    {
1379
        $this->cache->write($file, $content);
1380
    }
1381
}
(6-6/43)