Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 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 | |
| 12 | namespace Twig\Loader; |
| 13 | |
| 14 | use Twig\Error\LoaderError; |
| 15 | use 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 | */ |
| 29 | final class ArrayLoader implements LoaderInterface |
| 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 | public function setTemplate(string $name, string $template): void |
| 42 | { |
| 43 | $this->templates[$name] = $template; |
| 44 | } |
| 45 | |
| 46 | public function getSourceContext(string $name): Source |
| 47 | { |
| 48 | if (!isset($this->templates[$name])) { |
| 49 | throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); |
| 50 | } |
| 51 | |
| 52 | return new Source($this->templates[$name], $name); |
| 53 | } |
| 54 | |
| 55 | public function exists(string $name): bool |
| 56 | { |
| 57 | return isset($this->templates[$name]); |
| 58 | } |
| 59 | |
| 60 | public function getCacheKey(string $name): string |
| 61 | { |
| 62 | if (!isset($this->templates[$name])) { |
| 63 | throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); |
| 64 | } |
| 65 | |
| 66 | return $name.':'.$this->templates[$name]; |
| 67 | } |
| 68 | |
| 69 | public function isFresh(string $name, int $time): bool |
| 70 | { |
| 71 | if (!isset($this->templates[$name])) { |
| 72 | throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); |
| 73 | } |
| 74 | |
| 75 | return true; |
| 76 | } |
| 77 | } |