|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace BramR\TorExits\Collector; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
|
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
7
|
|
|
use Psr\Log\LoggerAwareInterface; |
|
8
|
|
|
use Psr\Log\LoggerAwareTrait; |
|
9
|
|
|
use Psr\Log\LoggerInterface; |
|
10
|
|
|
use Psr\Log\NullLogger; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Class Collector |
|
14
|
|
|
*/ |
|
15
|
|
|
class Collector implements CollectorInterface |
|
16
|
|
|
{ |
|
17
|
|
|
use LoggerAwareTrait; |
|
18
|
|
|
|
|
19
|
|
|
protected $client; |
|
20
|
|
|
protected $location; |
|
21
|
|
|
|
|
22
|
10 |
|
public function __construct(Client $client = null) |
|
23
|
|
|
{ |
|
24
|
10 |
|
$this->client = is_null($client) ? new Client() : $client; |
|
25
|
10 |
|
$this->setLogger(new NullLogger()); |
|
26
|
10 |
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Getter for location |
|
30
|
|
|
* |
|
31
|
|
|
* return string |
|
32
|
|
|
*/ |
|
33
|
6 |
|
public function getLocation() |
|
34
|
|
|
{ |
|
35
|
6 |
|
return $this->location; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Setter for location |
|
40
|
|
|
* |
|
41
|
|
|
* @param string $location |
|
42
|
|
|
* @return Collector |
|
43
|
|
|
*/ |
|
44
|
6 |
|
public function setLocation($location) |
|
45
|
|
|
{ |
|
46
|
6 |
|
$this->location = $location; |
|
47
|
6 |
|
return $this; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* fetch |
|
52
|
|
|
* @return \PSR\Http\Message\StreamInterface $tordata | null |
|
53
|
|
|
*/ |
|
54
|
4 |
|
public function fetch() |
|
55
|
|
|
{ |
|
56
|
4 |
|
if ($this->getLocation()) { |
|
57
|
|
|
try { |
|
58
|
3 |
|
$response = $this->client->request('GET', $this->getLocation(), ['stream' => true]); |
|
59
|
3 |
|
if ($response instanceof ResponseInterface) { |
|
60
|
2 |
|
if ($response->getStatusCode() === 200) { |
|
61
|
1 |
|
return $response->getBody(); |
|
62
|
|
|
} else { |
|
63
|
1 |
|
throw new CollectorFetchException( |
|
64
|
1 |
|
'Failed fetching with response status code: '.$response->getStatusCode() |
|
65
|
1 |
|
); |
|
66
|
|
|
} |
|
67
|
|
|
} else { |
|
68
|
|
|
//Should always return a response, better be safe |
|
69
|
2 |
|
throw new CollectorFetchException('Failed without response.'); |
|
70
|
|
|
} |
|
71
|
2 |
|
} catch (\Exception $e) { |
|
72
|
2 |
|
$this->logger->error('Failed fetching response, error: ' . $e->getMessage()); |
|
73
|
2 |
|
throw $e; |
|
74
|
|
|
} |
|
75
|
|
|
} else { |
|
76
|
1 |
|
$this->logger->error('Tried to fetch data from empty location.'); |
|
77
|
|
|
} |
|
78
|
1 |
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|