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