1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Mikemirten\Component\JsonApi\HttpClient\Decorator; |
5
|
|
|
|
6
|
|
|
use Mikemirten\Component\JsonApi\HttpClient\Decorator\SymfonyEvent\RequestEvent; |
7
|
|
|
use Mikemirten\Component\JsonApi\HttpClient\Decorator\SymfonyEvent\ResponseEvent; |
8
|
|
|
use Mikemirten\Component\JsonApi\HttpClient\HttpClientInterface; |
9
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
10
|
|
|
use Psr\Http\Message\RequestInterface; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Events handling decorator based on the Symfony EventDispatcher component. |
15
|
|
|
* |
16
|
|
|
* @package Mikemirten\Component\JsonApi\HttpClient\Decorator |
17
|
|
|
*/ |
18
|
|
|
class SymfonyEventDispatcherDecorator implements HttpClientInterface |
|
|
|
|
19
|
|
|
{ |
20
|
|
|
const EVENT_REQUEST = 'mrtn_json_api.http_client.request'; |
21
|
|
|
const EVENT_RESPONSE = 'mrtn_json_api.http_client.response'; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* HTTP Client |
25
|
|
|
* |
26
|
|
|
* @var HttpClientInterface |
27
|
|
|
*/ |
28
|
|
|
protected $client; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var EventDispatcherInterface |
32
|
|
|
*/ |
33
|
|
|
protected $dispatcher; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* SymfonyEventDispatcherDecorator constructor. |
37
|
|
|
* |
38
|
|
|
* @param HttpClientInterface $client |
39
|
|
|
* @param EventDispatcherInterface $dispatcher |
40
|
|
|
*/ |
41
|
1 |
|
public function __construct(HttpClientInterface $client, EventDispatcherInterface $dispatcher) |
42
|
|
|
{ |
43
|
1 |
|
$this->client = $client; |
44
|
1 |
|
$this->dispatcher = $dispatcher; |
45
|
1 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* {@inheritdoc} |
49
|
|
|
*/ |
50
|
1 |
|
public function request(RequestInterface $request): ResponseInterface |
51
|
|
|
{ |
52
|
1 |
|
$requestEvent = new RequestEvent($request); |
53
|
1 |
|
$this->dispatcher->dispatch(self::EVENT_REQUEST, $requestEvent); |
54
|
|
|
|
55
|
1 |
|
$response = $this->client->request($requestEvent->getRequest()); |
56
|
|
|
|
57
|
1 |
|
$responseEvent = new ResponseEvent($response); |
58
|
1 |
|
$this->dispatcher->dispatch(self::EVENT_RESPONSE, $responseEvent); |
59
|
|
|
|
60
|
1 |
|
return $responseEvent->getResponse(); |
61
|
|
|
} |
62
|
|
|
} |