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

nette / http / 21830508055

09 Feb 2026 03:10PM UTC coverage: 83.772% (+0.03%) from 83.744%
21830508055

push

github

dg
added RequestFactory::setForceHttps()

8 of 9 new or added lines in 2 files covered. (88.89%)

75 existing lines in 9 files now uncovered.

924 of 1103 relevant lines covered (83.77%)

0.84 hits per line

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

92.62
/src/Http/Url.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
use function array_pop, array_slice, bin2hex, chunk_split, defined, explode, function_exists, http_build_query, idn_to_utf8, implode, ini_get, ip2long, is_array, is_string, ksort, parse_str, parse_url, preg_match, preg_quote, preg_replace, preg_replace_callback, rawurldecode, rawurlencode, rtrim, str_contains, str_replace, str_starts_with, strcasecmp, strlen, strrpos, strtolower, strtoupper, substr;
14
use const IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46, PHP_QUERY_RFC3986;
15

16

17
/**
18
 * Mutable representation of a URL.
19
 *
20
 * <pre>
21
 * scheme  user  password  host  port      path        query    fragment
22
 *   |      |      |        |      |        |            |         |
23
 * /--\   /--\ /------\ /-------\ /--\/------------\ /--------\ /------\
24
 * http://john:x0y17575@nette.org:8042/en/manual.php?name=param#fragment  <-- absoluteUrl
25
 * \______\__________________________/
26
 *     |               |
27
 *  hostUrl        authority
28
 * </pre>
29
 *
30
 * @property   string $scheme
31
 * @property   string $user
32
 * @property   string $password
33
 * @property   string $host
34
 * @property   int $port
35
 * @property   string $path
36
 * @property   string $query
37
 * @property   string $fragment
38
 * @property-read string $absoluteUrl
39
 * @property-read string $authority
40
 * @property-read string $hostUrl
41
 * @property-read string $basePath
42
 * @property-read string $baseUrl
43
 * @property-read string $relativeUrl
44
 * @property-read array $queryParameters
45
 */
46
class Url implements \JsonSerializable
47
{
48
        use Nette\SmartObject;
49

50
        /** @var array<string, int> */
51
        public static array $defaultPorts = [
52
                'http' => 80,
53
                'https' => 443,
54
                'ftp' => 21,
55
        ];
56

57
        private string $scheme = '';
58
        private string $user = '';
59
        private string $password = '';
60
        private string $host = '';
61
        private ?int $port = null;
62
        private string $path = '';
63

64
        /** @var array<string, mixed> */
65
        private array $query = [];
66
        private string $fragment = '';
67

68

69
        /**
70
         * @throws Nette\InvalidArgumentException if URL is malformed
71
         */
72
        public function __construct(string|self|UrlImmutable|null $url = null)
1✔
73
        {
74
                if (is_string($url)) {
1✔
75
                        $p = @parse_url($url); // @ - is escalated to exception
1✔
76
                        if ($p === false) {
1✔
77
                                throw new Nette\InvalidArgumentException("Malformed or unsupported URI '$url'.");
1✔
78
                        }
79

80
                        $this->scheme = $p['scheme'] ?? '';
1✔
81
                        $this->port = $p['port'] ?? null;
1✔
82
                        $this->host = rawurldecode($p['host'] ?? '');
1✔
83
                        $this->user = rawurldecode($p['user'] ?? '');
1✔
84
                        $this->password = rawurldecode($p['pass'] ?? '');
1✔
85
                        $this->setPath($p['path'] ?? '');
1✔
86
                        $this->setQuery($p['query'] ?? []);
1✔
87
                        $this->fragment = rawurldecode($p['fragment'] ?? '');
1✔
88

89
                } elseif ($url instanceof UrlImmutable || $url instanceof self) {
1✔
90
                        [$this->scheme, $this->user, $this->password, $this->host, $this->port, $this->path, $this->query, $this->fragment] = $url->export();
1✔
91
                }
92
        }
1✔
93

94

95
        public function setScheme(string $scheme): static
1✔
96
        {
97
                $this->scheme = $scheme;
1✔
98
                return $this;
1✔
99
        }
100

101

102
        public function getScheme(): string
103
        {
104
                return $this->scheme;
1✔
105
        }
106

107

108
        /** @deprecated */
109
        public function setUser(string $user): static
110
        {
UNCOV
111
                $this->user = $user;
×
UNCOV
112
                return $this;
×
113
        }
114

115

116
        /** @deprecated */
117
        public function getUser(): string
118
        {
119
                return $this->user;
1✔
120
        }
121

122

123
        /** @deprecated */
124
        public function setPassword(string $password): static
125
        {
UNCOV
126
                $this->password = $password;
×
UNCOV
127
                return $this;
×
128
        }
129

130

131
        /** @deprecated */
132
        public function getPassword(): string
133
        {
134
                return $this->password;
1✔
135
        }
136

137

138
        public function setHost(string $host): static
1✔
139
        {
140
                $this->host = $host;
1✔
141
                $this->setPath($this->path);
1✔
142
                return $this;
1✔
143
        }
144

145

146
        public function getHost(): string
147
        {
148
                return $this->host;
1✔
149
        }
150

151

152
        /**
153
         * Returns the part of domain.
154
         */
155
        public function getDomain(int $level = 2): string
1✔
156
        {
157
                $parts = ip2long($this->host)
1✔
158
                        ? [$this->host]
1✔
159
                        : explode('.', $this->host);
1✔
160
                $parts = $level >= 0
1✔
161
                        ? array_slice($parts, -$level)
1✔
162
                        : array_slice($parts, 0, $level);
1✔
163
                return implode('.', $parts);
1✔
164
        }
165

166

167
        public function setPort(int $port): static
1✔
168
        {
169
                $this->port = $port;
1✔
170
                return $this;
1✔
171
        }
172

173

174
        public function getPort(): ?int
175
        {
176
                return $this->port ?: $this->getDefaultPort();
1✔
177
        }
178

179

180
        public function getDefaultPort(): ?int
181
        {
182
                return self::$defaultPorts[$this->scheme] ?? null;
1✔
183
        }
184

185

186
        public function setPath(string $path): static
1✔
187
        {
188
                $this->path = $path;
1✔
189
                if ($this->host && !str_starts_with($this->path, '/')) {
1✔
190
                        $this->path = '/' . $this->path;
1✔
191
                }
192

193
                return $this;
1✔
194
        }
195

196

197
        public function getPath(): string
198
        {
199
                return $this->path;
1✔
200
        }
201

202

203
        public function setQuery(string|array $query): static
1✔
204
        {
205
                $this->query = is_array($query) ? $query : self::parseQuery($query);
1✔
206
                return $this;
1✔
207
        }
208

209

210
        public function appendQuery(string|array $query): static
1✔
211
        {
212
                $this->query = is_array($query)
1✔
213
                        ? $query + $this->query
1✔
214
                        : self::parseQuery($this->getQuery() . '&' . $query);
1✔
215
                return $this;
1✔
216
        }
217

218

219
        public function getQuery(): string
220
        {
221
                return http_build_query($this->query, '', '&', PHP_QUERY_RFC3986);
1✔
222
        }
223

224

225
        /** @return array<string, mixed> */
226
        public function getQueryParameters(): array
227
        {
228
                return $this->query;
1✔
229
        }
230

231

232
        public function getQueryParameter(string $name): mixed
1✔
233
        {
234
                return $this->query[$name] ?? null;
1✔
235
        }
236

237

238
        public function setQueryParameter(string $name, mixed $value): static
1✔
239
        {
240
                $this->query[$name] = $value;
1✔
241
                return $this;
1✔
242
        }
243

244

245
        public function setFragment(string $fragment): static
246
        {
UNCOV
247
                $this->fragment = $fragment;
×
UNCOV
248
                return $this;
×
249
        }
250

251

252
        public function getFragment(): string
253
        {
254
                return $this->fragment;
1✔
255
        }
256

257

258
        public function getAbsoluteUrl(): string
259
        {
260
                return $this->getHostUrl() . $this->path
1✔
261
                        . (($tmp = $this->getQuery()) ? '?' . $tmp : '')
1✔
262
                        . ($this->fragment === '' ? '' : '#' . $this->fragment);
1✔
263
        }
264

265

266
        /**
267
         * Returns the [user[:pass]@]host[:port] part of URI.
268
         */
269
        public function getAuthority(): string
270
        {
271
                return $this->host === ''
1✔
272
                        ? ''
1✔
273
                        : ($this->user !== ''
1✔
274
                                ? rawurlencode($this->user) . ($this->password === '' ? '' : ':' . rawurlencode($this->password)) . '@'
1✔
275
                                : '')
1✔
276
                        . $this->host
1✔
277
                        . ($this->port && $this->port !== $this->getDefaultPort()
1✔
278
                                ? ':' . $this->port
1✔
279
                                : '');
1✔
280
        }
281

282

283
        /**
284
         * Returns the scheme and authority part of URI.
285
         */
286
        public function getHostUrl(): string
287
        {
288
                return ($this->scheme ? $this->scheme . ':' : '')
1✔
289
                        . (($authority = $this->getAuthority()) !== '' ? '//' . $authority : '');
1✔
290
        }
291

292

293
        /** @deprecated use UrlScript::getBasePath() instead */
294
        public function getBasePath(): string
295
        {
UNCOV
296
                $pos = strrpos($this->path, '/');
×
UNCOV
297
                return $pos === false ? '' : substr($this->path, 0, $pos + 1);
×
298
        }
299

300

301
        /** @deprecated use UrlScript::getBaseUrl() instead */
302
        public function getBaseUrl(): string
303
        {
UNCOV
304
                return $this->getHostUrl() . $this->getBasePath();
×
305
        }
306

307

308
        /** @deprecated use UrlScript::getRelativeUrl() instead */
309
        public function getRelativeUrl(): string
310
        {
UNCOV
311
                return substr($this->getAbsoluteUrl(), strlen($this->getBaseUrl()));
×
312
        }
313

314

315
        /**
316
         * URL comparison.
317
         */
318
        public function isEqual(string|self|UrlImmutable $url): bool
1✔
319
        {
320
                $url = new self($url);
1✔
321
                $query = $url->query;
1✔
322
                ksort($query);
1✔
323
                $query2 = $this->query;
1✔
324
                ksort($query2);
1✔
325
                $host = rtrim($url->host, '.');
1✔
326
                $host2 = rtrim($this->host, '.');
1✔
327
                return $url->scheme === $this->scheme
1✔
328
                        && (!strcasecmp($host, $host2)
1✔
329
                                || self::idnHostToUnicode($host) === self::idnHostToUnicode($host2))
1✔
330
                        && $url->getPort() === $this->getPort()
1✔
331
                        && $url->user === $this->user
1✔
332
                        && $url->password === $this->password
1✔
333
                        && self::unescape($url->path, '%/') === self::unescape($this->path, '%/')
1✔
334
                        && $query === $query2
1✔
335
                        && $url->fragment === $this->fragment;
1✔
336
        }
337

338

339
        /**
340
         * Transforms URL to canonical form.
341
         */
342
        public function canonicalize(): static
343
        {
344
                $this->path = preg_replace_callback(
1✔
345
                        '#[^!$&\'()*+,/:;=@%"]+#',
1✔
346
                        fn(array $m): string => rawurlencode($m[0]),
1✔
347
                        self::unescape($this->path, '%/'),
1✔
348
                );
349
                $this->host = rtrim($this->host, '.');
1✔
350
                $this->host = self::idnHostToUnicode(strtolower($this->host));
1✔
351
                return $this;
1✔
352
        }
353

354

355
        public function __toString(): string
356
        {
357
                return $this->getAbsoluteUrl();
1✔
358
        }
359

360

361
        public function jsonSerialize(): string
362
        {
363
                return $this->getAbsoluteUrl();
1✔
364
        }
365

366

367
        /** @internal */
368
        final public function export(): array
369
        {
370
                return [$this->scheme, $this->user, $this->password, $this->host, $this->port, $this->path, $this->query, $this->fragment];
1✔
371
        }
372

373

374
        /**
375
         * Converts IDN ASCII host to UTF-8.
376
         */
377
        private static function idnHostToUnicode(string $host): string
1✔
378
        {
379
                if (!str_contains($host, '--')) { // host does not contain IDN
1✔
380
                        return $host;
1✔
381
                }
382

383
                if (function_exists('idn_to_utf8') && defined('INTL_IDNA_VARIANT_UTS46')) {
1✔
384
                        return idn_to_utf8($host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) ?: $host;
1✔
385
                }
386

UNCOV
387
                trigger_error('PHP extension intl is not loaded or is too old', E_USER_WARNING);
×
388
        }
389

390

391
        /**
392
         * Similar to rawurldecode, but preserves reserved chars encoded.
393
         */
394
        public static function unescape(string $s, string $reserved = '%;/?:@&=+$,'): string
1✔
395
        {
396
                // reserved (@see RFC 2396) = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
397
                // within a path segment, the characters "/", ";", "=", "?" are reserved
398
                // within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", "$" are reserved.
399
                if ($reserved !== '') {
1✔
400
                        $s = preg_replace_callback(
1✔
401
                                '#%(' . substr(chunk_split(bin2hex($reserved), 2, '|'), 0, -1) . ')#i',
1✔
402
                                fn(array $m): string => '%25' . strtoupper($m[1]),
1✔
403
                                $s,
1✔
404
                        );
405
                }
406

407
                return rawurldecode($s);
1✔
408
        }
409

410

411
        /**
412
         * Parses query string. Is affected by directive arg_separator.input.
413
         * @return array<string, mixed>
414
         */
415
        public static function parseQuery(string $s): array
1✔
416
        {
417
                $s = str_replace(['%5B', '%5b'], '[', $s);
1✔
418
                $sep = preg_quote(ini_get('arg_separator.input'));
1✔
419
                $s = preg_replace("#([$sep])([^[$sep=]+)([^$sep]*)#", '&0[$2]$3', '&' . $s);
1✔
420
                parse_str($s, $res);
1✔
421
                return $res[0] ?? [];
1✔
422
        }
423

424

425
        /**
426
         * Determines if URL is absolute, ie if it starts with a scheme followed by colon.
427
         */
428
        public static function isAbsolute(string $url): bool
1✔
429
        {
430
                return (bool) preg_match('#^[a-z][a-z0-9+.-]*:#i', $url);
1✔
431
        }
432

433

434
        /**
435
         * Normalizes a path by handling and removing relative path references like '.', '..' and directory traversal.
436
         */
437
        public static function removeDotSegments(string $path): string
1✔
438
        {
439
                $prefix = $segment = '';
1✔
440
                if (str_starts_with($path, '/')) {
1✔
441
                        $prefix = '/';
1✔
442
                        $path = substr($path, 1);
1✔
443
                }
444
                $segments = explode('/', $path);
1✔
445
                $res = [];
1✔
446
                foreach ($segments as $segment) {
1✔
447
                        if ($segment === '..') {
1✔
448
                                array_pop($res);
1✔
449
                        } elseif ($segment !== '.') {
1✔
450
                                $res[] = $segment;
1✔
451
                        }
452
                }
453

454
                if ($segment === '.' || $segment === '..') {
1✔
455
                        $res[] = '';
1✔
456
                }
457
                return $prefix . implode('/', $res);
1✔
458
        }
459
}
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