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