-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathHttpReader.php
More file actions
109 lines (92 loc) · 2.28 KB
/
Copy pathHttpReader.php
File metadata and controls
109 lines (92 loc) · 2.28 KB
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
<?php
namespace Dusterio\LinkPreview\Readers;
use Dusterio\LinkPreview\Contracts\LinkInterface;
use Dusterio\LinkPreview\Contracts\ReaderInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Exception\ConnectException;
/**
* Class HttpReader
*/
class HttpReader implements ReaderInterface
{
/**
* @var Client $client
*/
private $client;
/**
* @var array $config
*/
private $config;
/**
* @var CookieJar $jar
*/
private $jar;
/**
* HttpReader constructor.
* @param array|null $config
*/
public function __construct($config = null)
{
$this->jar = new CookieJar();
$this->config = $config ?: [
'allow_redirects' => ['max' => 10],
'cookies' => $this->jar,
'connect_timeout' => 5
];
$this->config['headers']['User-Agent'] = 'Mozilla/5.0';
}
/**
* @param int $timeout
*/
public function setTimeout($timeout)
{
$this->config(['connect_timeout' => $timeout]);
}
/**
* @param array $parameters
*/
public function config(array $parameters)
{
foreach ($parameters as $key => $value) {
$this->config[$key] = $value;
}
}
/**
* @return Client
*/
public function getClient()
{
if (!$this->client) {
$this->client = new Client();
}
return $this->client;
}
/**
* @param Client $client
*/
public function setClient($client)
{
$this->client = $client;
}
/**
* @inheritdoc
*/
public function readLink(LinkInterface $link)
{
$client = $this->getClient();
try {
$response = $client->request('GET', $link->getUrl(), array_merge($this->config, [
'on_stats' => function (TransferStats $stats) use (&$link) {
$link->setEffectiveUrl($stats->getEffectiveUri());
}
]));
$link->setContent($response->getBody())
->setContentType($response->getHeader('Content-Type')[0]);
} catch (ConnectException $e) {
$link->setContent(false)->setContentType(false);
}
return $link;
}
}