Skip to content

Commit

Permalink
Add namespace loader
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-schranz committed Nov 1, 2022
1 parent 5645d7b commit d8ea450
Show file tree
Hide file tree
Showing 2 changed files with 117 additions and 0 deletions.
87 changes: 87 additions & 0 deletions src/Latte/Loaders/NamespaceLoader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

/**
* This file is part of the Latte (https://latte.nette.org)
* Copyright (c) 2008 David Grudl (https://davidgrudl.com)
*/

declare(strict_types=1);

namespace Latte\Loaders;

use Latte;


/**
* Template loader.
*/
class NamespaceLoader implements Latte\Loader
{
/**
* @var Latte\Loader[]
*/
private array $loaders;

public function __construct(array $loaders)
{
$this->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,
];
}
}
30 changes: 30 additions & 0 deletions tests/common/Loaders.NamespaceLoader.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

/**
* Test: StringLoader
*/

declare(strict_types=1);

use Latte\Loaders\StringLoader;
use Latte\Loaders\NamespaceLoader;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


test('', function () {
$defaultLoader = new StringLoader(['main' => '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'));
});

0 comments on commit d8ea450

Please sign in to comment.