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

nette / http / 15478969015

05 Jun 2025 11:00PM UTC coverage: 83.441%. Remained the same
15478969015

push

github

dg
Url, UrlImmutable: user & password are deprecated

907 of 1087 relevant lines covered (83.44%)

0.83 hits per line

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

92.57
/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

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 $queryParameters
43
 */
44
class Url implements \JsonSerializable
45
{
46
        use Nette\SmartObject;
47

48
        public static array $defaultPorts = [
49
                'http' => 80,
50
                'https' => 443,
51
                'ftp' => 21,
52
        ];
53

54
        private string $scheme = '';
55
        private string $user = '';
56
        private string $password = '';
57
        private string $host = '';
58
        private ?int $port = null;
59
        private string $path = '';
60
        private array $query = [];
61
        private string $fragment = '';
62

63

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

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

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

89

90
        public function setScheme(string $scheme): static
1✔
91
        {
92
                $this->scheme = $scheme;
1✔
93
                return $this;
1✔
94
        }
95

96

97
        public function getScheme(): string
98
        {
99
                return $this->scheme;
1✔
100
        }
101

102

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

110

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

117

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

125

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

132

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

140

141
        public function getHost(): string
142
        {
143
                return $this->host;
1✔
144
        }
145

146

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

161

162
        public function setPort(int $port): static
1✔
163
        {
164
                $this->port = $port;
1✔
165
                return $this;
1✔
166
        }
167

168

169
        public function getPort(): ?int
170
        {
171
                return $this->port ?: $this->getDefaultPort();
1✔
172
        }
173

174

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

180

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

188
                return $this;
1✔
189
        }
190

191

192
        public function getPath(): string
193
        {
194
                return $this->path;
1✔
195
        }
196

197

198
        public function setQuery(string|array $query): static
1✔
199
        {
200
                $this->query = is_array($query) ? $query : self::parseQuery($query);
1✔
201
                return $this;
1✔
202
        }
203

204

205
        public function appendQuery(string|array $query): static
1✔
206
        {
207
                $this->query = is_array($query)
1✔
208
                        ? $query + $this->query
1✔
209
                        : self::parseQuery($this->getQuery() . '&' . $query);
1✔
210
                return $this;
1✔
211
        }
212

213

214
        public function getQuery(): string
215
        {
216
                return http_build_query($this->query, '', '&', PHP_QUERY_RFC3986);
1✔
217
        }
218

219

220
        public function getQueryParameters(): array
221
        {
222
                return $this->query;
1✔
223
        }
224

225

226
        public function getQueryParameter(string $name): mixed
1✔
227
        {
228
                return $this->query[$name] ?? null;
1✔
229
        }
230

231

232
        public function setQueryParameter(string $name, mixed $value): static
1✔
233
        {
234
                $this->query[$name] = $value;
1✔
235
                return $this;
1✔
236
        }
237

238

239
        public function setFragment(string $fragment): static
240
        {
241
                $this->fragment = $fragment;
×
242
                return $this;
×
243
        }
244

245

246
        public function getFragment(): string
247
        {
248
                return $this->fragment;
1✔
249
        }
250

251

252
        public function getAbsoluteUrl(): string
253
        {
254
                return $this->getHostUrl() . $this->path
1✔
255
                        . (($tmp = $this->getQuery()) ? '?' . $tmp : '')
1✔
256
                        . ($this->fragment === '' ? '' : '#' . $this->fragment);
1✔
257
        }
258

259

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

276

277
        /**
278
         * Returns the scheme and authority part of URI.
279
         */
280
        public function getHostUrl(): string
281
        {
282
                return ($this->scheme ? $this->scheme . ':' : '')
1✔
283
                        . (($authority = $this->getAuthority()) !== '' ? '//' . $authority : '');
1✔
284
        }
285

286

287
        /** @deprecated use UrlScript::getBasePath() instead */
288
        public function getBasePath(): string
289
        {
290
                $pos = strrpos($this->path, '/');
×
291
                return $pos === false ? '' : substr($this->path, 0, $pos + 1);
×
292
        }
293

294

295
        /** @deprecated use UrlScript::getBaseUrl() instead */
296
        public function getBaseUrl(): string
297
        {
298
                return $this->getHostUrl() . $this->getBasePath();
×
299
        }
300

301

302
        /** @deprecated use UrlScript::getRelativeUrl() instead */
303
        public function getRelativeUrl(): string
304
        {
305
                return substr($this->getAbsoluteUrl(), strlen($this->getBaseUrl()));
×
306
        }
307

308

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

332

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

348

349
        public function __toString(): string
350
        {
351
                return $this->getAbsoluteUrl();
1✔
352
        }
353

354

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

360

361
        /** @internal */
362
        final public function export(): array
363
        {
364
                return [$this->scheme, $this->user, $this->password, $this->host, $this->port, $this->path, $this->query, $this->fragment];
1✔
365
        }
366

367

368
        /**
369
         * Converts IDN ASCII host to UTF-8.
370
         */
371
        private static function idnHostToUnicode(string $host): string
1✔
372
        {
373
                if (!str_contains($host, '--')) { // host does not contain IDN
1✔
374
                        return $host;
1✔
375
                }
376

377
                if (function_exists('idn_to_utf8') && defined('INTL_IDNA_VARIANT_UTS46')) {
1✔
378
                        return idn_to_utf8($host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) ?: $host;
1✔
379
                }
380

381
                trigger_error('PHP extension intl is not loaded or is too old', E_USER_WARNING);
×
382
        }
383

384

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

401
                return rawurldecode($s);
1✔
402
        }
403

404

405
        /**
406
         * Parses query string. Is affected by directive arg_separator.input.
407
         */
408
        public static function parseQuery(string $s): array
1✔
409
        {
410
                $s = str_replace(['%5B', '%5b'], '[', $s);
1✔
411
                $sep = preg_quote(ini_get('arg_separator.input'));
1✔
412
                $s = preg_replace("#([$sep])([^[$sep=]+)([^$sep]*)#", '&0[$2]$3', '&' . $s);
1✔
413
                parse_str($s, $res);
1✔
414
                return $res[0] ?? [];
1✔
415
        }
416

417

418
        /**
419
         * Determines if URL is absolute, ie if it starts with a scheme followed by colon.
420
         */
421
        public static function isAbsolute(string $url): bool
1✔
422
        {
423
                return (bool) preg_match('#^[a-z][a-z0-9+.-]*:#i', $url);
1✔
424
        }
425

426

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

447
                if ($segment === '.' || $segment === '..') {
1✔
448
                        $res[] = '';
1✔
449
                }
450
                return $prefix . implode('/', $res);
1✔
451
        }
452
}
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