1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) 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
12namespace Twig\Loader;
13
14use Twig\Error\LoaderError;
15use Twig\Source;
16
17/**
18 * Loads a template from an array.
19 *
20 * When using this loader with a cache mechanism, you should know that a new cache
21 * key is generated each time a template content "changes" (the cache key being the
22 * source code of the template). If you don't want to see your cache grows out of
23 * control, you need to take care of clearing the old cache file by yourself.
24 *
25 * This loader should only be used for unit testing.
26 *
27 * @author Fabien Potencier <fabien@symfony.com>
28 */
29final class ArrayLoader implements LoaderInterface, ExistsLoaderInterface, SourceContextLoaderInterface
30{
31    private $templates = [];
32
33    /**
34     * @param array $templates An array of templates (keys are the names, and values are the source code)
35     */
36    public function __construct(array $templates = [])
37    {
38        $this->templates = $templates;
39    }
40
41    /**
42     * Adds or overrides a template.
43     *
44     * @param string $name     The template name
45     * @param string $template The template source
46     */
47    public function setTemplate($name, $template)
48    {
49        $this->templates[$name] = $template;
50    }
51
52    public function getSourceContext($name)
53    {
54        $name = (string) $name;
55        if (!isset($this->templates[$name])) {
56            throw new LoaderError(sprintf('Template "%s" is not defined.', $name));
57        }
58
59        return new Source($this->templates[$name], $name);
60    }
61
62    public function exists($name)
63    {
64        return isset($this->templates[$name]);
65    }
66
67    public function getCacheKey($name)
68    {
69        if (!isset($this->templates[$name])) {
70            throw new LoaderError(sprintf('Template "%s" is not defined.', $name));
71        }
72
73        return $name.':'.$this->templates[$name];
74    }
75
76    public function isFresh($name, $time)
77    {
78        if (!isset($this->templates[$name])) {
79            throw new LoaderError(sprintf('Template "%s" is not defined.', $name));
80        }
81
82        return true;
83    }
84}
85
86class_alias('Twig\Loader\ArrayLoader', 'Twig_Loader_Array');
87