Add the Router and RouteMap components for http2.
[hoplite.git] / http2 / router.php
1 <?php
2 // Hoplite
3 // Copyright (c) 2016 Blue Static
4 //
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License along with
15 // this program. If not, see <http://www.gnu.org/licenses/>.
16
17 namespace hoplite\http2;
18
19 require_once HOPLITE_ROOT . '/http2/middleware.php';
20 require_once HOPLITE_ROOT . '/http2/pipeline.php';
21 require_once HOPLITE_ROOT . '/http2/route_map.php';
22
23 /*!
24 The Router is a middleware that operates on a RouteMap object. If a Request
25 matches, the value in the RouteMap is treated as a Middleware to be built by
26 Pipeline::buildMiddleware().
27
28 If the secondary Pipeline Router::subpipe is provided, the matched value will
29 be treated as if it were Pipeline::add()ed immediately before being built.
30 This allows additional middleware to execute IFF a route match occurs.
31
32 If no route mach is made, then the Router runs the next middleware.
33 */
34 class Router extends Middleware {
35 private $map;
36 private $subpipe;
37
38 public function __construct(Pipeline $pipeline,
39 Middleware $next,
40 RouteMap $map,
41 Pipeline $subpipe=NULL) {
42 parent::__construct($pipeline, $next);
43 $this->map = $map;
44 $this->subpipe = $subpipe ? $subpipe : new Pipeline();
45 }
46
47 public function execute(Request $request) {
48 // The query rewriter module of the webserver rewrites a request from:
49 // http://example.com/webapp/user/view/42
50 // to:
51 // http://example.com/webapp/index.php/user/view/42
52 // ... which then becomes accessible from PATH_INFO.
53 if (isset($_SERVER['PATH_INFO']))
54 $url = $_SERVER['PATH_INFO'];
55 else
56 $url = '/';
57 if ($url[0] == '/')
58 $url = substr($url, 1);
59
60 $request->url = $url;
61 $route_result = $this->map->match($request);
62
63 if ($route_result) {
64 $request->context[self::class] = $route_result;
65 $next = $this->subpipe->buildWithTail($route_result['result']);
66 return $next->execute($request);
67 }
68
69 return $this->next->execute($request);
70 }
71 }