-
Notifications
You must be signed in to change notification settings - Fork 3
/
IRI.php
604 lines (528 loc) · 16.7 KB
/
IRI.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
<?php
/*
* (c) Markus Lanthaler <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ML\IRI;
/**
* IRI represents an IRI as per RFC3987.
*
* @author Markus Lanthaler <[email protected]>
*
* @link http://tools.ietf.org/html/rfc3987 RFC3987
*/
class IRI
{
/**
* The scheme
*
* @var string|null
*/
private $scheme = null;
/**
* The user information
*
* @var string|null
*/
private $userinfo = null;
/**
* The host
*
* @var string|null
*/
private $host = null;
/**
* The port
*
* @var string|null
*/
private $port = null;
/**
* The path
*
* @var string
*/
private $path = '';
/**
* The query component
*
* @var string|null
*/
private $query = null;
/**
* The fragment identifier
*
* @var string|null
*/
private $fragment = null;
/**
* Constructor
*
* @param null|string|IRI $iri The IRI.
*
* @throws \InvalidArgumentException If an invalid IRI is passed.
*
* @api
*/
public function __construct($iri = null)
{
if (null === $iri) {
return;
} elseif (is_string($iri)) {
$this->parse($iri);
} elseif ($iri instanceof IRI) {
$this->scheme = $iri->scheme;
$this->userinfo = $iri->userinfo;
$this->host = $iri->host;
$this->port = $iri->port;
$this->path = $iri->path;
$this->query = $iri->query;
$this->fragment = $iri->fragment;
} else {
throw new \InvalidArgumentException(
'Expecting a string or an IRI, got ' .
(is_object($iri) ? get_class($iri) : gettype($iri))
);
}
}
/**
* Get the scheme
*
* @return string|null Returns the scheme or null if not set.
*/
public function getScheme()
{
return $this->scheme;
}
/**
* Get the authority
*
* @return string|null Returns the authority or null if not set.
*/
public function getAuthority()
{
$authority = null;
if (null !== $this->host) {
if (null !== $this->userinfo) {
$authority .= $this->userinfo . '@';
}
$authority .= $this->host;
if (null !== $this->port) {
$authority .= ':' . $this->port;
}
}
return $authority;
}
/**
* Get the user information
*
* @return string|null Returns the user information or null if not set.
*/
public function getUserInfo()
{
return $this->userinfo;
}
/**
* Get the host
*
* @return string|null Returns the host or null if not set.
*/
public function getHost()
{
return $this->host;
}
/**
* Get the port
*
* @return string|null Returns the port or null if not set.
*/
public function getPort()
{
return $this->port;
}
/**
* Get the path
*
* @return string Returns the path which might be empty.
*/
public function getPath()
{
return $this->path;
}
/**
* Get the query component
*
* @return string|null Returns the query component or null if not set.
*/
public function getQuery()
{
return $this->query;
}
/**
* Get the fragment identifier
*
* @return string|null Returns the fragment identifier or null if not set.
*/
public function getFragment()
{
return $this->fragment;
}
/**
* Find out whether the IRI is absolute
*
* @return bool Returns true if the IRI is absolute, false otherwise.
*
* @api
*/
public function isAbsolute()
{
return (null !== $this->scheme);
}
/**
* Get as absolute IRI, i.e., without fragment identifier
*
* @return IRI The absolute IRI, i.e., without fragment identifier
*
* @throws \UnexpectedValueException If the IRI is a relative IRI.
*
* @link http://tools.ietf.org/html/rfc3987#section-2.2 RFC3987 absolute-IRI
*
* @api
*/
public function getAbsoluteIri()
{
if (false === $this->isAbsolute()) {
throw new \UnexpectedValueException('Cannot get the absolute IRI of a relative IRI.');
}
$absolute = clone $this;
$absolute->fragment = null;
return $absolute;
}
/**
* Check whether the passed IRI is equal
*
* @param IRI|string $iri IRI to compare to this instance.
*
* @return bool Returns true if the two IRIs are equal, false otherwise.
*
* @api
*/
public function equals($iri)
{
// Make sure both instances are strings
return ($this->__toString() === (string)$iri);
}
/**
* Resolve a (relative) IRI reference against this IRI
*
* @param IRI|string $reference The (relative) IRI reference that should
* be resolved against this IRI.
*
* @return IRI The resolved IRI.
*
* @throws \InvalidArgumentException If an invalid IRI is passed.
*
* @link http://tools.ietf.org/html/rfc3986#section-5.2
*
* @api
*/
public function resolve($reference)
{
$reference = new IRI($reference);
$scheme = null;
$authority = null;
$path = '';
$query = null;
$fragment = null;
// The Transform References algorithm as specified by RFC3986
// see: http://tools.ietf.org/html/rfc3986#section-5.2.2
if ($reference->scheme) {
$scheme = $reference->scheme;
$authority = $reference->getAuthority();
$path = self::removeDotSegments($reference->path);
$query = $reference->query;
} else {
if (null !== $reference->getAuthority()) {
$authority = $reference->getAuthority();
$path = self::removeDotSegments($reference->path);
$query = $reference->query;
} else {
if (0 === strlen($reference->path)) {
$path = $this->path;
if (null !== $reference->query) {
$query = $reference->query;
} else {
$query = $this->query;
}
} else {
if ('/' === $reference->path[0]) {
$path = self::removeDotSegments($reference->path);
} else {
// T.path = merge(Base.path, R.path);
if ((null !== $this->getAuthority()) && ('' === $this->path)) {
$path = '/' . $reference->path;
} else {
if (false !== ($end = strrpos($this->path, '/'))) {
$path = substr($this->path, 0, $end + 1);
}
$path .= $reference->path;
}
$path = self::removeDotSegments($path);
}
$query = $reference->query;
}
$authority = $this->getAuthority();
}
$scheme = $this->scheme;
}
$fragment = $reference->fragment;
// The Component Recomposition algorithm as specified by RFC3986
// see: http://tools.ietf.org/html/rfc3986#section-5.3
$result = '';
if ($scheme) {
$result = $scheme . ':';
}
if (null !== $authority) {
$result .= '//' . $authority;
}
$result .= $path;
if (null !== $query) {
$result .= '?' . $query;
}
if (null !== $fragment) {
$result .= '#' . $fragment;
}
return new IRI($result);
}
/**
* Transform this IRI to a IRI reference relative to the passed base IRI
*
* @param IRI|string $base The (relative) IRI reference that should be
* be used as base IRI.
* @param bool Defines whether schema-relative IRIs such
* as `//example.com` should be created (`true`)
* or not (`false`).
*
* @return IRI The IRI reference relative to the passed base IRI.
*
* @throws \InvalidArgumentException If an invalid IRI is passed.
*
* @api
*/
public function relativeTo($base, $schemaRelative = false)
{
if (false === ($base instanceof IRI)) {
$base = new IRI($base);
}
$relative = clone $this;
// Compare scheme
if ($relative->scheme !== $base->scheme) {
return $relative;
}
// Compare authority
if ($relative->getAuthority() !== $base->getAuthority()) {
if (true === $schemaRelative) {
$relative->scheme = null;
}
return $relative;
}
$relative->scheme = null;
$relative->host = null;
$relative->userinfo = null;
$relative->port = null;
// Compare path
$baseSegments = explode('/', $base->path);
$relativeSegments = explode('/', $relative->path);
$len = min(count($baseSegments), count($relativeSegments)) - 1; // do not move beyond last segment
$pos = 0;
while (($baseSegments[$pos] === $relativeSegments[$pos]) && ($pos < $len)) {
$pos++;
}
$relative->path = '';
$numBaseSegments = count($baseSegments) - $pos - 1;
if ($numBaseSegments > 0) {
$relative->path .= str_repeat('../', $numBaseSegments);
}
if (($baseSegments[$pos] !== $relativeSegments[$pos]) ||
((null === $relative->query) && (null === $relative->fragment)) ||
($base->path === '')) {
// if the two paths differ or if there's neither a query component nor a fragment
// or there is no base path, we need to consider this IRI's path
if (($relative->path === '') && (false !== strpos($relativeSegments[$pos], ':'))) {
// if the first path segment contains a colon, we need to
// prepend a ./ to distinguish it from an absolute IRI
$relative->path .= './';
}
$relative->path .= implode('/', array_slice($relativeSegments, $pos));
// .. and ensure that the resulting path isn't empty
if (($relative->path === '')) {
$relative->path .= './';
}
}
if ($relative->query !== $base->query) {
return $relative;
}
if (null !== $relative->fragment) {
$relative->query = null;
}
return $relative;
}
/**
* Convert an IRI to a relative IRI reference using this IRI as base
*
* This method provides a more convenient interface than the
* {@link IRI::relativeTo()} method if the base IRI stays the same while
* the IRIs to convert to relative IRI references change.
*
* @param string|IRI $iri The IRI to convert to a relative reference
* @param bool Defines whether schema-relative IRIs such
* as `//example.com` should be created (`true`)
* or not (`false`).
*
* @throws \InvalidArgumentException If an invalid IRI is passed.
*
* @see \ML\IRI\IRI::relativeTo()
*
* @return IRI The relative IRI reference
*/
public function baseFor($iri, $schemaRelative = false)
{
if (false === ($iri instanceof IRI)) {
$iri = new IRI($iri);
}
return $iri->relativeTo($this, $schemaRelative);
}
/**
* Get a string representation of this IRI object
*
* @return string A string representation of this IRI instance.
*
* @api
*/
public function __toString()
{
$result = '';
if ($this->scheme) {
$result .= $this->scheme . ':';
}
if (null !== ($authority = $this->getAuthority())) {
$result .= '//' . $authority;
}
$result .= $this->path;
if (null !== $this->query) {
$result .= '?' . $this->query;
}
if (null !== $this->fragment) {
$result .= '#' . $this->fragment;
}
return $result;
}
/**
* Parse an IRI into it's components
*
* This is done according to
* {@link http://tools.ietf.org/html/rfc3986#section-3.1 RFC3986}.
*
* @param string $iri The IRI to parse.
*/
protected function parse($iri)
{
// Parse IRI by using the regular expression as specified by
// http://tools.ietf.org/html/rfc3986#appendix-B
$regex = '|^((?P<scheme>[^:/?#]+):)?' .
'((?P<doubleslash>//)(?P<authority>[^/?#]*))?(?P<path>[^?#]*)' .
'((?P<querydef>\?)(?P<query>[^#]*))?(#(?P<fragment>.*))?|';
preg_match($regex, $iri, $match);
// Extract scheme
if (false === empty($match['scheme'])) {
$this->scheme = $match['scheme'];
}
// Parse authority (http://tools.ietf.org/html/rfc3986#section-3.2)
if ('//' === $match['doubleslash']) {
if (0 === strlen($match['authority'])) {
$this->host = '';
} else {
$authority = $match['authority'];
// Split authority into userinfo and host
// (use last @ to ignore unescaped @ symbols)
if (false !== ($pos = strrpos($authority, '@'))) {
$this->userinfo = substr($authority, 0, $pos);
$authority = substr($authority, $pos + 1);
}
// Split authority into host and port
$hostEnd = 0;
if ((strlen($authority) > 0) &&
('[' === $authority[0]) &&
(false !== ($pos = strpos($authority, ']')))) {
$hostEnd = $pos;
}
if ((false !== ($pos = strrpos($authority, ':'))) && ($pos > $hostEnd)) {
$this->host = substr($authority, 0, $pos);
$this->port = substr($authority, $pos + 1);
} else {
$this->host = $authority;
}
}
}
// Extract path (http://tools.ietf.org/html/rfc3986#section-3.3)
// The path is always present but might be empty
$this->path = $match['path'];
// Extract query (http://tools.ietf.org/html/rfc3986#section-3.4)
if (false === empty($match['querydef'])) {
$this->query = $match['query'];
}
// Extract fragment (http://tools.ietf.org/html/rfc3986#section-3.5)
if (isset($match['fragment'])) {
$this->fragment = $match['fragment'];
}
}
/**
* Remove dot-segments
*
* This method removes the special "." and ".." complete path segments
* from an IRI.
*
* @param string $input The IRI from which dot segments should be removed.
*
* @return string The IRI with all dot-segments removed.
*
* @link http://tools.ietf.org/html/rfc3986#section-5.2.4
*/
private static function removeDotSegments($input)
{
$output = '';
while (strlen($input) > 0) {
if (('../' === substr($input, 0, 3)) || ('./' === substr($input, 0, 2))) {
$input = substr($input, strpos($input, '/'));
} elseif ('/./' === substr($input, 0, 3)) {
$input = substr($input, 2);
} elseif ('/.' === $input) {
$input = '/';
} elseif (('/../' === substr($input, 0, 4)) || ('/..' === $input)) {
if ($input == '/..') {
$input = '/';
} else {
$input = substr($input, 3);
}
if (false !== ($end = strrpos($output, '/'))) {
$output = substr($output, 0, $end);
} else {
$output = '';
}
} elseif (('..' === $input) || ('.' === $input)) {
$input = '';
} else {
if (false === ($end = strpos($input, '/', 1))) {
$output .= $input;
$input = '';
} else {
$output .= substr($input, 0, $end);
$input = substr($input, $end);
}
}
}
return $output;
}
}