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

nette / http / 40214702155

25 Oct 2026 04:58PM UTC coverage: 82.088% (-0.03%) from 82.117%
40214702155

push

github

dg
uses #Deprecated wip

1022 of 1245 relevant lines covered (82.09%)

0.82 hits per line

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

88.06
/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 count, is_array, strlen;
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 $rawBody
29
 */
30
class Request implements IRequest
31
{
32
        use Nette\SmartObject;
33

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

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

40

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

62

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

73

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

82

83
        /********************* query, post, files & cookies ****************d*g**/
84

85

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

97

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

109

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

121

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

131

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

140

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

150

151
        /********************* method & headers ****************d*g**/
152

153

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

162

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

171

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

181

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

191

192
        #[\Deprecated('deprecated in favor of the getOrigin()')]
193
        public function getReferer(): ?UrlImmutable
194
        {
195
                trigger_error(__METHOD__ . '() is deprecated', E_USER_DEPRECATED);
×
196
                return isset($this->headers['referer'])
×
197
                        ? new UrlImmutable($this->headers['referer'])
×
198
                        : null;
×
199
        }
200

201

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

214

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

223

224
        /**
225
         * Checks whether the request originated from your own site (same-site), i.e. it was not
226
         * triggered from a foreign website. Serves as a CSRF-like protection for forms and signals.
227
         * @deprecated use isFrom()
228
         */
229
        public function isSameSite(): bool
230
        {
231
                trigger_error(__METHOD__ . '() is deprecated, use isFrom() instead', E_USER_DEPRECATED);
×
232
                return $this->isFrom([FetchSite::SameSite, FetchSite::SameOrigin]);
×
233
        }
234

235

236
        /**
237
         * Checks whether the request matches the given Sec-Fetch-Site, Sec-Fetch-Dest and Sec-Fetch-User values.
238
         * @param  FetchSite|list<FetchSite>  $site
239
         * @param  FetchDest|list<FetchDest>|null  $dest
240
         */
241
        public function isFrom(
242
                FetchSite|array $site,
243
                FetchDest|array|null $dest = null,
244
                ?bool $user = null,
245
        ): bool
246
        {
247
                $actualSite = FetchSite::tryFrom($this->headers['sec-fetch-site'] ?? '');
1 ✔
248
                $actualDest = FetchDest::tryFrom($this->headers['sec-fetch-dest'] ?? '');
1 ✔
249
                $actualUser = ($this->headers['sec-fetch-user'] ?? null) === '?1';
1 ✔
250
                $site = is_array($site) ? $site : [$site];
1 ✔
251
                $dest = $dest === null || is_array($dest) ? $dest : [$dest];
1 ✔
252

253
                return $actualSite !== null
1 ✔
254
                        && in_array($actualSite, $site, true)
1 ✔
255
                        && ($dest === null || ($actualDest !== null && in_array($actualDest, $dest, true)))
1 ✔
256
                        && ($user === null || $user === $actualUser);
1 ✔
257
        }
258

259

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

268

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

277

278
        /**
279
         * Returns raw content of HTTP request body.
280
         */
281
        public function getRawBody(): ?string
282
        {
283
                return $this->rawBodyCallback ? ($this->rawBodyCallback)() : null;
1 ✔
284
        }
285

286

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

305

306
        /**
307
         * Returns the most preferred language from the Accept-Language header that matches one of the supported languages,
308
         * or null if no match is found.
309
         * @param  array<string>  $langs  supported language codes (e.g. ['en', 'cs', 'de'])
310
         */
311
        public function detectLanguage(array $langs): ?string
312
        {
313
                $header = $this->getHeader('Accept-Language');
1 ✔
314
                if (!$header) {
1 ✔
315
                        return null;
1 ✔
316
                }
317

318
                usort($langs, fn($a, $b) => strlen($b) <=> strlen($a)); // more specific first
1 ✔
319
                $accepted = Helpers::parseQualityList(strtr($header, '_', '-')); // cs_CZ means cs-CZ
1 ✔
320

321
                foreach (array_keys($accepted) as $token) {
1 ✔
322
                        foreach ($langs as $lang) {
1 ✔
323
                                $l = strtolower($lang);
1 ✔
324
                                if ($token === '*' || $token === $l || str_starts_with($token, $l . '-')) {
1 ✔
325
                                        return $lang;
1 ✔
326
                                }
327
                        }
328
                }
329

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

© 2026 Coveralls, Inc