-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathSendsRequests.php
More file actions
81 lines (64 loc) · 2.31 KB
/
SendsRequests.php
File metadata and controls
81 lines (64 loc) · 2.31 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
<?php
namespace Mollie\Api\Traits;
use Mollie\Api\Contracts\RetryStrategyContract;
use Mollie\Api\Exceptions\LogicException;
use Mollie\Api\Exceptions\MollieException;
use Mollie\Api\Exceptions\RetryableNetworkRequestException;
use Mollie\Api\Http\LinearRetryStrategy;
use Mollie\Api\Http\PendingRequest;
use Mollie\Api\Http\Request;
use Mollie\Api\MollieApiClient;
use Mollie\Api\Utils\DataTransformer;
/**
* @mixin MollieApiClient
*/
trait SendsRequests
{
/**
* Strategy that defines retry behavior.
*/
protected RetryStrategyContract $retryStrategy;
protected function initializeSendsRequests(): void
{
$this->retryStrategy = $this->retryStrategy ?? new LinearRetryStrategy();
}
/**
* Set a custom retry strategy implementation.
*/
public function setRetryStrategy(RetryStrategyContract $strategy): self
{
$this->retryStrategy = $strategy;
return $this;
}
/**
* @return mixed
*/
public function send(Request $request)
{
$pendingRequest = new PendingRequest($this, $request);
$pendingRequest = $pendingRequest->executeRequestHandlers();
$pendingRequest = (new DataTransformer)->transform($pendingRequest);
$lastException = null;
for ($attempt = 0; $attempt <= $this->retryStrategy->maxRetries(); $attempt++) {
if ($attempt > 0) {
$delayMs = $this->retryStrategy->delayBeforeAttemptMs($attempt);
usleep($delayMs * 1000);
}
try {
$response = $this->httpClient->sendRequest($pendingRequest);
return $pendingRequest->executeResponseHandlers($response);
} catch (RetryableNetworkRequestException $e) {
$lastException = $e;
} catch (MollieException $exception) {
$exception = $pendingRequest->executeFatalHandlers($exception);
throw $exception;
}
}
if ($lastException instanceof MollieException) {
$lastException = $pendingRequest->executeFatalHandlers($lastException);
throw $lastException;
}
// This should be unreachable, but keep a safe fallback for static analysis
throw new LogicException('Request failed after retries without a final exception.');
}
}