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
 * Loads a template from an array.
14
 *
15
 * When using this loader with a cache mechanism, you should know that a new cache
16
 * key is generated each time a template content "changes" (the cache key being the
17
 * source code of the template). If you don't want to see your cache grows out of
18
 * control, you need to take care of clearing the old cache file by yourself.
19
 *
20
 * @package    twig
21
 * @author     Fabien Potencier <fabien@symfony.com>
22
 */
23
class Twig_Loader_Array implements Twig_LoaderInterface, Twig_ExistsLoaderInterface
24
{
25
    protected $templates;
26

    
27
    /**
28
     * Constructor.
29
     *
30
     * @param array $templates An array of templates (keys are the names, and values are the source code)
31
     *
32
     * @see Twig_Loader
33
     */
34
    public function __construct(array $templates)
35
    {
36
        $this->templates = array();
37
        foreach ($templates as $name => $template) {
38
            $this->templates[$name] = $template;
39
        }
40
    }
41

    
42
    /**
43
     * Adds or overrides a template.
44
     *
45
     * @param string $name     The template name
46
     * @param string $template The template source
47
     */
48
    public function setTemplate($name, $template)
49
    {
50
        $this->templates[(string) $name] = $template;
51
    }
52

    
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function getSource($name)
57
    {
58
        $name = (string) $name;
59
        if (!isset($this->templates[$name])) {
60
            throw new Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
61
        }
62

    
63
        return $this->templates[$name];
64
    }
65

    
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function exists($name)
70
    {
71
        return isset($this->templates[(string) $name]);
72
    }
73

    
74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function getCacheKey($name)
78
    {
79
        $name = (string) $name;
80
        if (!isset($this->templates[$name])) {
81
            throw new Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
82
        }
83

    
84
        return $this->templates[$name];
85
    }
86

    
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function isFresh($name, $time)
91
    {
92
        $name = (string) $name;
93
        if (!isset($this->templates[$name])) {
94
            throw new Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
95
        }
96

    
97
        return true;
98
    }
99
}
(1-1/4)