1<?php
2
3/*
4 * This file is part of Mustache.php.
5 *
6 * (c) 2010-2017 Justin Hileman
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 * Mustache Template array Loader implementation.
14 *
15 * An ArrayLoader instance loads Mustache Template source by name from an initial array:
16 *
17 *     $loader = new ArrayLoader(
18 *         'foo' => '{{ bar }}',
19 *         'baz' => 'Hey {{ qux }}!'
20 *     );
21 *
22 *     $tpl = $loader->load('foo'); // '{{ bar }}'
23 *
24 * The ArrayLoader is used internally as a partials loader by Mustache_Engine instance when an array of partials
25 * is set. It can also be used as a quick-and-dirty Template loader.
26 */
27class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader
28{
29    private $templates;
30
31    /**
32     * ArrayLoader constructor.
33     *
34     * @param array $templates Associative array of Template source (default: array())
35     */
36    public function __construct(array $templates = array())
37    {
38        $this->templates = $templates;
39    }
40
41    /**
42     * Load a Template.
43     *
44     * @throws Mustache_Exception_UnknownTemplateException If a template file is not found
45     *
46     * @param string $name
47     *
48     * @return string Mustache Template source
49     */
50    public function load($name)
51    {
52        if (!isset($this->templates[$name])) {
53            throw new Mustache_Exception_UnknownTemplateException($name);
54        }
55
56        return $this->templates[$name];
57    }
58
59    /**
60     * Set an associative array of Template sources for this loader.
61     *
62     * @param array $templates
63     */
64    public function setTemplates(array $templates)
65    {
66        $this->templates = $templates;
67    }
68
69    /**
70     * Set a Template source by name.
71     *
72     * @param string $name
73     * @param string $template Mustache Template source
74     */
75    public function setTemplate($name, $template)
76    {
77        $this->templates[$name] = $template;
78    }
79}
80