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

nette / http / 11677741619

05 Nov 2024 04:45AM UTC coverage: 82.146% (+0.4%) from 81.742%
11677741619

push

github

dg
IRequest, IResponse: added typehints, unification (BC break)

2 of 2 new or added lines in 1 file covered. (100.0%)

13 existing lines in 2 files now uncovered.

911 of 1109 relevant lines covered (82.15%)

0.82 hits per line

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

89.68
/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
                trigger_error(__METHOD__ . '() is deprecated', E_USER_DEPRECATED);
×
UNCOV
107
                $this->user = $user;
×
UNCOV
108
                return $this;
×
109
        }
110

111

112
        /** @deprecated */
113
        public function getUser(): string
114
        {
115
                trigger_error(__METHOD__ . '() is deprecated', E_USER_DEPRECATED);
1✔
116
                return $this->user;
1✔
117
        }
118

119

120
        /** @deprecated */
121
        public function setPassword(string $password): static
122
        {
UNCOV
123
                trigger_error(__METHOD__ . '() is deprecated', E_USER_DEPRECATED);
×
UNCOV
124
                $this->password = $password;
×
UNCOV
125
                return $this;
×
126
        }
127

128

129
        /** @deprecated */
130
        public function getPassword(): string
131
        {
132
                trigger_error(__METHOD__ . '() is deprecated', E_USER_DEPRECATED);
1✔
133
                return $this->password;
1✔
134
        }
135

136

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

144

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

150

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

165

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

172

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

178

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

184

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

192
                return $this;
1✔
193
        }
194

195

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

201

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

217

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

223

224
        public function getQueryParameters(): array
225
        {
226
                return $this->query;
1✔
227
        }
228

229

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

235

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

242

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

249

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

255

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

263

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

280

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

290

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

299

300
        /** @deprecated use UrlScript::getBaseUrl() instead */
301
        public function getBaseUrl(): string
302
        {
303
                trigger_error(__METHOD__ . '() is deprecated, use UrlScript object', E_USER_DEPRECATED);
×
304
                return $this->getHostUrl() . $this->getBasePath();
×
305
        }
306

307

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

315

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

339

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

355

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

361

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

367

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

374

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

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

UNCOV
388
                trigger_error('PHP extension intl is not loaded or is too old', E_USER_WARNING);
×
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,
405
                        );
406
                }
407

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

411

412
        /**
413
         * Parses query string. Is affected by directive arg_separator.input.
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
        public static function isAbsolute(string $url): bool
1✔
426
        {
427
                return (bool) preg_match('#^[a-z][a-z0-9+.-]*:#i', $url);
1✔
428
        }
429

430

431
        public static function removeDotSegments(string $path): string
1✔
432
        {
433
                $prefix = $segment = '';
1✔
434
                if (str_starts_with($path, '/')) {
1✔
435
                        $prefix = '/';
1✔
436
                        $path = substr($path, 1);
1✔
437
                }
438
                $segments = explode('/', $path);
1✔
439
                $res = [];
1✔
440
                foreach ($segments as $segment) {
1✔
441
                        if ($segment === '..') {
1✔
442
                                array_pop($res);
1✔
443
                        } elseif ($segment !== '.') {
1✔
444
                                $res[] = $segment;
1✔
445
                        }
446
                }
447

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