HttpApp::shutdownWithResponse()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Weew\HttpApp;
4
5
use Exception;
6
use Weew\App\App;
7
use Weew\Http\IHttpResponseable;
8
use Weew\HttpApp\Events\HandleHttpRequestEvent;
9
use Weew\HttpApp\Events\HttpRequestHandledEvent;
10
use Weew\HttpApp\Events\IncomingHttpRequestEvent;
11
use Weew\Http\HttpRequest;
12
use Weew\Http\HttpResponse;
13
use Weew\Http\HttpStatusCode;
14
use Weew\Http\IHttpRequest;
15
use Weew\Http\IHttpResponse;
16
17
class HttpApp extends App implements IHttpApp {
18
    /**
19
     * HttpApp constructor.
20
     *
21
     * @param string $environment
22
     * @param bool $debug
23
     */
24
    public function __construct($environment = null, $debug = null) {
25
        parent::__construct($environment, $debug);
26
27
        $this->container->set([HttpApp::class, IHttpApp::class], $this);
0 ignored issues
show
Documentation introduced by
array(\Weew\HttpApp\Http...ttpApp\IHttpApp::class) is of type array<integer,?>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
28
    }
29
30
    /**
31
     * @param IHttpRequest $request
32
     *
33
     * @return IHttpResponse
34
     */
35
    public function handleRequest(IHttpRequest $request) {
36
        $this->detectEnvFromRequest($request);
37
38
        return $this->handleExceptions(function() use ($request) {
39
            $response = $this->processRequest($request);
40
            $this->shutdown();
41
42
            return $response;
43
        });
44
    }
45
46
    /**
47
     * @param IHttpRequest $request
48
     *
49
     * @return IHttpResponse
50
     */
51
    public function handleInternalRequest(IHttpRequest $request) {
52
        return $this->handleExceptions(function() use ($request) {
53
            return $this->processRequest($request);
54
        });
55
    }
56
57
    /**
58
     * @param IHttpResponse $response
59
     */
60
    public function shutdownWithResponse(IHttpResponse $response) {
61
        $this->shutdown();
62
        $response->send();
63
64
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method shutdownWithResponse() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
65
    }
66
67
    /**
68
     * @param IHttpRequest $request
69
     *
70
     * @return IHttpResponse
71
     */
72
    protected function processRequest(IHttpRequest $request) {
73
        // share request instance
74
        $this->container->set(
75
            [HttpRequest::class, IHttpRequest::class], $request
0 ignored issues
show
Documentation introduced by
array(\Weew\Http\HttpReq...tp\IHttpRequest::class) is of type array<integer,?>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
76
        );
77
78
        // boot application and the kernel
79
        $this->start();
80
81
        // notify listeners about an incoming http request
82
        $this->eventer->dispatch(new IncomingHttpRequestEvent($request));
83
84
        // allow listeners to handle the request and provide a valid http response
85
        $event = new HandleHttpRequestEvent($request);
86
        $this->eventer->dispatch($event);
87
        $response = $event->getResponse();
88
89
        // in case there is a valid http response
90
        if ($response instanceof IHttpResponse) {
91
            // give listeners a chance to modify it
92
            $this->eventer->dispatch(
93
                new HttpRequestHandledEvent($request, $response)
94
            );
95
        }
96
97
        // in case there was a valid http response,
98
        // return it as the final application result
99
        if ( ! $response instanceof IHttpResponse) {
100
            $response = new HttpResponse(
101
                HttpStatusCode::NOT_FOUND,
102
                s(
103
                    'Http request was not handled. ' .
104
                    'It seems like no one is registered to handle it. ' .
105
                    'You can solve this by handling the "%s" event and providing ' .
106
                    'a valid IHttpResponse i.e: $event->setResponse($response)',
107
                    HandleHttpRequestEvent::class
108
                )
109
            );
110
        }
111
112
        return $response;
113
    }
114
115
    /**
116
     * @param callable $callable
117
     *
118
     * @return IHttpResponse
119
     * @throws Exception
120
     */
121
    protected function handleExceptions(callable $callable) {
122
        try {
123
            return $callable();
124
        } catch (Exception $ex) {
125
            if ($ex instanceof IHttpResponseable) {
126
                return $ex->toHttpResponse();
127
            }
128
129
            throw $ex;
130
        }
131
    }
132
133
    /**
134
     * @param IHttpRequest $request
135
     */
136
    protected function detectEnvFromRequest(IHttpRequest $request) {
137
        $envs = [];
138
        $envs[] = $this->detectEnvFromRequestHeader($request);
139
        $envs[] = $this->detectEnvFromUrlQuery($request);
140
        $envs[] = $this->detectEnvFromUrlPath($request);
141
142
        if ($this->getDebug()) {
143
            foreach ($envs as $env) {
144
                if ($env) {
145
                    $this->setEnvironment($env);
146
                    break;
147
                }
148
            }
149
        }
150
    }
151
152
    /**
153
     * @param IHttpRequest $request
154
     *
155
     * @return string
156
     */
157
    protected function detectEnvFromRequestHeader(IHttpRequest $request) {
158
        $env = $request->getHeaders()->find('x-env');
159
        $request->getHeaders()->remove('x-env');
160
161
        return $env;
162
    }
163
164
    /**
165
     * @param IHttpRequest $request
166
     *
167
     * @return mixed
168
     */
169
    protected function detectEnvFromUrlQuery(IHttpRequest $request) {
170
        $env = $request->getUrl()->getQuery()->get('env');
171
172
        if (is_scalar($env)) {
173
            // remove env setting from the url
174
            $request->getUrl()->getQuery()->remove('env');
175
176
            return $env;
177
        }
178
179
        return null;
180
    }
181
182
    /**
183
     * @param IHttpRequest $request
184
     *
185
     * @return mixed
186
     */
187
    protected function detectEnvFromUrlPath(IHttpRequest $request) {
188
        $env = $request->getUrl()->parse('/env={env}')->get('env');
189
190
        if ($env) {
191
            // remove environment from the url
192
            $cleanPath = str_replace(s('/env=%s', $env), '', $request->getUrl()->getPath());
193
            $request->getUrl()->setPath($cleanPath);
194
        }
195
196
        return $env;
197
    }
198
}
199