Completed
Pull Request — master (#39)
by Tobias
03:52
created

Request::setServerRequestCreator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace PHPFastCGI\FastCGIDaemon\Http;
4
5
use Nyholm\Psr7Server\ServerRequestCreatorInterface;
6
use Symfony\Component\HttpFoundation\Request as HttpFoundationRequest;
7
8
/**
9
 * The default implementation of the RequestInterface.
10
 */
11
final class Request implements RequestInterface
12
{
13
    /**
14
     * @var ServerRequestCreatorInterface|null
15
     */
16
    private static $serverRequestCreator = null;
17
18
    /**
19
     * @var int
20
     */
21
    private static $bufferSize = 10485760; // 10 MB
22
23
    /**
24
     * @var string
25
     */
26
    private static $uploadDir = null;
27
28
    /**
29
     * @var array
30
     */
31
    private $uploadedFiles = [];
32
33
    /**
34
     * @var array
35
     */
36
    private $params;
37
38
    /**
39
     * @var resource
40
     */
41
    private $stdin;
42
43
    /**
44
     * Constructor.
45
     *
46
     * @param array    $params The FastCGI server params as an associative array
47
     * @param resource $stdin  The FastCGI stdin data as a stream resource
48
     */
49
    public function __construct(array $params, $stdin)
50
    {
51
        $this->params = [];
52
53
        foreach ($params as $name => $value) {
54
            $this->params[strtoupper($name)] = $value;
55
        }
56
57
        $this->stdin  = $stdin;
58
59
        rewind($this->stdin);
60
    }
61
62
    public static function setServerRequestCreator(ServerRequestCreatorInterface $serverRequestCreator): void
63
    {
64
        self::$serverRequestCreator = $serverRequestCreator;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function getParams()
71
    {
72
        return $this->params;
73
    }
74
75
    /**
76
     * Remove all uploaded files
77
     */
78
    public function cleanUploadedFiles(): void
79
    {
80
        foreach ($this->uploadedFiles as $file) {
81
            @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...
82
        }
83
    }
84
85
    /**
86
     * Set a buffer size to read uploaded files
87
     */
88
    public static function setBufferSize(int $size): void
89
    {
90
        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...
91
    }
92
93
    public static function getBufferSize(): int
94
    {
95
        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...
96
    }
97
98
    public static function setUploadDir(string $dir): void
99
    {
100
        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...
101
    }
102
103
    public static function getUploadDir(): string
104
    {
105
        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...
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    public function getQuery()
112
    {
113
        $query = null;
114
115
        if (isset($this->params['QUERY_STRING'])) {
116
            parse_str($this->params['QUERY_STRING'], $query);
117
        }
118
119
        return $query ?: [];
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125
    public function getPost()
126
    {
127
        $post = null;
128
129
        if (isset($this->params['REQUEST_METHOD']) && isset($this->params['CONTENT_TYPE'])) {
130
            $requestMethod = $this->params['REQUEST_METHOD'];
131
            $contentType   = $this->params['CONTENT_TYPE'];
132
133
            if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'multipart/form-data') === 0) {
134
                if (preg_match('/boundary=(?P<quote>[\'"]?)(.*)(?P=quote)/', $contentType, $matches)) {
135
                    list($postData, $this->uploadedFiles) = $this->parseMultipartFormData($this->stdin, $matches[2]);
136
                    parse_str($postData, $post);
137
138
                    return $post;
139
                }
140
            }
141
142
            if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'application/x-www-form-urlencoded') === 0) {
143
                $postData = stream_get_contents($this->stdin);
144
                rewind($this->stdin);
145
146
                parse_str($postData, $post);
147
            }
148
        }
149
150
        return $post ?: [];
151
    }
152
153
    private function parseMultipartFormData($stream, $boundary) {
154
        $post = "";
155
        $files = [];
156
        $fieldType = $fieldName = $filename = $mimeType = null;
157
        $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...
158
159
        while (!feof($stream)) {
160
            $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...
161
            $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...
162
            $buffer = trim($buffer, "\r");
163
164
            // Find the empty line between headers and body
165
            if ($inHeader && strlen($buffer) == 0) {
166
                $inHeader = false;
167
168
                continue;
169
            }
170
171
            if ($getContent) {
172
                if ($fieldType === 'data') {
173
                    $post .= (isset($post[0]) ? '&' : '') . $fieldName . "=" . urlencode($buffer);
174
                } elseif ($fieldType === 'file' && $filename) {
175
                    $tmpPath = tempnam($this->getUploadDir(), 'fastcgi_upload');
176
                    $err = file_put_contents($tmpPath, $buffer);
177
                    $files[$fieldName] = [
178
                        'type' => $mimeType ?: 'application/octet-stream',
179
                        'name' => $filename,
180
                        'tmp_name' => $tmpPath,
181
                        'error' => ($err === false) ? true : 0,
182
                        'size' => filesize($tmpPath),
183
                    ];
184
                    $filename = $mimeType = null;
185
                }
186
                $fieldName = $fieldType = null;
187
188
                continue;
189
            }
190
191
            // Assert: We may be in the header, lets try to find 'Content-Disposition' and 'Content-Type'.
192
            if (strpos($buffer, 'Content-Disposition') === 0) {
193
                $inHeader = true;
194
                if (preg_match('/name=\"([^\"]*)\"/', $buffer, $matches)) {
195
                    $fieldName = $matches[1];
196
                }
197
                if (preg_match('/filename=\"([^\"]*)\"/', $buffer, $matches)) {
198
                    $filename = $matches[1];
199
                    $fieldType = 'file';
200
                } else {
201
                    $fieldType = 'data';
202
                }
203
            } elseif (strpos($buffer, 'Content-Type') === 0) {
204
                $inHeader = true;
205
                if (preg_match('/Content-Type: (.*)?/', $buffer, $matches)) {
206
                    $mimeType = trim($matches[1]);
207
                }
208
            }
209
        }
210
211
        return [$post, $files];
212
    }
213
214
    /**
215
     * {@inheritdoc}
216
     */
217
    public function getCookies()
218
    {
219
        $cookies = [];
220
221
        if (isset($this->params['HTTP_COOKIE'])) {
222
            $cookiePairs = explode(';', $this->params['HTTP_COOKIE']);
223
224
            foreach ($cookiePairs as $cookiePair) {
225
                list($name, $value) = explode('=', trim($cookiePair));
226
                $cookies[$name] = $value;
227
            }
228
        }
229
230
        return $cookies;
231
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236
    public function getStdin()
237
    {
238
        return $this->stdin;
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244
    public function getServerRequest()
245
    {
246
        if (null === self::$serverRequestCreator) {
247
            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');
248
        }
249
250
        $server  = $this->params;
251
        $query   = $this->getQuery();
252
        $post    = $this->getPost();
253
        $cookies = $this->getCookies();
254
255
        return self::$serverRequestCreator->fromArrays(
256
            $server,
257
            self::$serverRequestCreator->getHeadersFromServer($server),
258
            $cookies,
259
            $query,
260
            $post,
0 ignored issues
show
Bug introduced by
It seems like $post defined by $this->getPost() on line 252 can also be of type null; however, Nyholm\Psr7Server\Server...Interface::fromArrays() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
261
            $this->uploadedFiles,
262
            $this->stdin
263
        );
264
    }
265
266
    /**
267
     * {@inheritdoc}
268
     */
269
    public function getHttpFoundationRequest()
270
    {
271
        if (!class_exists(HttpFoundationRequest::class)) {
272
            throw new \RuntimeException('You need to install symfony/http-foundation:^4.0 to use HttpFoundation requests.');
273
        }
274
275
        $query   = $this->getQuery();
276
        $post    = $this->getPost();
277
        $cookies = $this->getCookies();
278
279
        return new HttpFoundationRequest($query, $post, [], $cookies, $this->uploadedFiles, $this->params, $this->stdin);
0 ignored issues
show
Bug introduced by
It seems like $post defined by $this->getPost() on line 276 can also be of type null; however, Symfony\Component\HttpFo...\Request::__construct() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
280
    }
281
}
282