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

nette / http / 22837209177

09 Mar 2026 03:32AM UTC coverage: 83.513% (-0.1%) from 83.62%
22837209177

push

github

dg
added CLAUDE.md

932 of 1116 relevant lines covered (83.51%)

0.84 hits per line

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

92.68
/src/Http/Request.php
1
<?php declare(strict_types=1);
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
namespace Nette\Http;
9

10
use Nette;
11
use function array_change_key_case, base64_decode, count, explode, gethostbyaddr, implode, in_array, preg_match, preg_match_all, rsort, strcasecmp, strtr;
12

13

14
/**
15
 * Immutable representation of an HTTP request with access to URL, headers, cookies, uploaded files, and body.
16
 *
17
 * @property-read UrlScript $url
18
 * @property-read array<string,mixed> $query
19
 * @property-read array<string,mixed> $post
20
 * @property-read array<string,mixed> $files
21
 * @property-read array<string,string> $cookies
22
 * @property-read string $method
23
 * @property-read array<string,string> $headers
24
 * @property-read ?UrlImmutable $referer
25
 * @property-read bool $secured
26
 * @property-read bool $ajax
27
 * @property-read ?string $remoteAddress
28
 * @property-read ?string $remoteHost
29
 * @property-read ?string $rawBody
30
 */
31
class Request implements IRequest
32
{
33
        use Nette\SmartObject;
34

35
        /** @var array<string, string> */
36
        private readonly array $headers;
37

38
        /** @var (\Closure(): string)|null */
39
        private readonly ?\Closure $rawBodyCallback;
40

41

42
        /**
43
         * @param array<string, string> $headers
44
         * @param ?(callable(): string) $rawBodyCallback
45
         */
46
        public function __construct(
1✔
47
                private UrlScript $url,
48
                /** @var mixed[] */
49
                private readonly array $post = [],
50
                /** @var mixed[] */
51
                private readonly array $files = [],
52
                /** @var array<string, string> */
53
                private readonly array $cookies = [],
54
                array $headers = [],
55
                private readonly string $method = 'GET',
56
                private readonly ?string $remoteAddress = null,
57
                private ?string $remoteHost = null,
58
                ?callable $rawBodyCallback = null,
59
        ) {
60
                $this->headers = array_change_key_case($headers, CASE_LOWER);
1✔
61
                $this->rawBodyCallback = $rawBodyCallback ? $rawBodyCallback(...) : null;
1✔
62
        }
1✔
63

64

65
        /**
66
         * Returns a clone with a different URL.
67
         */
68
        public function withUrl(UrlScript $url): static
1✔
69
        {
70
                $dolly = clone $this;
1✔
71
                $dolly->url = $url;
1✔
72
                return $dolly;
1✔
73
        }
74

75

76
        /**
77
         * Returns the URL of the request.
78
         */
79
        public function getUrl(): UrlScript
80
        {
81
                return $this->url;
1✔
82
        }
83

84

85
        /********************* query, post, files & cookies ****************d*g**/
86

87

88
        /**
89
         * Returns a URL query parameter, or all parameters as an array if no key is given.
90
         */
91
        public function getQuery(?string $key = null): mixed
1✔
92
        {
93
                if ($key === null) {
1✔
94
                        return $this->url->getQueryParameters();
1✔
95
                }
96

97
                return $this->url->getQueryParameter($key);
1✔
98
        }
99

100

101
        /**
102
         * Returns a POST parameter, or all POST parameters as an array if no key is given.
103
         */
104
        public function getPost(?string $key = null): mixed
1✔
105
        {
106
                if ($key === null) {
1✔
107
                        return $this->post;
1✔
108
                }
109

110
                return $this->post[$key] ?? null;
1✔
111
        }
112

113

114
        /**
115
         * Returns the uploaded file for the given key, or null if not present.
116
         * Accepts a string key or an array of keys for nested file structures (e.g. ['form', 'avatar']).
117
         * @param  string|string[]  $key
118
         */
119
        public function getFile($key): ?FileUpload
120
        {
121
                $res = Nette\Utils\Arrays::get($this->files, $key, null);
1✔
122
                return $res instanceof FileUpload ? $res : null;
1✔
123
        }
124

125

126
        /**
127
         * Returns the tree of uploaded files, with each leaf being a FileUpload instance.
128
         * @return mixed[]
129
         */
130
        public function getFiles(): array
131
        {
132
                return $this->files;
1✔
133
        }
134

135

136
        /**
137
         * Returns a cookie or `null` if it does not exist.
138
         */
139
        public function getCookie(string $key): mixed
1✔
140
        {
141
                return $this->cookies[$key] ?? null;
1✔
142
        }
143

144

145
        /**
146
         * Returns all cookies.
147
         * @return array<string, string>
148
         */
149
        public function getCookies(): array
150
        {
151
                return $this->cookies;
1✔
152
        }
153

154

155
        /********************* method & headers ****************d*g**/
156

157

158
        /**
159
         * Returns the HTTP method with which the request was made (GET, POST, HEAD, PUT, ...).
160
         */
161
        public function getMethod(): string
162
        {
163
                return $this->method;
1✔
164
        }
165

166

167
        /**
168
         * Checks the HTTP method with which the request was made. The parameter is case-insensitive.
169
         */
170
        public function isMethod(string $method): bool
171
        {
172
                return strcasecmp($this->method, $method) === 0;
×
173
        }
174

175

176
        /**
177
         * Returns an HTTP header or `null` if it does not exist. The parameter is case-insensitive.
178
         */
179
        public function getHeader(string $header): ?string
1✔
180
        {
181
                $header = strtolower($header);
1✔
182
                return $this->headers[$header] ?? null;
1✔
183
        }
184

185

186
        /**
187
         * Returns all HTTP headers as associative array.
188
         * @return array<string, string>
189
         */
190
        public function getHeaders(): array
191
        {
192
                return $this->headers;
1✔
193
        }
194

195

196
        /**
197
         * Returns the referrer URL from the Referer header. Unreliable - clients may omit or spoof it.
198
         * @deprecated  use getOrigin()
199
         */
200
        public function getReferer(): ?UrlImmutable
201
        {
202
                return isset($this->headers['referer'])
×
203
                        ? new UrlImmutable($this->headers['referer'])
×
204
                        : null;
×
205
        }
206

207

208
        /**
209
         * Returns the request origin (scheme + host + port) from the Origin header, or null if absent or invalid.
210
         */
211
        public function getOrigin(): ?UrlImmutable
212
        {
213
                $header = $this->headers['origin'] ?? '';
1✔
214
                if (!preg_match('~^[a-z][a-z0-9+.-]*://[^/]+$~i', $header)) {
1✔
215
                        return null;
1✔
216
                }
217
                return new UrlImmutable($header);
1✔
218
        }
219

220

221
        /**
222
         * Checks whether the request was sent via a secure channel (HTTPS).
223
         */
224
        public function isSecured(): bool
225
        {
226
                return $this->url->getScheme() === 'https';
1✔
227
        }
228

229

230
        /**
231
         * Checks whether the request is coming from the same site and was initiated by clicking on a link.
232
         */
233
        public function isSameSite(): bool
234
        {
235
                return isset($this->cookies[Helpers::StrictCookieName]);
×
236
        }
237

238

239
        /**
240
         * Checks whether the request origin and initiator match the given Sec-Fetch-Site and Sec-Fetch-Dest values.
241
         * Falls back to the Origin header for browsers that don't send Sec-Fetch headers (Safari < 16.4).
242
         * @param  string|list<string>|null  $site       expected Sec-Fetch-Site values (e.g. 'same-origin', 'cross-site')
243
         * @param  string|list<string>|null  $initiator  expected Sec-Fetch-Dest values (e.g. 'document', 'empty')
244
         */
245
        public function isFrom(string|array|null $site = null, string|array|null $initiator = null): bool
1✔
246
        {
247
                $actualSite = $this->headers['sec-fetch-site'] ?? null;
1✔
248
                $actualDest = $this->headers['sec-fetch-dest'] ?? null;
1✔
249

250
                if ($actualSite === null && ($origin = $this->getOrigin())) { // fallback for Safari < 16.4
1✔
251
                        $actualSite = strcasecmp($origin->getScheme(), $this->url->getScheme()) === 0
1✔
252
                                        && strcasecmp(rtrim($origin->getHost(), '.'), rtrim($this->url->getHost(), '.')) === 0
1✔
253
                                        && $origin->getPort() === $this->url->getPort()
1✔
254
                                ? 'same-origin'
1✔
255
                                : 'cross-site';
1✔
256
                }
257

258
                return ($site === null || ($actualSite !== null && in_array($actualSite, (array) $site, strict: true)))
1✔
259
                        && ($initiator === null || ($actualDest !== null && in_array($actualDest, (array) $initiator, strict: true)));
1✔
260
        }
261

262

263
        /**
264
         * Checks whether the request was made via AJAX (X-Requested-With: XMLHttpRequest).
265
         */
266
        public function isAjax(): bool
267
        {
268
                return $this->getHeader('X-Requested-With') === 'XMLHttpRequest';
×
269
        }
270

271

272
        /**
273
         * Returns the IP address of the remote client.
274
         */
275
        public function getRemoteAddress(): ?string
276
        {
277
                return $this->remoteAddress;
1✔
278
        }
279

280

281
        /**
282
         * Returns the host of the remote client.
283
         */
284
        public function getRemoteHost(): ?string
285
        {
286
                if ($this->remoteHost === null && $this->remoteAddress !== null) {
1✔
287
                        $this->remoteHost = gethostbyaddr($this->remoteAddress) ?: null;
1✔
288
                }
289

290
                return $this->remoteHost;
1✔
291
        }
292

293

294
        /**
295
         * Returns raw content of HTTP request body.
296
         */
297
        public function getRawBody(): ?string
298
        {
299
                return $this->rawBodyCallback ? ($this->rawBodyCallback)() : null;
1✔
300
        }
301

302

303
        /**
304
         * Returns basic HTTP authentication credentials.
305
         * @return array{string, string}|null
306
         */
307
        public function getBasicCredentials(): ?array
308
        {
309
                return preg_match(
1✔
310
                        '~^Basic (\S+)$~',
1✔
311
                        $this->headers['authorization'] ?? '',
1✔
312
                        $t,
1✔
313
                )
314
                        && ($t = base64_decode($t[1], strict: true))
1✔
315
                        && ($t = explode(':', $t, 2))
1✔
316
                        && (count($t) === 2)
1✔
317
                        ? $t
1✔
318
                        : null;
1✔
319
        }
320

321

322
        /**
323
         * Returns the most preferred language from the Accept-Language header that matches one of the supported languages,
324
         * or null if no match is found.
325
         * @param  array<string>  $langs  supported language codes (e.g. ['en', 'cs', 'de'])
326
         */
327
        public function detectLanguage(array $langs): ?string
1✔
328
        {
329
                $header = $this->getHeader('Accept-Language');
1✔
330
                if (!$header) {
1✔
331
                        return null;
1✔
332
                }
333

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

339
                if (!$matches[0]) {
1✔
340
                        return null;
1✔
341
                }
342

343
                $max = 0;
1✔
344
                $lang = null;
1✔
345
                foreach ($matches[1] as $key => $value) {
1✔
346
                        $q = $matches[2][$key] === '' ? 1.0 : (float) $matches[2][$key];
1✔
347
                        if ($q > $max) {
1✔
348
                                $max = $q;
1✔
349
                                $lang = $value;
1✔
350
                        }
351
                }
352

353
                return $lang;
1✔
354
        }
355
}
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