1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
<?php
use Nette\Application\Routers;
/**
* Micro-framework router for templates using {url} macro.
*/
class TemplateRouter extends Routers\RouteList
{
public function __construct($path, $cachePath)
{
if (is_file($cacheFile = $cachePath . '/routes.php')) {
$routes = require $cacheFile;
} else {
$routes = $this->scanRoutes($path);
file_put_contents($cacheFile, '<?php return ' . var_export($routes, TRUE) . ';');
}
foreach ($routes as $mask => $file) {
$this[] = new Routers\Route($mask, function ($presenter) use ($file, $cachePath) {
return $presenter->createTemplate(NULL, function () use ($cachePath) {
$latte = new Latte\Engine;
$latte->setTempDirectory($cachePath . '/cache');
$macroSet = new Latte\Macros\MacroSet($latte->getCompiler());
$macroSet->addMacro('url', function () {}, NULL, NULL, $macroSet::ALLOWED_IN_HEAD); // ignore
return $latte;
})->setFile($file);
});
}
}
public function scanRoutes($path)
{
$routes = [];
$latte = new Latte\Engine;
$macroSet = new Latte\Macros\MacroSet($latte->getCompiler());
$macroSet->addMacro('url', function ($node) use (&$routes, &$file) {
$routes[$node->args] = (string) $file;
}, NULL, NULL, $macroSet::ALLOWED_IN_HEAD);
foreach (Nette\Utils\Finder::findFiles('*.latte')->from($path) as $file) {
$latte->compile($file);
}
return $routes;
}
}
|