1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Bridges\ApplicationDI;
9:
10: use Nette;
11:
12:
13: 14: 15:
16: class RoutingExtension extends Nette\DI\CompilerExtension
17: {
18: public $defaults = array(
19: 'debugger' => TRUE,
20: 'routes' => array(),
21: 'cache' => FALSE,
22: );
23:
24:
25: private $debugMode;
26:
27:
28: public function __construct($debugMode = FALSE)
29: {
30: $this->debugMode = $debugMode;
31: }
32:
33:
34: public function loadConfiguration()
35: {
36: $config = $this->validateConfig($this->defaults);
37: $container = $this->getContainerBuilder();
38:
39: $router = $container->addDefinition($this->prefix('router'))
40: ->setClass('Nette\Application\IRouter')
41: ->setFactory('Nette\Application\Routers\RouteList');
42:
43: foreach ($config['routes'] as $mask => $action) {
44: $router->addSetup('$service[] = new Nette\Application\Routers\Route(?, ?);', array($mask, $action));
45: }
46:
47: if ($this->name === 'routing') {
48: $container->addAlias('router', $this->prefix('router'));
49: }
50: }
51:
52:
53: public function beforeCompile()
54: {
55: $container = $this->getContainerBuilder();
56:
57: if ($this->debugMode && $this->config['debugger'] && $application = $container->getByType('Nette\Application\Application')) {
58: $container->getDefinition($application)->addSetup('@Tracy\Bar::addPanel', array(
59: new Nette\DI\Statement('Nette\Bridges\ApplicationTracy\RoutingPanel'),
60: ));
61: }
62: }
63:
64:
65: public function afterCompile(Nette\PhpGenerator\ClassType $class)
66: {
67: if (!empty($this->config['cache'])) {
68: $method = $class->getMethod(Nette\DI\Container::getMethodName($this->prefix('router')));
69: try {
70: $router = serialize(eval($method->getBody()));
71: } catch (\Throwable $e) {
72: throw new Nette\DI\ServiceCreationException('Unable to cache router due to error: ' . $e->getMessage(), 0, $e);
73: } catch (\Exception $e) {
74: throw new Nette\DI\ServiceCreationException('Unable to cache router due to error: ' . $e->getMessage(), 0, $e);
75: }
76: $method->setBody('return unserialize(?);', array($router));
77: }
78: }
79:
80: }
81: