Completed
Push — master ( 9561ee...bb752b )
by Dawid
02:42
created

ServerRequest::fromSwooleRequest()   C

Complexity

Conditions 7
Paths 16

Size

Total Lines 36
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 23
nc 16
nop 1
dl 0
loc 36
ccs 22
cts 22
cp 1
crap 7
rs 6.7272
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Igni\Http;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
use Psr\Http\Message\StreamInterface;
7
use Psr\Http\Message\UploadedFileInterface;
8
use Zend\Diactoros\ServerRequestFactory;
9
10
class ServerRequest extends Request implements ServerRequestInterface
11
{
12
    /**
13
     * @var array
14
     */
15
    private $attributes = [];
16
17
    /**
18
     * @var array
19
     */
20
    private $cookieParams = [];
21
22
    /**
23
     * @var null|array|object
24
     */
25
    private $parsedBody;
26
27
    /**
28
     * @var array
29
     */
30
    private $queryParams = [];
31
32
    /**
33
     * @var array
34
     */
35
    private $serverParams;
36
37
    /**
38
     * @var array
39
     */
40
    private $uploadedFiles;
41
42
43
    /**
44
     * Server request constructor.
45
     *
46
     * @param array $serverParams Server parameters, typically from $_SERVER
47
     * @param array $uploadedFiles Upload file information, a tree of UploadedFiles
48
     * @param null|string $uri URI for the request, if any.
49
     * @param null|string $method HTTP method for the request, if any.
50
     * @param string|resource|StreamInterface $body Messages body, if any.
51
     * @param array $headers Headers for the message, if any.
52
     * @throws \InvalidArgumentException for any invalid value.
53
     */
54 17
    public function __construct(
55
        array $serverParams = [],
56
        array $uploadedFiles = [],
57
        string $uri = null,
58
        string $method = self::METHOD_GET,
59
        $body = 'php://input',
60
        array $headers = []
61
    ) {
62 17
        parent::__construct($uri, $method, $body, $headers);
63 17
        $this->validateUploadedFiles($uploadedFiles);
64 17
        $this->serverParams  = $serverParams;
65 17
        $this->uploadedFiles = $uploadedFiles;
66 17
        parse_str($this->getUri()->getQuery(), $this->queryParams);
67 17
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 2
    public function getServerParams(): array
73
    {
74 2
        return $this->serverParams;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 2
    public function getUploadedFiles(): array
81
    {
82 2
        return $this->uploadedFiles;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 1
    public function withUploadedFiles(array $uploadedFiles)
89
    {
90 1
        $this->validateUploadedFiles($uploadedFiles);
91 1
        $new = clone $this;
92 1
        $new->uploadedFiles = $uploadedFiles;
93 1
        return $new;
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 2
    public function getCookieParams(): array
100
    {
101 2
        return $this->cookieParams;
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107 1
    public function withCookieParams(array $cookies)
108
    {
109 1
        $new = clone $this;
110 1
        $new->cookieParams = $cookies;
111 1
        return $new;
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117 4
    public function getQueryParams(): array
118
    {
119 4
        return $this->queryParams;
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125 1
    public function withQueryParams(array $query)
126
    {
127 1
        $new = clone $this;
128 1
        $new->queryParams = $query;
129 1
        return $new;
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135 2
    public function getParsedBody()
136
    {
137 2
        return $this->parsedBody;
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 1
    public function withParsedBody($data)
144
    {
145 1
        $new = clone $this;
146 1
        $new->parsedBody = $data;
147 1
        return $new;
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153 2
    public function getAttributes(): array
154
    {
155 2
        return $this->attributes;
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     */
161 10
    public function getAttribute($attribute, $default = null)
162
    {
163 10
        if (! isset($this->attributes[$attribute])) {
164 1
            return $default;
165
        }
166
167 10
        return $this->attributes[$attribute];
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173 1
    public function withAttribute($attribute, $value)
174
    {
175 1
        $new = clone $this;
176 1
        $new->attributes[$attribute] = $value;
177 1
        return $new;
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183 1
    public function withoutAttribute($attribute)
184
    {
185 1
        if (!isset($this->attributes[$attribute])) {
186 1
            return clone $this;
187
        }
188
189 1
        $new = clone $this;
190 1
        unset($new->attributes[$attribute]);
191 1
        return $new;
192
    }
193
194
    /**
195
     * Sets request attributes
196
     *
197
     * This method returns a new instance.
198
     *
199
     * @param array $attributes
200
     * @return self
201
     */
202 10
    public function withAttributes(array $attributes): ServerRequest
203
    {
204 10
        $new = clone $this;
205 10
        $new->attributes = $attributes;
206 10
        return $new;
207
    }
208
209
    /**
210
     * Recursively validate the structure in an uploaded files array.
211
     *
212
     * @param array $uploadedFiles
213
     * @throws \InvalidArgumentException if any leaf is not an UploadedFileInterface instance.
214
     */
215 17
    private function validateUploadedFiles(array $uploadedFiles): void
216
    {
217 17
        foreach ($uploadedFiles as $file) {
218 1
            if (is_array($file)) {
219
                $this->validateUploadedFiles($file);
220
                continue;
221
            }
222
223 1
            if (! $file instanceof UploadedFileInterface) {
224 1
                throw new \InvalidArgumentException('Invalid leaf in uploaded files structure');
225
            }
226
        }
227 17
    }
228
229 2
    public static function fromGlobals(): ServerRequest
230
    {
231 2
        $instance = new self(
232 2
            $_SERVER,
233 2
            ServerRequestFactory::normalizeFiles($_FILES),
234 2
            $_SERVER['REQUEST_URI'] ?? '',
235 2
            $_SERVER['REQUEST_METHOD'] ?? 'GET',
236 2
            'php://input',
237 2
            ServerRequestFactory::marshalHeaders($_SERVER)
238
        );
239
240 2
        return $instance;
241
    }
242
243
    /**
244
     * @param \Swoole\Http\Request $request
0 ignored issues
show
Bug introduced by
The type Swoole\Http\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
245
     * @return ServerRequest
246
     */
247 2
    public static function fromSwooleRequest($request): ServerRequest
248
    {
249 2
        if (isset($request->server['query_string'])) {
250 1
            $uri = $request->server['request_uri'] . '?' . $request->server['query_string'];
251
        } else {
252 1
            $uri = $request->server['request_uri'];
253
        }
254
255
        // Parse headers
256 2
        $headers = [];
257 2
        if ($request->header) {
258 1
            foreach ($request->header as $name => $value) {
259 1
                if (!isset($headers[$name])) {
260 1
                    $headers[$name] = [];
261
                }
262 1
                array_push($headers[$name], $value);
263
            }
264
        }
265
266
        try {
267 2
            $body = $request->rawContent();
268 2
        } catch (\Throwable $throwable) {
269 2
            $body = '';
270
        }
271
272 2
        if (!$body) {
273 2
            $body = '';
274
        }
275
276 2
        return new ServerRequest(
277 2
            $request->server ?? [],
278 2
            ServerRequestFactory::normalizeFiles($request->files ?? []) ?? [],
279 2
            $uri,
280 2
            $request->server['request_method'] ?? 'GET',
281 2
            $body,
282 2
            $headers
283
        );
284
    }
285
286 12
    public static function fromUri($uri, $method = self::METHOD_GET, string $body = ''): ServerRequest
287
    {
288 12
        return new ServerRequest([], [], $uri, $method, $body);
289
    }
290
}
291