1: <?php
2: 3: 4: 5: 6: 7: 8: 9:
10:
11: namespace Autarky\Routing;
12:
13: 14: 15: 16:
17: class Configuration
18: {
19: 20: 21:
22: protected $router;
23:
24: 25: 26:
27: protected $routes = array();
28:
29: 30: 31:
32: protected $namespace;
33:
34: 35: 36: 37: 38:
39: public function __construct(RouterInterface $router, array $routes, $namespace = null)
40: {
41: $this->router = $router;
42: $this->routes = $routes;
43:
44: if ($namespace) {
45: $this->namespace = $namespace;
46: }
47: }
48:
49: 50: 51: 52: 53: 54: 55: 56:
57: public function override($name, array $routeData)
58: {
59: if (!isset($this->routes[$name])) {
60: throw new \InvalidArgumentException("No route for name $name defined");
61: }
62:
63: $this->routes[$name] = $routeData + $this->routes[$name];
64: }
65:
66: 67: 68: 69: 70: 71: 72:
73: public function merge(array $routes)
74: {
75: foreach ($routes as $name => $route) {
76: $this->override($name, $route);
77: }
78: }
79:
80: 81: 82: 83: 84: 85: 86:
87: public function mount($prefix = null)
88: {
89: if ($prefix) {
90: $this->router->group(['prefix' => $prefix], function() {
91: $this->registerRoutes();
92: });
93: } else {
94: $this->registerRoutes();
95: }
96: }
97:
98: protected function registerRoutes()
99: {
100: foreach ($this->routes as $name => $route) {
101: if ($this->namespace) {
102: $name = $this->namespace . ':' . $name;
103: }
104:
105: $path = $route['path'];
106:
107: if (isset($route['methods'])) {
108: $methods = (array) $route['methods'];
109: } elseif (isset($route['method'])) {
110: $methods = (array) $route['method'];
111: } else {
112: $methods = ['GET'];
113: }
114:
115: $options = [];
116: if (isset($route['params'])) {
117: $options['params'] = $route['params'];
118: }
119: if (isset($route['constructor_params'])) {
120: $options['constructor_params'] = $route['constructor_params'];
121: }
122:
123: if (array_filter(array_keys($methods), 'is_string')) {
124: foreach ($methods as $method => $controller) {
125: $this->router->addRoute([$method], $path, $controller, $name);
126: $name = null;
127: }
128: } else {
129: $controller = isset($route['controller']) ?
130: $route['controller'] : $route['handler'];
131: $this->router->addRoute($methods, $path, $controller, $name);
132: }
133: }
134: }
135: }
136: