Middleware no longer takes a Pipeline.
[hoplite.git] / http2 / pipeline.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/request.php';
21 require_once HOPLITE_ROOT . '/http2/response.php';
22
23 class Pipeline {
24 private $middleware = [];
25
26 public function add($middleware) {
27 array_push($this->middleware, $middleware);
28 return $this;
29 }
30
31 public function build() {
32 return $this->_build(new Sentinel(new NotFoundResponse()));
33 }
34
35 public function buildWithTail($tail) {
36 $chain = new Sentinel(new NotFoundResponse());
37 $chain = $this->buildMiddleware($tail, $chain);
38 return $this->_build($chain);
39 }
40
41 public function buildMiddleware($args, $next) {
42 if ($args instanceof \Closure) {
43 return new ClosureMiddleware($next, $args);
44 } else if ($args instanceof Pipeline) {
45 return $args->_build($next);
46 } else if (is_array($args)) {
47 $class = array_shift($args);
48 array_unshift($args, $next);
49 return new $class(...$args);
50 } else {
51 return new $args($next);
52 }
53 }
54
55 private function _build($chain) {
56 for ($i = count($this->middleware) - 1; $i >= 0; --$i) {
57 $chain = $this->buildMiddleware($this->middleware[$i], $chain);
58 }
59 return $chain;
60 }
61
62 public function run(Middleware $chain) {
63 $response = $chain->execute(new Request());
64 $response->generate();
65 }
66
67 public function buildAndRun() {
68 $this->run($this->build());
69 }
70 }