-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUrlGenerationContext.php
93 lines (73 loc) · 2.38 KB
/
UrlGenerationContext.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
declare(strict_types=1);
namespace Snicco\Component\HttpRouting\Routing\UrlGenerator;
use Webmozart\Assert\Assert;
use function parse_url;
final class UrlGenerationContext
{
private string $host;
private int $https_port;
private int $http_port;
private bool $https_by_default;
public function __construct(
string $host,
int $https_port = 443,
int $http_port = 80,
bool $https_by_default = true
) {
Assert::stringNotEmpty($host, '$host cant be empty.');
Assert::notContains($host, 'http', '$host must not contain a scheme.');
Assert::notContains($host, '://', '$host must not contain a scheme.');
$this->host = $host;
Assert::positiveInteger($https_port);
$this->https_port = $https_port;
Assert::positiveInteger($http_port);
$this->http_port = $http_port;
$this->https_by_default = $https_by_default;
}
public static function fromUrlAndParts(
string $url,
?string $host = null,
?int $https_port = null,
?int $http_port = null,
?bool $https_by_default = null
): self {
$parts = parse_url($url);
Assert::isArray($parts, "{$url} is not a valid url.");
Assert::keyExists($parts, 'host', "{$url} is not a valid url. 'host' is missing.");
Assert::keyExists($parts, 'scheme', "{$url} is not a valid url. 'scheme' is missing.");
/** @var array{host: string, scheme: string, port?: int} $parts */
$host = $host ?? $parts['host'];
$scheme_https = 'https' === $parts['scheme'];
if ($scheme_https) {
$https_port = $https_port ?? $parts['port'] ?? 443;
$http_port = $http_port ?? 80;
} else {
$https_port = $https_port ?? 443;
$http_port = $http_port ?? $parts['port'] ?? 80;
}
$https_by_default = $https_by_default ?? $scheme_https;
return new self(
$host,
$https_port,
$http_port,
$https_by_default
);
}
public function host(): string
{
return $this->host;
}
public function httpsPort(): int
{
return $this->https_port;
}
public function httpPort(): int
{
return $this->http_port;
}
public function httpsByDefault(): bool
{
return $this->https_by_default;
}
}