3 // Copyright (c) 2016 Blue Static
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.
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
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/>.
17 namespace hoplite\http2
;
19 require_once HOPLITE_ROOT
. '/http2/middleware.php';
20 require_once HOPLITE_ROOT
. '/http2/request.php';
21 require_once HOPLITE_ROOT
. '/http2/response.php';
24 private $middleware = [];
26 public function add($middleware) {
27 array_push($this->middleware
, $middleware);
31 public function build() {
32 return $this->_build(new Sentinel(new NotFoundResponse()));
35 public function buildWithTail($tail) {
36 $chain = new Sentinel(new NotFoundResponse());
37 $chain = $this->buildMiddleware($tail, $chain);
38 return $this->_build($chain);
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);
51 return new $args($next);
55 private function _build($chain) {
56 for ($i = count($this->middleware
) - 1; $i >= 0; --$i) {
57 $chain = $this->buildMiddleware($this->middleware
[$i], $chain);
62 public function run(Middleware
$chain) {
63 $response = $chain->execute(new Request());
64 $response->generate();
67 public function buildAndRun() {
68 $this->run($this->build());