/
Whois.php
118 lines (102 loc) · 2.91 KB
/
Whois.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
<?php
/*
* This file is part of the Chanshige\Whois package.
*
* (c) shigeki tanaka <dev@shigeki.tokyo>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chanshige;
use Chanshige\Collection\CountryCode;
use Chanshige\Collection\Servers;
use Chanshige\Contracts\ResponseParserInterface;
use Chanshige\Contracts\WhoisInterface;
use Chanshige\Exception\InvalidQueryException;
use Chanshige\Handler\SocketInterface;
/**
* Class Whois
*
* @package Chanshige
*/
final class Whois implements WhoisInterface
{
/** @var string */
private const IANA_WHOIS_SERVER = 'whois.iana.org';
/** @var SocketInterface */
private $socket;
/** @var ResponseParserInterface */
private $response;
/**
* Whois constructor.
*
* @param SocketInterface $socket
* @param ResponseParserInterface $response
*/
public function __construct(
SocketInterface $socket,
ResponseParserInterface $response
) {
$this->socket = $socket;
$this->response = $response;
}
/**
* {@inheritdoc}
*/
public function query(string $domain, ?string $servername = null): WhoisInterface
{
$tld = get_tld($domain);
$servername = $servername ?: $this->findServerName($tld);
$response = $this->invoke($domain, $servername);
// not acquired
if ($response->isRegistered() === false) {
return $this;
}
if (CountryCode::existsValue($tld) || strlen($registrar = $response->servername()) === 0) {
return $this;
}
if ($servername === $registrar) {
return $this;
}
return $this->query($domain, $registrar);
}
/**
* {@inheritDoc}
*/
public function response(): ResponseParserInterface
{
return $this->response;
}
/**
* Find a whois servername from iana database.
*
* @param string $tld
* @return string
* @throws InvalidQueryException
*/
private function findServerName(string $tld): string
{
if (Servers::hasKey($tld)) {
return Servers::get($tld);
}
$servername = $this->invoke($tld, self::IANA_WHOIS_SERVER)->servername();
if (strlen($servername) > 0) {
return $servername;
}
throw new InvalidQueryException('Could not find to ' . $tld . ' whois server from iana database.');
}
/**
* Return a ResponseParser with whois result.
*
* @param string $domain
* @param string $servername
* @return ResponseParserInterface
*/
private function invoke(string $domain, string $servername)
{
$request = $this->socket->__invoke($servername, $domain);
$this->response = clone $this->response();
return ($this->response)($request->read());
}
}