Request   C
last analyzed

Complexity

Total Complexity 54

Size/Duplication

Total Lines 302
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 54
lcom 1
cbo 2
dl 0
loc 302
rs 6.4799
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
A setServerRequestCreator() 0 4 1
A getParams() 0 4 1
A cleanUploadedFiles() 0 6 2
A setBufferSize() 0 4 1
A getBufferSize() 0 4 1
A setUploadDir() 0 4 1
A getUploadDir() 0 4 2
A getQuery() 0 10 3
B getPost() 0 27 9
C parseMultipartFormData() 0 54 16
A getCookies() 0 15 3
A getStdin() 0 4 1
A getServerRequest() 0 23 2
A getHttpFoundationRequest() 0 12 2
B addFile() 0 31 7

How to fix   Complexity   

Complex Class

Complex classes like Request often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Request, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace PHPFastCGI\FastCGIDaemon\Http;
6
7
use Nyholm\Psr7Server\ServerRequestCreatorInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Symfony\Component\HttpFoundation\Request as HttpFoundationRequest;
10
11
/**
12
 * The default implementation of the RequestInterface.
13
 */
14
final class Request implements RequestInterface
15
{
16
    /**
17
     * @var ServerRequestCreatorInterface|null
18
     */
19
    private static $serverRequestCreator = null;
20
21
    /**
22
     * @var int
23
     */
24
    private static $bufferSize = 10485760; // 10 MB
25
26
    /**
27
     * @var string
28
     */
29
    private static $uploadDir = null;
30
31
    /**
32
     * @var array
33
     */
34
    private $uploadedFiles = [];
35
36
    /**
37
     * @var array
38
     */
39
    private $params;
40
41
    /**
42
     * @var resource
43
     */
44
    private $stdin;
45
46
    /**
47
     * Constructor.
48
     *
49
     * @param array    $params The FastCGI server params as an associative array
50
     * @param resource $stdin  The FastCGI stdin data as a stream resource
51
     */
52
    public function __construct(array $params, $stdin)
53
    {
54
        $this->params = [];
55
56
        foreach ($params as $name => $value) {
57
            $this->params[strtoupper($name)] = $value;
58
        }
59
60
        $this->stdin  = $stdin;
61
62
        rewind($this->stdin);
63
    }
64
65
    public static function setServerRequestCreator(ServerRequestCreatorInterface $serverRequestCreator): void
66
    {
67
        self::$serverRequestCreator = $serverRequestCreator;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function getParams(): array
74
    {
75
        return $this->params;
76
    }
77
78
    /**
79
     * Remove all uploaded files
80
     */
81
    public function cleanUploadedFiles(): void
82
    {
83
        foreach ($this->uploadedFiles as $file) {
84
            @unlink($file['tmp_name']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
85
        }
86
    }
87
88
    /**
89
     * Set a buffer size to read uploaded files
90
     */
91
    public static function setBufferSize(int $size): void
92
    {
93
        static::$bufferSize = $size;
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
94
    }
95
96
    public static function getBufferSize(): int
97
    {
98
        return static::$bufferSize;
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
99
    }
100
101
    public static function setUploadDir(string $dir): void
102
    {
103
        static::$uploadDir = $dir;
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
104
    }
105
106
    public static function getUploadDir(): string
107
    {
108
        return static::$uploadDir ?: sys_get_temp_dir();
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public function getQuery(): array
115
    {
116
        $query = null;
117
118
        if (isset($this->params['QUERY_STRING'])) {
119
            parse_str($this->params['QUERY_STRING'], $query);
120
        }
121
122
        return $query ?: [];
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128
    public function getPost(): array
129
    {
130
        $post = null;
131
132
        if (isset($this->params['REQUEST_METHOD']) && isset($this->params['CONTENT_TYPE'])) {
133
            $requestMethod = $this->params['REQUEST_METHOD'];
134
            $contentType   = $this->params['CONTENT_TYPE'];
135
136
            if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'multipart/form-data') === 0) {
137
                if (preg_match('/boundary=(?P<quote>[\'"]?)(.*)(?P=quote)/', $contentType, $matches)) {
138
                    list($postData, $this->uploadedFiles) = $this->parseMultipartFormData($this->stdin, $matches[2]);
139
                    parse_str($postData, $post);
140
141
                    return $post;
142
                }
143
            }
144
145
            if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'application/x-www-form-urlencoded') === 0) {
146
                $postData = stream_get_contents($this->stdin);
147
                rewind($this->stdin);
148
149
                parse_str($postData, $post);
150
            }
151
        }
152
153
        return $post ?: [];
154
    }
155
156
    private function parseMultipartFormData($stream, string $boundary): array {
157
        $post = "";
158
        $files = [];
159
        $fieldType = $fieldName = $filename = $mimeType = null;
160
        $inHeader = $getContent = false;
0 ignored issues
show
Unused Code introduced by
$getContent is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
161
162
        while (!feof($stream)) {
163
            $getContent = $fieldName && !$inHeader;
0 ignored issues
show
Bug Best Practice introduced by
The expression $fieldName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
164
            $buffer = stream_get_line($stream, static::$bufferSize,  "\n" . ($getContent ? '--'.$boundary : ''));
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
165
            $buffer = trim($buffer, "\r");
166
167
            // Find the empty line between headers and body
168
            if ($inHeader && strlen($buffer) == 0) {
169
                $inHeader = false;
170
171
                continue;
172
            }
173
174
            if ($getContent) {
175
                if ($fieldType === 'data') {
176
                    $post .= (isset($post[0]) ? '&' : '') . $fieldName . "=" . urlencode($buffer);
177
                } elseif ($fieldType === 'file' && $filename) {
178
                    $tmpPath = @tempnam($this->getUploadDir(), 'fastcgi_upload');
179
                    $err = file_put_contents($tmpPath, $buffer);
180
                    $this->addFile($files, $fieldName, $filename, $tmpPath, $mimeType, false === $err);
181
                    $filename = $mimeType = null;
182
                }
183
                $fieldName = $fieldType = null;
184
185
                continue;
186
            }
187
188
            // Assert: We may be in the header, lets try to find 'Content-Disposition' and 'Content-Type'.
189
            if (strpos($buffer, 'Content-Disposition') === 0) {
190
                $inHeader = true;
191
                if (preg_match('/name=\"([^\"]*)\"/', $buffer, $matches)) {
192
                    $fieldName = $matches[1];
193
                }
194
                if (preg_match('/filename=\"([^\"]*)\"/', $buffer, $matches)) {
195
                    $filename = $matches[1];
196
                    $fieldType = 'file';
197
                } else {
198
                    $fieldType = 'data';
199
                }
200
            } elseif (strpos($buffer, 'Content-Type') === 0) {
201
                $inHeader = true;
202
                if (preg_match('/Content-Type: (.*)?/', $buffer, $matches)) {
203
                    $mimeType = trim($matches[1]);
204
                }
205
            }
206
        }
207
208
        return [$post, $files];
209
    }
210
211
    /**
212
     * {@inheritdoc}
213
     */
214
    public function getCookies(): array
215
    {
216
        $cookies = [];
217
218
        if (isset($this->params['HTTP_COOKIE'])) {
219
            $cookiePairs = explode(';', $this->params['HTTP_COOKIE']);
220
221
            foreach ($cookiePairs as $cookiePair) {
222
                list($name, $value) = explode('=', trim($cookiePair));
223
                $cookies[$name] = $value;
224
            }
225
        }
226
227
        return $cookies;
228
    }
229
230
    /**
231
     * {@inheritdoc}
232
     */
233
    public function getStdin()
234
    {
235
        return $this->stdin;
236
    }
237
238
    /**
239
     * {@inheritdoc}
240
     */
241
    public function getServerRequest(): ServerRequestInterface
242
    {
243
        if (null === self::$serverRequestCreator) {
244
            throw new \RuntimeException('You need to add an object of \Nyholm\Psr7Server\ServerRequestCreatorInterface to \PHPFastCGI\FastCGIDaemon\Http\Request::setServerRequestCreator to use PSR-7 requests. Please install and read more at https://github.com/nyholm/psr7-server');
245
        }
246
247
        $server  = $this->params;
248
        $query   = $this->getQuery();
249
        $post    = $this->getPost();
250
        $cookies = $this->getCookies();
251
252
        return self::$serverRequestCreator->fromArrays(
253
            $server,
254
            self::$serverRequestCreator->getHeadersFromServer($server),
255
            $cookies,
256
            $query,
257
            $post,
258
            $this->uploadedFiles,
259
            $this->stdin
260
        );
261
262
263
    }
264
265
    /**
266
     * {@inheritdoc}
267
     */
268
    public function getHttpFoundationRequest(): HttpFoundationRequest
269
    {
270
        if (!class_exists(HttpFoundationRequest::class)) {
271
            throw new \RuntimeException('You need to install symfony/http-foundation:^4.0 to use HttpFoundation requests.');
272
        }
273
274
        $query   = $this->getQuery();
275
        $post    = $this->getPost();
276
        $cookies = $this->getCookies();
277
278
        return new HttpFoundationRequest($query, $post, [], $cookies, $this->uploadedFiles, $this->params, $this->stdin);
279
    }
280
281
    /**
282
     * Add a file to the $files array
283
     */
284
    private function addFile(array &$files, string $fieldName, string $filename, string $tmpPath, string $mimeType, bool $err): void
285
    {
286
        $data = [
287
            'type' => $mimeType ?: 'application/octet-stream',
288
            'name' => $filename,
289
            'tmp_name' => $tmpPath,
290
            'error' => $err ? UPLOAD_ERR_CANT_WRITE : UPLOAD_ERR_OK,
291
            'size' => filesize($tmpPath),
292
        ];
293
294
        $parts = preg_split('|(\[[^\]]*\])|', $fieldName, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
295
        $count = count($parts);
296
        if (1 === $count) {
297
            $files[$fieldName] = $data;
298
        } else {
299
            $current = &$files;
300
            foreach ($parts as $i => $part) {
301
                if ($part === '[]') {
302
                    $current[] = $data;
303
                    continue;
304
                }
305
306
                $trimmedMatch = trim($part, '[]');
307
                if ($i === $count -1) {
308
                    $current[$trimmedMatch] = $data;
309
                } else {
310
                    $current = &$current[$trimmedMatch];
311
                }
312
            }
313
        }
314
    }
315
}
316