1 | <?php |
||
8 | class Url |
||
9 | { |
||
10 | /** @var string */ |
||
11 | protected $inputUrl; |
||
12 | |||
13 | /** @var array */ |
||
14 | protected $parsedUrl; |
||
15 | |||
16 | /** @var string */ |
||
17 | protected $validatedURL; |
||
18 | |||
19 | /** @var string */ |
||
20 | protected $ipAddress; |
||
21 | |||
22 | public function __toString() |
||
23 | { |
||
24 | return $this->getInputUrl(); |
||
25 | } |
||
26 | |||
27 | 1 | private static function verifyAndGetDNS($domain): ?string |
|
28 | { |
||
29 | 1 | $domainIp = gethostbyname($domain); |
|
30 | 1 | if (! filter_var($domainIp, FILTER_VALIDATE_IP)) { |
|
31 | return null; |
||
32 | } |
||
33 | |||
34 | 1 | return $domainIp; |
|
35 | } |
||
36 | |||
37 | 8 | public function __construct(string $url) |
|
38 | { |
||
39 | 8 | $this->inputUrl = $url; |
|
40 | 8 | $parser = new UriParser(); |
|
41 | 8 | $this->parsedUrl = $parser($this->inputUrl); |
|
42 | |||
43 | // Verify parsing has a host |
||
44 | 8 | if (is_null($this->parsedUrl['host'])) { |
|
45 | try { |
||
46 | 8 | $this->parsedUrl = $parser('https://'.$this->inputUrl); |
|
47 | 6 | } catch (\Exception $e) { |
|
48 | 6 | throw InvalidUrl::couldNotValidate($url); |
|
49 | } |
||
50 | 2 | if (is_null($this->parsedUrl['host'])) { |
|
51 | throw InvalidUrl::couldNotDetermineHost($url); |
||
52 | } |
||
53 | } |
||
54 | |||
55 | 2 | if (! filter_var($this->getValidUrl(), FILTER_VALIDATE_URL)) { |
|
56 | 1 | throw InvalidUrl::couldNotValidate($url); |
|
57 | } |
||
58 | |||
59 | 1 | $this->ipAddress = self::verifyAndGetDNS($this->parsedUrl['host']); |
|
60 | 1 | $this->validatedURL = $url; |
|
61 | 1 | } |
|
62 | |||
63 | public function getIp(): ?string |
||
64 | { |
||
65 | if (null === $this->ipAddress) { |
||
66 | throw InvalidUrl::couldNotResolveDns($this->inputUrl); |
||
67 | } |
||
68 | return $this->ipAddress; |
||
69 | } |
||
70 | |||
71 | public function getInputUrl(): string |
||
72 | { |
||
73 | return $this->inputUrl; |
||
74 | } |
||
75 | |||
76 | 2 | public function getHostName(): string |
|
77 | { |
||
78 | 2 | return $this->parsedUrl['host']; |
|
79 | } |
||
80 | |||
81 | public function getValidatedURL(): string |
||
82 | { |
||
83 | return $this->validatedURL; |
||
84 | } |
||
85 | |||
86 | 2 | public function getPort(): string |
|
87 | { |
||
88 | 2 | return (isset($this->parsedUrl['port'])) ? $this->parsedUrl['port'] : '443'; |
|
89 | } |
||
90 | |||
91 | 1 | public function getTestURL(): string |
|
95 | |||
96 | 2 | public function getValidUrl(): string |
|
97 | { |
||
98 | 2 | if ($this->getPort() === '80') { |
|
99 | return 'http://'.$this->getHostName().'/'; |
||
100 | } |
||
101 | |||
102 | 2 | return 'https://'.$this->getHostName().'/'; |
|
103 | } |
||
104 | } |
||
105 |