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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Bridges\ApplicationDI;
use Nette;
use Tracy;
/**
* Routing extension for Nette DI.
*/
class RoutingExtension extends Nette\DI\CompilerExtension
{
public $defaults = [
'debugger' => NULL,
'routes' => [], // of [mask => action]
'cache' => FALSE,
];
/** @var bool */
private $debugMode;
public function __construct($debugMode = FALSE)
{
$this->defaults['debugger'] = interface_exists(Tracy\IBarPanel::class);
$this->debugMode = $debugMode;
}
public function loadConfiguration()
{
$config = $this->validateConfig($this->defaults);
$builder = $this->getContainerBuilder();
$router = $builder->addDefinition($this->prefix('router'))
->setClass(Nette\Application\IRouter::class)
->setFactory(Nette\Application\Routers\RouteList::class);
foreach ($config['routes'] as $mask => $action) {
$router->addSetup('$service[] = new Nette\Application\Routers\Route(?, ?);', [$mask, $action]);
}
if ($this->name === 'routing') {
$builder->addAlias('router', $this->prefix('router'));
}
}
public function beforeCompile()
{
$builder = $this->getContainerBuilder();
if ($this->debugMode && $this->config['debugger'] && $application = $builder->getByType(Nette\Application\Application::class)) {
$builder->getDefinition($application)->addSetup('@Tracy\Bar::addPanel', [
new Nette\DI\Statement(Nette\Bridges\ApplicationTracy\RoutingPanel::class),
]);
}
}
public function afterCompile(Nette\PhpGenerator\ClassType $class)
{
if (!empty($this->config['cache'])) {
$method = $class->getMethod(Nette\DI\Container::getMethodName($this->prefix('router')));
try {
$router = eval($method->getBody());
if ($router instanceof Nette\Application\Routers\RouteList) {
$router->warmupCache();
}
$s = serialize($router);
} catch (\Throwable $e) {
throw new Nette\DI\ServiceCreationException('Unable to cache router due to error: ' . $e->getMessage(), 0, $e);
} catch (\Exception $e) {
throw new Nette\DI\ServiceCreationException('Unable to cache router due to error: ' . $e->getMessage(), 0, $e);
}
$method->setBody('return unserialize(?);', [$s]);
}
}
}
|