-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.php
53 lines (45 loc) · 1.51 KB
/
Client.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
<?php
declare(strict_types=1);
namespace TypistTech\WordfenceApi;
use Generator;
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\TransferException;
use Psr\Http\Message\ResponseInterface;
use TypistTech\WordfenceApi\Exceptions\HttpException;
use TypistTech\WordfenceApi\Exceptions\InvalidJsonException;
readonly class Client
{
public function __construct(
private ClientInterface $http = new GuzzleHttpClient,
private RecordFactory $recordFactory = new RecordFactory,
) {}
/**
* @return Generator<Record>
*/
public function fetch(Feed $feed): Generator
{
$response = $this->get($feed);
// TODO: This is memory inefficient. We should decode from body stream. Help wanted!
$content = $response->getBody()->getContents();
if (! json_validate($content)) {
throw InvalidJsonException::forFeedResponse($feed);
}
$data = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
foreach ($data as $datum) {
$record = $this->recordFactory->make($datum);
if ($record !== null) {
yield $record;
}
}
}
private function get(Feed $feed): ResponseInterface
{
try {
return $this->http->get($feed->url());
} catch (TransferException $exception) {
// Guzzle throws exceptions for non-2xx responses.
throw HttpException::fromResponse($feed, $exception);
}
}
}