1
|
|
|
<?php |
2
|
|
|
namespace vipnytt\RobotsTxtParser\Client; |
3
|
|
|
|
4
|
|
|
use GuzzleHttp; |
5
|
|
|
use vipnytt\RobotsTxtParser\Parser\UrlParser; |
6
|
|
|
use vipnytt\RobotsTxtParser\RobotsTxtInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class Download |
10
|
|
|
* |
11
|
|
|
* @package vipnytt\RobotsTxtParser\Client |
12
|
|
|
*/ |
13
|
|
|
class Download implements RobotsTxtInterface |
14
|
|
|
{ |
15
|
|
|
use UrlParser; |
16
|
|
|
|
17
|
|
|
private $response; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Download constructor. |
21
|
|
|
* |
22
|
|
|
* @param string $url |
23
|
|
|
*/ |
24
|
|
|
public function __construct($url) |
25
|
|
|
{ |
26
|
|
|
$client = new GuzzleHttp\Client( |
27
|
|
|
[ |
28
|
|
|
'base_uri' => $this->urlBase($url), |
29
|
|
|
'max' => self::MAX_REDIRECTS, |
30
|
|
|
'http_errors' => false, |
31
|
|
|
] |
32
|
|
|
); |
33
|
|
|
$this->response = $client->request('GET', '/robots.txt'); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Status code |
38
|
|
|
* |
39
|
|
|
* @return int |
40
|
|
|
*/ |
41
|
|
|
public function getStatusCode() |
42
|
|
|
{ |
43
|
|
|
return $this->response->getStatusCode(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Encoding |
48
|
|
|
* |
49
|
|
|
* @return string |
50
|
|
|
*/ |
51
|
|
|
public function getEncoding() |
52
|
|
|
{ |
53
|
|
|
$header = $this->response->getHeader('content-type')[0]; |
54
|
|
|
$split = array_map('trim', mb_split(';', $header)); |
55
|
|
|
foreach ($split as $string) { |
56
|
|
|
if (mb_stripos($string, 'charset=') === 0) { |
57
|
|
|
return mb_split('=', $string, 2)[1]; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
return $this->detectEncoding(); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Manually detect encoding |
65
|
|
|
* |
66
|
|
|
* @return string |
67
|
|
|
*/ |
68
|
|
|
protected function detectEncoding() |
69
|
|
|
{ |
70
|
|
|
if (($encoding = mb_detect_encoding($this->getBody())) !== false) { |
71
|
|
|
return $encoding; |
72
|
|
|
} |
73
|
|
|
return self::ENCODING; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* URL content |
78
|
|
|
* |
79
|
|
|
* @return string |
80
|
|
|
*/ |
81
|
|
|
public function getBody() |
82
|
|
|
{ |
83
|
|
|
return $this->response->getBody()->getContents(); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|