Initial implementation of a new HTTP library based on pipelines.
[hoplite.git] / http2 / api.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 DataResponse extends Response {
24 public $data;
25
26 public function __construct($data) {
27 parent::__construct();
28 $this->data = $data;
29 }
30
31 public function generate() {
32 throw new \Exception(__CLASS__ . ' cannot generate a response');
33 }
34 }
35
36 class JsonResponse extends Response {
37 private $data;
38
39 public function __construct(DataResponse $r) {
40 $this->code = $r->code;
41 $this->data = $r->data;
42 }
43
44 public function generate() {
45 $this->headers['Content-Type'] = 'application/json';
46 parent::generate();
47 print json_encode($this->data);
48 }
49 }
50
51 class JsonResponseFilter extends Middleware {
52 public function execute(Request $request) {
53 $response = $this->next->execute($request);
54
55 if ($response instanceof DataResponse) {
56 return new JsonResponse($response);
57 }
58
59 return $response;
60 }
61 }