-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConfiguration.php
More file actions
292 lines (235 loc) · 7.12 KB
/
Copy pathConfiguration.php
File metadata and controls
292 lines (235 loc) · 7.12 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
<?php
declare(strict_types=1);
namespace AvitoAds;
use AvitoAds\Auth\Credentials;
use AvitoAds\Auth\Storage\TokenStorageInterface;
use AvitoAds\Exception\ConfigurationException;
use Psr\Log\LoggerInterface;
use Psr\SimpleCache\CacheInterface;
/**
* Конфигурация клиента Авито Реклама.
*
* Содержит учётные данные, идентификатор аккаунта (токен всегда привязан к одному
* аккаунту), выбор окружения (прод/песочница), таймауты, параметры повторов,
* логгер и кэш для хранения токена.
*
* Объект иммутабельный: методы `with*()` возвращают новый экземпляр.
*/
final class Configuration
{
public const ENV_PRODUCTION = 'production';
public const ENV_SANDBOX = 'sandbox';
private const HOST = 'https://api.avito.ru';
private const PREFIX_PRODUCTION = 'ads';
private const PREFIX_SANDBOX = 'ads-sandbox';
/** @var Credentials */
private $credentials;
/** @var int Идентификатор рекламного аккаунта (path-параметр accountID). */
private $accountId;
/** @var string */
private $environment = self::ENV_PRODUCTION;
/** @var float Таймаут запроса в секундах. */
private $timeout = 30.0;
/** @var float Таймаут соединения в секундах. */
private $connectTimeout = 10.0;
/** @var int Максимум повторов при 429/5xx/сетевых ошибках. */
private $maxRetries = 4;
/** @var int Базовая задержка повтора в миллисекундах. */
private $retryBaseDelayMs = 1000;
/** @var int Запас в секундах для досрочного обновления токена. */
private $tokenLeeway = 60;
/** @var LoggerInterface|null */
private $logger;
/** @var CacheInterface|null PSR-16 кэш для хранения токена между запросами. */
private $cache;
/** @var TokenStorageInterface|null Явное хранилище токена (приоритетнее cache). */
private $tokenStorage;
/** @var callable|null Кастомный Guzzle-handler (для тестов/моков). */
private $httpHandler;
public function __construct(Credentials $credentials, int $accountId)
{
if ($accountId <= 0) {
throw new ConfigurationException('accountID должен быть положительным целым числом.');
}
$this->credentials = $credentials;
$this->accountId = $accountId;
}
/**
* Быстрое создание конфигурации.
*/
public static function create(string $clientId, string $clientSecret, int $accountId): self
{
return new self(new Credentials($clientId, $clientSecret), $accountId);
}
/**
* @return static
*/
public function production(): self
{
$clone = clone $this;
$clone->environment = self::ENV_PRODUCTION;
return $clone;
}
/**
* @return static
*/
public function sandbox(): self
{
$clone = clone $this;
$clone->environment = self::ENV_SANDBOX;
return $clone;
}
/**
* @return static
*/
public function withTimeout(float $seconds): self
{
$clone = clone $this;
$clone->timeout = $seconds;
return $clone;
}
/**
* @return static
*/
public function withConnectTimeout(float $seconds): self
{
$clone = clone $this;
$clone->connectTimeout = $seconds;
return $clone;
}
/**
* @return static
*/
public function withMaxRetries(int $maxRetries): self
{
$clone = clone $this;
$clone->maxRetries = max(0, $maxRetries);
return $clone;
}
/**
* @return static
*/
public function withRetryBaseDelay(int $milliseconds): self
{
$clone = clone $this;
$clone->retryBaseDelayMs = max(0, $milliseconds);
return $clone;
}
/**
* @return static
*/
public function withTokenLeeway(int $seconds): self
{
$clone = clone $this;
$clone->tokenLeeway = max(0, $seconds);
return $clone;
}
/**
* @return static
*/
public function withLogger(LoggerInterface $logger): self
{
$clone = clone $this;
$clone->logger = $logger;
return $clone;
}
/**
* @return static
*/
public function withCache(CacheInterface $cache): self
{
$clone = clone $this;
$clone->cache = $cache;
return $clone;
}
/**
* @return static
*/
public function withTokenStorage(TokenStorageInterface $storage): self
{
$clone = clone $this;
$clone->tokenStorage = $storage;
return $clone;
}
/**
* Подменяет Guzzle-handler (например, MockHandler в тестах).
*
* @return static
*/
public function withHttpHandler(callable $handler): self
{
$clone = clone $this;
$clone->httpHandler = $handler;
return $clone;
}
public function getCredentials(): Credentials
{
return $this->credentials;
}
public function getAccountId(): int
{
return $this->accountId;
}
public function getEnvironment(): string
{
return $this->environment;
}
public function isSandbox(): bool
{
return $this->environment === self::ENV_SANDBOX;
}
/**
* Базовый URL API с учётом окружения, со слэшем на конце.
*
* Прод: https://api.avito.ru/ads/
* Песочница: https://api.avito.ru/ads-sandbox/
*/
public function getBaseUri(): string
{
$prefix = $this->isSandbox() ? self::PREFIX_SANDBOX : self::PREFIX_PRODUCTION;
return self::HOST . '/' . $prefix . '/';
}
/**
* URL эндпоинта получения токена (не зависит от окружения).
*/
public function getTokenUrl(): string
{
return self::HOST . '/token';
}
public function getTimeout(): float
{
return $this->timeout;
}
public function getConnectTimeout(): float
{
return $this->connectTimeout;
}
public function getMaxRetries(): int
{
return $this->maxRetries;
}
public function getRetryBaseDelayMs(): int
{
return $this->retryBaseDelayMs;
}
public function getTokenLeeway(): int
{
return $this->tokenLeeway;
}
public function getLogger(): ?LoggerInterface
{
return $this->logger;
}
public function getCache(): ?CacheInterface
{
return $this->cache;
}
public function getTokenStorage(): ?TokenStorageInterface
{
return $this->tokenStorage;
}
public function getHttpHandler(): ?callable
{
return $this->httpHandler;
}
}