From d8ea4508ebab2516aa1591b7b166512593b27a0f Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Tue, 1 Nov 2022 16:57:35 +0100 Subject: [PATCH] Add namespace loader --- src/Latte/Loaders/NamespaceLoader.php | 87 +++++++++++++++++++++++ tests/common/Loaders.NamespaceLoader.phpt | 30 ++++++++ 2 files changed, 117 insertions(+) create mode 100644 src/Latte/Loaders/NamespaceLoader.php create mode 100644 tests/common/Loaders.NamespaceLoader.phpt diff --git a/src/Latte/Loaders/NamespaceLoader.php b/src/Latte/Loaders/NamespaceLoader.php new file mode 100644 index 0000000000..803614b91c --- /dev/null +++ b/src/Latte/Loaders/NamespaceLoader.php @@ -0,0 +1,87 @@ +loaders = $loaders; + } + + /** + * Returns template source code. + */ + public function getContent(string $name): string + { + [$loader, $name] = $this->extractLoaderAndName($name); + + return $loader->getContent($name); + } + + + public function isExpired(string $file, int $time): bool + { + [$loader, $name] = $this->extractLoaderAndName($file); + + return $loader->isExpired($name, $time); + } + + + /** + * Returns referred template name. + */ + public function getReferredName(string $name, string $referringName): string + { + [$loader, $name] = $this->extractLoaderAndName($name); + + return $loader->getReferredName($name, $referringName); + } + + + /** + * Returns unique identifier for caching. + */ + public function getUniqueId(string $name): string + { + [$loader, $name] = $this->extractLoaderAndName($name); + + return $loader->getUniqueId($name); + } + + + private function extractLoaderAndName(string $name): array + { + $namespaceParts = \explode('::', $name, 2); + + if (count($namespaceParts) === 2) { + return [ + $this->loaders[$namespaceParts[0]], + $namespaceParts[1], + ]; + } + + return [ + $this->loaders[''], + $name, + ]; + } +} diff --git a/tests/common/Loaders.NamespaceLoader.phpt b/tests/common/Loaders.NamespaceLoader.phpt new file mode 100644 index 0000000000..5327229511 --- /dev/null +++ b/tests/common/Loaders.NamespaceLoader.phpt @@ -0,0 +1,30 @@ + 'defaultcontent']); + $appLoader = new StringLoader(['main' => 'appcontent']); + $otherLoader = new StringLoader(['main' => 'othercontent']); + + $loader = new NamespaceLoader([ + '' => $defaultLoader, + 'app' => $appLoader, + 'other' => $otherLoader, + ]); + + Assert::same('defaultcontent', $loader->getContent('main')); + Assert::same('appcontent', $loader->getContent('app::main')); + Assert::same('othercontent', $loader->getContent('other::main')); +});