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' => NULL,
20: 'routes' => array(),
21: 'cache' => FALSE,
22: );
23:
24:
25: private $debugMode;
26:
27:
28: public function __construct($debugMode = FALSE)
29: {
30: $this->defaults['debugger'] = interface_exists('Tracy\IBarPanel');
31: $this->debugMode = $debugMode;
32: }
33:
34:
35: public function loadConfiguration()
36: {
37: $config = $this->validateConfig($this->defaults);
38: $container = $this->getContainerBuilder();
39:
40: $router = $container->addDefinition($this->prefix('router'))
41: ->setClass('Nette\Application\IRouter')
42: ->setFactory('Nette\Application\Routers\RouteList');
43:
44: foreach ($config['routes'] as $mask => $action) {
45: $router->addSetup('$service[] = new Nette\Application\Routers\Route(?, ?);', array($mask, $action));
46: }
47:
48: if ($this->name === 'routing') {
49: $container->addAlias('router', $this->prefix('router'));
50: }
51: }
52:
53:
54: public function beforeCompile()
55: {
56: $container = $this->getContainerBuilder();
57:
58: if ($this->debugMode && $this->config['debugger'] && $application = $container->getByType('Nette\Application\Application')) {
59: $container->getDefinition($application)->addSetup('@Tracy\Bar::addPanel', array(
60: new Nette\DI\Statement('Nette\Bridges\ApplicationTracy\RoutingPanel'),
61: ));
62: }
63: }
64:
65:
66: public function afterCompile(Nette\PhpGenerator\ClassType $class)
67: {
68: if (!empty($this->config['cache'])) {
69: $method = $class->getMethod(Nette\DI\Container::getMethodName($this->prefix('router')));
70: try {
71: $router = eval($method->getBody());
72: if ($router instanceof Nette\Application\Routers\RouteList) {
73: $router->warmupCache();
74: }
75: $s = serialize($router);
76: } catch (\Throwable $e) {
77: throw new Nette\DI\ServiceCreationException('Unable to cache router due to error: ' . $e->getMessage(), 0, $e);
78: } catch (\Exception $e) {
79: throw new Nette\DI\ServiceCreationException('Unable to cache router due to error: ' . $e->getMessage(), 0, $e);
80: }
81: $method->setBody('return unserialize(?);', array($s));
82: }
83: }
84:
85: }
86: