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

nette / http / 22293514258

23 Feb 2026 04:58AM UTC coverage: 83.62%. Remained the same
22293514258

push

github

dg
added CLAUDE.md

924 of 1105 relevant lines covered (83.62%)

0.84 hits per line

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

92.0
/src/Http/Url.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_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;
12
use const IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46, PHP_QUERY_RFC3986;
13

14

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

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

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

62
        /** @var mixed[] */
63
        private array $query = [];
64
        private string $fragment = '';
65

66

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

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

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

92

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

99

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

105

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

113

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

120

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

128

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

135

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

143

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

149

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

164

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

171

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

177

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

183

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

191
                return $this;
1✔
192
        }
193

194

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

200

201
        /** @param string|mixed[] $query */
202
        public function setQuery(string|array $query): static
1✔
203
        {
204
                $this->query = is_array($query) ? $query : self::parseQuery($query);
1✔
205
                return $this;
1✔
206
        }
207

208

209
        /** @param string|mixed[] $query */
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 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
        {
247
                $this->fragment = $fragment;
×
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
        {
296
                $pos = strrpos($this->path, '/');
×
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
        {
304
                return $this->getHostUrl() . $this->getBasePath();
×
305
        }
306

307

308
        /** @deprecated use UrlScript::getRelativeUrl() instead */
309
        public function getRelativeUrl(): string
310
        {
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

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

391

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

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

411

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

425

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

434

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

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