Completed
Pull Request — master (#59)
by Rick
02:00
created

TgLog::downloadFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\TelegramAPI;
6
7
use Psr\Log\LoggerInterface;
8
use React\Promise\PromiseInterface;
9
use unreal4u\TelegramAPI\Abstracts\TelegramMethods;
10
use unreal4u\TelegramAPI\InternalFunctionality\DummyLogger;
11
use unreal4u\TelegramAPI\InternalFunctionality\PostOptionsConstructor;
12
use unreal4u\TelegramAPI\InternalFunctionality\TelegramDocument;
13
use unreal4u\TelegramAPI\InternalFunctionality\TelegramResponse;
14
use unreal4u\TelegramAPI\Telegram\Types\File;
15
16
/**
17
 * The main API which does it all
18
 */
19
class TgLog
20
{
21
    /**
22
     * @var RequestHandlerInterface
23
     */
24
    protected $requestHandler;
25
26
    /**
27
     * @var PostOptionsConstructor
28
     */
29
    protected $formConstructor;
30
31
    /**
32
     * Stores the token
33
     * @var string
34
     */
35
    private $botToken;
36
37
    /**
38
     * Contains an instance to a PSR-3 compatible logger
39
     * @var LoggerInterface
40
     */
41
    protected $logger;
42
43
    /**
44
     * Stores the API URL from Telegram
45
     * @var string
46
     */
47
    private $apiUrl = '';
48
49
    /**
50
     * @var string
51
     */
52
    protected $methodName = '';
53
54
    /**
55
     * TelegramLog constructor.
56
     *
57
     * @param string $botToken
58
     * @param RequestHandlerInterface $handler
59
     * @param LoggerInterface $logger
60
     */
61 40
    public function __construct(string $botToken, RequestHandlerInterface $handler, LoggerInterface $logger = null)
62
    {
63 40
        $this->botToken = $botToken;
64
65
        // Initialize new dummy logger (PSR-3 compatible) if not injected
66 40
        if ($logger === null) {
67 40
            $logger = new DummyLogger();
68
        }
69 40
        $this->logger = $logger;
70
71 40
        $this->requestHandler = $handler;
72 40
        $this->formConstructor = new PostOptionsConstructor();
73 40
        $this->apiUrl = 'https://api.telegram.org/bot' . $this->botToken . '/';
74 40
    }
75
76
    /**
77
     * @param TelegramMethods $method
78
     *
79
     * @return PromiseInterface
80
     */
81 31
    public function performApiRequest(TelegramMethods $method)
82
    {
83 31
        $this->logger->debug('Request for async API call, resetting internal values', [get_class($method)]);
84 31
        $this->resetObjectValues();
85 31
        $option = $this->formConstructor->constructOptions($method);
86 29
        return $this->sendRequestToTelegram($method, $option)
87
            ->then(function (TelegramResponse $response) use ($method) {
88 24
                return $method::bindToObject($response, $this->logger);
89 24
            });
90
    }
91
92
    /**
93
     * @param File $file
94
     *
95
     * @return PromiseInterface
96
     */
97
    public function downloadFile(File $file): PromiseInterface
98
    {
99
        $this->logger->debug('Downloading file async from Telegram, creating URL');
100
        $url = 'https://api.telegram.org/file/bot' . $this->botToken . '/' . $file->file_path;
101
        $this->logger->debug('About to perform request to begin downloading file');
102
103
        return $this->requestHandler->get($url)->then(
104
            function (TelegramResponse $rawData) {
105
                return new TelegramDocument($rawData);
106
            }
107
        );
108
    }
109
110
    /**
111
     * @param TelegramMethods $method
112
     * @param array $formData
113
     *
114
     * @return PromiseInterface
115
     */
116
    protected function sendRequestToTelegram(TelegramMethods $method, array $formData): PromiseInterface
117
    {
118
        $this->logger->debug('About to perform async HTTP call to Telegram\'s API');
119
        return $this->requestHandler->post($this->composeApiMethodUrl($method), $formData);
120
    }
121
122
    /**
123
     * Resets everything to the default values
124
     *
125
     * @return TgLog
126
     */
127 31
    private function resetObjectValues(): TgLog
128
    {
129 31
        $this->formConstructor->formType = 'application/x-www-form-urlencoded';
130 31
        return $this;
131
    }
132
133
    /**
134
     * Builds up the URL with which we can work with
135
     *
136
     * All methods in the Bot API are case-insensitive.
137
     * All queries must be made using UTF-8.
138
     *
139
     * @see https://core.telegram.org/bots/api#making-requests
140
     *
141
     * @param TelegramMethods $call
142
     * @return string
143
     */
144 30
    protected function composeApiMethodUrl(TelegramMethods $call): string
145
    {
146 30
        $completeClassName = get_class($call);
147 30
        $this->methodName = substr($completeClassName, strrpos($completeClassName, '\\') + 1);
148 30
        $this->logger->info('About to perform API request', ['method' => $this->methodName]);
149
150 30
        return $this->apiUrl . $this->methodName;
151
    }
152
}
153