-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathDownloader.php
More file actions
79 lines (67 loc) · 2.4 KB
/
Downloader.php
File metadata and controls
79 lines (67 loc) · 2.4 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
<?php
declare(strict_types = 1);
namespace FioApi\Download;
use FioApi\Download\Entity\TransactionList;
use FioApi\Exceptions\InternalErrorException;
use FioApi\Exceptions\TooGreedyException;
use FioApi\Transferrer;
use GuzzleHttp\ClientInterface;
use Psr\Http\Message\ResponseInterface;
class Downloader extends Transferrer
{
public function __construct(
string $token,
ClientInterface $client = null
) {
parent::__construct($token, $client);
}
public function downloadFromTo(\DateTimeInterface $from, \DateTimeInterface $to): TransactionList
{
$url = $this->urlBuilder->buildPeriodsUrl($from, $to);
return $this->downloadTransactionsList($url);
}
public function downloadSince(\DateTimeInterface $since): TransactionList
{
return $this->downloadFromTo($since, new \DateTimeImmutable());
}
public function downloadLast(): TransactionList
{
$url = $this->urlBuilder->buildLastUrl();
return $this->downloadTransactionsList($url);
}
public function setLastId(string $id): void
{
$client = $this->getClient();
$url = $this->urlBuilder->buildSetLastIdUrl($id);
try {
$client->request('get', $url, ['verify' => $this->getCertificatePath()]);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
$this->handleException($e);
}
}
private function downloadTransactionsList(string $url): TransactionList
{
$client = $this->getClient();
try {
/** @var ResponseInterface $response */
$response = $client->request('get', $url, ['verify' => $this->getCertificatePath()]);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
$this->handleException($e);
}
return TransactionList::create(json_decode($response->getBody()->getContents())->accountStatement);
}
private function handleException(\GuzzleHttp\Exception\BadResponseException $e): void
{
if ($e->getCode() == 409) {
throw new TooGreedyException('You can use one token for API call every 30 seconds', $e->getCode(), $e);
}
if ($e->getCode() == 500) {
throw new InternalErrorException(
'Server returned 500 Internal Error (probably invalid token?)',
$e->getCode(),
$e
);
}
throw $e;
}
}