|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Pachico\SlimCorrelationId\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use \Pachico\SlimCorrelationId\Generator; |
|
6
|
|
|
use \Pachico\SlimCorrelationId\Model; |
|
7
|
|
|
use \Psr\Http\Message; |
|
8
|
|
|
|
|
9
|
|
|
class CorrelationId |
|
10
|
|
|
{ |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @var callable |
|
14
|
|
|
*/ |
|
15
|
|
|
private $callable; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var array |
|
19
|
|
|
*/ |
|
20
|
|
|
private $settings; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var Generator\IdInterface |
|
24
|
|
|
*/ |
|
25
|
|
|
private $idGenerator; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @param array $settings |
|
29
|
|
|
* @param callable $callable Which will be called as soon as the correlation id is resolved |
|
30
|
|
|
* @param Generator\IdInterface $idGenerator |
|
31
|
|
|
*/ |
|
32
|
|
|
public function __construct( |
|
33
|
|
|
array $settings = [], |
|
34
|
|
|
callable $callable = null, |
|
35
|
|
|
Generator\IdInterface $idGenerator = null |
|
36
|
|
|
) { |
|
37
|
|
|
$this->settings = array_merge([ |
|
38
|
|
|
'header_key' => Model\CorrelationId::DEFAULT_HEADER_KEY |
|
39
|
|
|
], $settings); |
|
40
|
|
|
|
|
41
|
|
|
$this->callable = $callable; |
|
42
|
|
|
$this->idGenerator = $idGenerator ?: new Generator\Simple(); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @param Message\RequestInterface $request |
|
47
|
|
|
* @param Message\ResponseInterface $response |
|
48
|
|
|
* @param callable $next |
|
49
|
|
|
* |
|
50
|
|
|
* @return Message\ResponseInterface |
|
51
|
|
|
*/ |
|
52
|
|
|
public function __invoke(Message\RequestInterface $request, Message\ResponseInterface $response, callable $next) |
|
53
|
|
|
{ |
|
54
|
|
|
$correlationId = $this->resolveCorrelationId($request); |
|
55
|
|
|
if ($this->callable) { |
|
56
|
|
|
call_user_func_array($this->callable, [$correlationId]); |
|
57
|
|
|
} |
|
58
|
|
|
$requestWithHeader = $request->withHeader($this->settings['header_key'], (string) $correlationId); |
|
59
|
|
|
$pipeThroughResponse = $next($requestWithHeader, $response); |
|
60
|
|
|
$responseWithHeader = $pipeThroughResponse->withHeader($this->settings['header_key'], (string) $correlationId); |
|
61
|
|
|
|
|
62
|
|
|
return $responseWithHeader; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @param \Psr\Http\Message\RequestInterface $request |
|
67
|
|
|
* |
|
68
|
|
|
* @return Model\IdInterface |
|
69
|
|
|
*/ |
|
70
|
|
|
private function resolveCorrelationId(Message\RequestInterface $request) |
|
71
|
|
|
{ |
|
72
|
|
|
$headerLine = $request->getHeaderLine($this->settings['header_key']); |
|
73
|
|
|
|
|
74
|
|
|
if (!empty($headerLine)) { |
|
75
|
|
|
return new Model\CorrelationId($headerLine); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
return Model\CorrelationId::create($this->idGenerator); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|