35 lines
1.1 KiB
PHP
35 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Str;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class CorrelationId
|
|
{
|
|
/** @param Closure(Request): Response $next */
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$provided = $request->header('X-Correlation-ID');
|
|
$correlationId = is_string($provided) && Str::isUuid($provided)
|
|
? $provided
|
|
: (string) Str::uuid();
|
|
|
|
if ($provided !== null && ! Str::isUuid($provided)) {
|
|
return response()->json([
|
|
'message' => 'O identificador de correlação deve ser um UUID válido.',
|
|
'code' => 'invalid_correlation_id',
|
|
'correlation_id' => $correlationId,
|
|
], 422)->header('X-Correlation-ID', $correlationId);
|
|
}
|
|
|
|
$request->attributes->set('correlation_id', $correlationId);
|
|
$response = $next($request);
|
|
$response->headers->set('X-Correlation-ID', $correlationId);
|
|
|
|
return $response;
|
|
}
|
|
}
|