FileDownloader   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 26
c 1
b 0
f 0
dl 0
loc 35
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A downloadFile() 0 32 3
1
<?php
2
3
4
namespace Sysbot\Telegram\Helpers;
5
6
7
use GuzzleHttp\Client;
8
use GuzzleHttp\Exception\RequestException;
9
use GuzzleHttp\Promise\PromiseInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Sysbot\Telegram\Exceptions\TelegramAPIException;
12
use Sysbot\Telegram\Exceptions\TelegramBadRequestException;
13
use Sysbot\Telegram\Exceptions\TelegramForbiddenException;
14
use Sysbot\Telegram\Exceptions\TelegramNotFoundException;
15
use Sysbot\Telegram\Exceptions\TelegramUnauthorizedException;
16
17
trait FileDownloader
18
{
19
20
    public function downloadFile(string $remotePath): PromiseInterface
21
    {
22
        /** @var Client $client */
23
        $client = $this->client;
24
        $uri = sprintf('/file/bot%s/%s', $this->token, $remotePath);
25
        return $client->getAsync($uri)->then(
26
            function (ResponseInterface $response) {
27
                return $response->getBody();
28
            },
29
            function (RequestException $e) {
30
                $message = sprintf(
31
                    'An unknown error occurred when trying to fetch the file (%s): %s',
32
                    $e->getCode(),
33
                    $e->getMessage()
34
                );
35
                if (!$e->hasResponse()) {
36
                    throw new TelegramAPIException($message);
37
                }
38
                $data = json_decode($e->getResponse()?->getBody());
39
                if (empty($data)) {
40
                    throw new TelegramAPIException($message);
41
                }
42
                match ($data->error_code) {
43
                    400 => throw new TelegramBadRequestException($data->description),
44
                    401 => throw new TelegramUnauthorizedException('Token invalid or expired'),
45
                    403 => throw new TelegramForbiddenException($data->description),
46
                    404 => throw new TelegramNotFoundException($data->description),
47
                    default => throw new TelegramAPIException(
48
                        sprintf(
49
                            'Telegram API returned an error (%s): %s',
50
                            $data->error_code ?? 'Unknown',
51
                            $data->description ?? 'Unknown'
52
                        )
53
                    )
54
                };
55
            }
56
        );
57
    }
58
59
}