-
Notifications
You must be signed in to change notification settings - Fork 0
/
Url.php
93 lines (76 loc) 路 2.5 KB
/
Url.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
<?php
namespace Urling\Core;
use Urling\Core\Misc\UrlParser;
use Urling\Core\Misc\Tools\Tools;
use Urling\Core\Misc\BaseEditors\BaseUrlEditor;
use Urling\Core\Misc\PartParsers\Registrars\AliasesRegistrar;
use Urling\Core\Misc\PartParsers\Registrars\ParsersRegistrar;
use Urling\Core\Misc\Exceptions\IntelliExceptions\IntelliExceptions;
use Webmozart\Assert\Assert;
final class Url
{
use ParsersRegistrar;
use AliasesRegistrar;
use IntelliExceptions;
use BaseUrlEditor;
protected ?string $origin;
public function __construct(string $url = null)
{
$this->origin = trim((string) $url);
$this->bootstrap();
if (mb_strlen((string) $this->origin) && !$this->get()) {
throw new \Exception("Incorrect URL passed!");
}
}
/**
* @return void
*/
protected function bootstrap(): void
{
$this->registerParsers();
$this->registerAliases();
}
/**
* @param array<string, string|null> $url_parts
*
* @return string|null
*/
public function construct(array $url_parts): ?string
{
$parts = array_keys($url_parts);
$values = array_values($url_parts);
foreach ($parts as $index => $part) {
if (!UrlParser::searchUrlPart($part)) {
throw new \Exception("Unsupported name or alias for the part of URL: $part!");
}
$this->{$part}->add($values[$index]);
}
return $this->get();
}
/**
* @param string $url
* @param string|null $origin
* @param bool $verify_protocols
*
* @return bool
*/
public function isSameOrigin(string $url, string $origin = null, bool $verify_protocols = true): bool
{
if (!($origin = $origin ?: $this->origin)) {
return false;
}
if (($verify_protocols && ($url && $origin))) {
$url_protocol = UrlParser::getPartValueFromUrl($url, "protocol");
$origin_protocol = UrlParser::getPartValueFromUrl($origin, "protocol");
if (!Tools::isSameStrings((string) $url_protocol, (string) $origin_protocol)) {
return false;
}
}
$url_hostname = UrlParser::getPartValueFromUrl($url, "hostname");
$origin_hostname = UrlParser::getPartValueFromUrl($origin, "hostname");
if (!$url_hostname || !$origin_hostname) {
return false;
}
return Tools::isSameStrings((string) $url_hostname, (string) $origin_hostname);
}
}