/
EventClient.php
40 lines (33 loc) · 1.37 KB
/
EventClient.php
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
<?php declare(strict_types=1);
namespace StrictPhp\HttpClients\Clients\Event;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use StrictPhp\HttpClients\Clients\Event\Entities\HttpStateEntity;
use StrictPhp\HttpClients\Clients\Event\Events\BeforeRequestEvent;
use StrictPhp\HttpClients\Clients\Event\Events\FailedRequestEvent;
use StrictPhp\HttpClients\Clients\Event\Events\SuccessRequestEvent;
use Throwable;
final class EventClient implements ClientInterface
{
public function __construct(
private readonly ClientInterface $client,
private readonly EventDispatcherInterface $eventDispatcher,
) {
}
public function sendRequest(RequestInterface $request): ResponseInterface
{
$httpState = new HttpStateEntity($request);
$this->eventDispatcher->dispatch(new BeforeRequestEvent($httpState));
try {
$response = $this->client->sendRequest($request);
} catch (Throwable $throwable) {
$this->eventDispatcher->dispatch(new FailedRequestEvent($httpState->finish(), $throwable));
throw $throwable;
}
// keep out of try-catch block
$this->eventDispatcher->dispatch(new SuccessRequestEvent($httpState->finish(), $response));
return $response;
}
}