1 | <?php |
||
12 | class Uuid |
||
13 | { |
||
14 | use Utils\AttributeTrait; |
||
15 | |||
16 | const KEY = 'UUID'; |
||
17 | |||
18 | /** |
||
19 | * @var string|false The header name to use |
||
20 | */ |
||
21 | private $header = 'X-Uuid'; |
||
22 | |||
23 | /** |
||
24 | * @var array The version and arguments needed to generate the Uuid |
||
25 | */ |
||
26 | private $version = [1]; |
||
27 | |||
28 | /** |
||
29 | * Returns the Uuid instance. |
||
30 | * |
||
31 | * @param ServerRequestInterface $request |
||
32 | * |
||
33 | * @return \Ramsey\Uuid\Uuid|null |
||
34 | */ |
||
35 | public static function getUuid(ServerRequestInterface $request) |
||
39 | |||
40 | /** |
||
41 | * Constructor. Set the version of UUID. |
||
42 | * |
||
43 | * @param int|null $version |
||
44 | */ |
||
45 | public function __construct($version = null) |
||
51 | |||
52 | /** |
||
53 | * Choose the Uuid version. |
||
54 | * |
||
55 | * @param int $version 1, 3, 4 or 5 |
||
56 | * |
||
57 | * @return self |
||
58 | */ |
||
59 | public function version($version) |
||
69 | |||
70 | /** |
||
71 | * Set whether the Uuid is stored in the header. |
||
72 | * Set false to do not store. |
||
73 | * |
||
74 | * @param false|string $header |
||
75 | * |
||
76 | * @return self |
||
77 | */ |
||
78 | public function header($header) |
||
84 | |||
85 | /** |
||
86 | * Execute the middleware. |
||
87 | * |
||
88 | * @param ServerRequestInterface $request |
||
89 | * @param ResponseInterface $response |
||
90 | * @param callable $next |
||
91 | * |
||
92 | * @return ResponseInterface |
||
93 | */ |
||
94 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
95 | { |
||
96 | $uuid = $this->generateUuid(); |
||
97 | |||
98 | $request = self::setAttribute($request, self::KEY, $uuid); |
||
99 | |||
100 | if (empty($this->header)) { |
||
101 | return $next($request, $response); |
||
102 | } |
||
103 | |||
104 | $request = $request->withHeader($this->header, (string) $uuid); |
||
105 | |||
106 | return $next($request, $response)->withHeader($this->header, (string) $uuid); |
||
107 | } |
||
108 | |||
109 | /** |
||
110 | * Generate the uuid with the current configuration. |
||
111 | * |
||
112 | * @return string |
||
113 | */ |
||
114 | private function generateUuid() |
||
121 | } |
||
122 |