• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / http / 11668545093

04 Nov 2024 04:33PM UTC coverage: 81.742% (-0.03%) from 81.776%
11668545093

push

github

dg
IRequest, IResponse: added typehints, unification (BC break)

2 of 2 new or added lines in 1 file covered. (100.0%)

9 existing lines in 1 file now uncovered.

873 of 1068 relevant lines covered (81.74%)

0.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.58
/src/Http/Request.php
1
<?php
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\Http;
11

12
use Nette;
13

14

15
/**
16
 * HttpRequest provides access scheme for request sent via HTTP.
17
 *
18
 * @property-read UrlScript $url
19
 * @property-read array $query
20
 * @property-read array $post
21
 * @property-read array $files
22
 * @property-read array $cookies
23
 * @property-read string $method
24
 * @property-read array $headers
25
 * @property-read UrlImmutable|null $referer
26
 * @property-read bool $secured
27
 * @property-read bool $ajax
28
 * @property-read string|null $remoteAddress
29
 * @property-read string|null $remoteHost
30
 * @property-read string|null $rawBody
31
 */
32
class Request implements IRequest
33
{
34
        use Nette\SmartObject;
35

36
        private readonly array $headers;
37

38
        private readonly ?\Closure $rawBodyCallback;
39

40

41
        public function __construct(
1✔
42
                private UrlScript $url,
43
                private readonly array $post = [],
44
                private readonly array $files = [],
45
                private readonly array $cookies = [],
46
                array $headers = [],
47
                private readonly string $method = 'GET',
48
                private readonly ?string $remoteAddress = null,
49
                private ?string $remoteHost = null,
50
                ?callable $rawBodyCallback = null,
51
        ) {
52
                $this->headers = array_change_key_case($headers, CASE_LOWER);
1✔
53
                $this->rawBodyCallback = $rawBodyCallback ? $rawBodyCallback(...) : null;
1✔
54
        }
1✔
55

56

57
        /**
58
         * Returns a clone with a different URL.
59
         */
60
        public function withUrl(UrlScript $url): static
1✔
61
        {
62
                $dolly = clone $this;
1✔
63
                $dolly->url = $url;
1✔
64
                return $dolly;
1✔
65
        }
66

67

68
        /**
69
         * Returns the URL of the request.
70
         */
71
        public function getUrl(): UrlScript
72
        {
73
                return $this->url;
1✔
74
        }
75

76

77
        /********************* query, post, files & cookies ****************d*g**/
78

79

80
        /**
81
         * Returns variable provided to the script via URL query ($_GET).
82
         * If no key is passed, returns the entire array.
83
         */
84
        public function getQuery(?string $key = null): mixed
1✔
85
        {
86
                if (func_num_args() === 0) {
1✔
87
                        return $this->url->getQueryParameters();
1✔
88
                }
89

90
                return $this->url->getQueryParameter($key);
1✔
91
        }
92

93

94
        /**
95
         * Returns variable provided to the script via POST method ($_POST).
96
         * If no key is passed, returns the entire array.
97
         */
98
        public function getPost(?string $key = null): mixed
1✔
99
        {
100
                if (func_num_args() === 0) {
1✔
101
                        return $this->post;
1✔
102
                }
103

104
                return $this->post[$key] ?? null;
1✔
105
        }
106

107

108
        /**
109
         * Returns uploaded file.
110
         * @param  string|string[]  $key
111
         */
112
        public function getFile($key): ?FileUpload
113
        {
114
                $res = Nette\Utils\Arrays::get($this->files, $key, null);
1✔
115
                return $res instanceof FileUpload ? $res : null;
1✔
116
        }
117

118

119
        /**
120
         * Returns tree of upload files in a normalized structure, with each leaf an instance of Nette\Http\FileUpload.
121
         */
122
        public function getFiles(): array
123
        {
124
                return $this->files;
1✔
125
        }
126

127

128
        /**
129
         * Returns a cookie or `null` if it does not exist.
130
         */
131
        public function getCookie(string $key): mixed
1✔
132
        {
133
                return $this->cookies[$key] ?? null;
1✔
134
        }
135

136

137
        /**
138
         * Returns all cookies.
139
         */
140
        public function getCookies(): array
141
        {
142
                return $this->cookies;
1✔
143
        }
144

145

146
        /********************* method & headers ****************d*g**/
147

148

149
        /**
150
         * Returns the HTTP method with which the request was made (GET, POST, HEAD, PUT, ...).
151
         */
152
        public function getMethod(): string
153
        {
154
                return $this->method;
1✔
155
        }
156

157

158
        /**
159
         * Checks the HTTP method with which the request was made. The parameter is case-insensitive.
160
         */
161
        public function isMethod(string $method): bool
162
        {
UNCOV
163
                return strcasecmp($this->method, $method) === 0;
×
164
        }
165

166

167
        /**
168
         * Returns an HTTP header or `null` if it does not exist. The parameter is case-insensitive.
169
         */
170
        public function getHeader(string $header): ?string
1✔
171
        {
172
                $header = strtolower($header);
1✔
173
                return $this->headers[$header] ?? null;
1✔
174
        }
175

176

177
        /**
178
         * Returns all HTTP headers as associative array.
179
         */
180
        public function getHeaders(): array
181
        {
182
                return $this->headers;
1✔
183
        }
184

185

186
        /**
187
         * What URL did the user come from? Beware, it is not reliable at all.
188
         * @deprecated  deprecated in favor of the getOrigin()
189
         */
190
        public function getReferer(): ?UrlImmutable
191
        {
UNCOV
192
                trigger_error(__METHOD__ . '() is deprecated', E_USER_DEPRECATED);
×
UNCOV
193
                return isset($this->headers['referer'])
×
194
                        ? new UrlImmutable($this->headers['referer'])
×
195
                        : null;
×
196
        }
197

198

199
        /**
200
         * What origin did the user come from? It contains scheme, hostname and port.
201
         */
202
        public function getOrigin(): ?UrlImmutable
203
        {
204
                $header = $this->headers['origin'] ?? 'null';
1✔
205
                try {
206
                        return $header === 'null'
1✔
207
                                ? null
1✔
208
                                : new UrlImmutable($header);
1✔
UNCOV
209
                } catch (Nette\InvalidArgumentException $e) {
×
UNCOV
210
                        return null;
×
211
                }
212
        }
213

214

215
        /**
216
         * Is the request sent via secure channel (https)?
217
         */
218
        public function isSecured(): bool
219
        {
220
                return $this->url->getScheme() === 'https';
1✔
221
        }
222

223

224
        /**
225
         * Is the request coming from the same site and is initiated by clicking on a link?
226
         */
227
        public function isSameSite(): bool
228
        {
UNCOV
229
                return isset($this->cookies[Helpers::StrictCookieName]);
×
230
        }
231

232

233
        /**
234
         * Is it an AJAX request?
235
         */
236
        public function isAjax(): bool
237
        {
UNCOV
238
                return $this->getHeader('X-Requested-With') === 'XMLHttpRequest';
×
239
        }
240

241

242
        /**
243
         * Returns the IP address of the remote client.
244
         */
245
        public function getRemoteAddress(): ?string
246
        {
247
                return $this->remoteAddress;
1✔
248
        }
249

250

251
        /**
252
         * Returns the host of the remote client.
253
         */
254
        public function getRemoteHost(): ?string
255
        {
256
                return $this->remoteHost;
1✔
257
        }
258

259

260
        /**
261
         * Returns raw content of HTTP request body.
262
         */
263
        public function getRawBody(): ?string
264
        {
265
                return $this->rawBodyCallback ? ($this->rawBodyCallback)() : null;
1✔
266
        }
267

268

269
        /**
270
         * Returns decoded content of HTTP request body.
271
         */
272
        public function getDecodedBody(): mixed
273
        {
UNCOV
274
                $type = $this->getHeader('Content-Type');
×
UNCOV
275
                return match ($type) {
×
276
                        'application/json' => json_decode($this->getRawBody()),
×
277
                        'application/x-www-form-urlencoded' => $_POST,
×
278
                        default => throw new \Exception("Unsupported content type: $type"),
×
279
                };
280
        }
281

282

283
        /**
284
         * Returns basic HTTP authentication credentials.
285
         * @return array{string, string}|null
286
         */
287
        public function getBasicCredentials(): ?array
288
        {
289
                return preg_match(
1✔
290
                        '~^Basic (\S+)$~',
1✔
291
                        $this->headers['authorization'] ?? '',
1✔
292
                        $t,
293
                )
294
                        && ($t = base64_decode($t[1], strict: true))
1✔
295
                        && ($t = explode(':', $t, 2))
1✔
296
                        && (count($t) === 2)
1✔
297
                        ? $t
1✔
298
                        : null;
1✔
299
        }
300

301

302
        /**
303
         * Returns the most preferred language by browser. Uses the `Accept-Language` header. If no match is reached, it returns `null`.
304
         * @param  string[]  $langs  supported languages
305
         */
306
        public function detectLanguage(array $langs): ?string
1✔
307
        {
308
                $header = $this->getHeader('Accept-Language');
1✔
309
                if (!$header) {
1✔
310
                        return null;
1✔
311
                }
312

313
                $s = strtolower($header);  // case insensitive
1✔
314
                $s = strtr($s, '_', '-');  // cs_CZ means cs-CZ
1✔
315
                rsort($langs);             // first more specific
1✔
316
                preg_match_all('#(' . implode('|', $langs) . ')(?:-[^\s,;=]+)?\s*(?:;\s*q=([0-9.]+))?#', $s, $matches);
1✔
317

318
                if (!$matches[0]) {
1✔
319
                        return null;
1✔
320
                }
321

322
                $max = 0;
1✔
323
                $lang = null;
1✔
324
                foreach ($matches[1] as $key => $value) {
1✔
325
                        $q = $matches[2][$key] === '' ? 1.0 : (float) $matches[2][$key];
1✔
326
                        if ($q > $max) {
1✔
327
                                $max = $q;
1✔
328
                                $lang = $value;
1✔
329
                        }
330
                }
331

332
                return $lang;
1✔
333
        }
334
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc