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 * A Mustache Template cascading loader implementation, which delegates to other
14 * Loader instances.
15 */
16class Mustache_Loader_CascadingLoader implements Mustache_Loader
17{
18    private $loaders;
19
20    /**
21     * Construct a CascadingLoader with an array of loaders.
22     *
23     *     $loader = new Mustache_Loader_CascadingLoader(array(
24     *         new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__),
25     *         new Mustache_Loader_FilesystemLoader(__DIR__.'/templates')
26     *     ));
27     *
28     * @param Mustache_Loader[] $loaders
29     */
30    public function __construct(array $loaders = array())
31    {
32        $this->loaders = array();
33        foreach ($loaders as $loader) {
34            $this->addLoader($loader);
35        }
36    }
37
38    /**
39     * Add a Loader instance.
40     *
41     * @param Mustache_Loader $loader
42     */
43    public function addLoader(Mustache_Loader $loader)
44    {
45        $this->loaders[] = $loader;
46    }
47
48    /**
49     * Load a Template by name.
50     *
51     * @throws Mustache_Exception_UnknownTemplateException If a template file is not found
52     *
53     * @param string $name
54     *
55     * @return string Mustache Template source
56     */
57    public function load($name)
58    {
59        foreach ($this->loaders as $loader) {
60            try {
61                return $loader->load($name);
62            } catch (Mustache_Exception_UnknownTemplateException $e) {
63                // do nothing, check the next loader.
64            }
65        }
66
67        throw new Mustache_Exception_UnknownTemplateException($name);
68    }
69}
70