Skip to content

Commit

Permalink
Refactor Idempotency middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
jewei committed Apr 26, 2024
1 parent 384631c commit a504ec1
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions app/Http/Middleware/Idempotency.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Symfony\Component\HttpFoundation\Response;

class Idempotency
{
Expand Down Expand Up @@ -50,7 +49,7 @@ class Idempotency
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): SymfonyResponse
public function handle(Request $request, Closure $next): Response
{
if (! $this->isIdempotentRequest($request) || empty($idempotenceKey = $this->getIdempotencyKey($request))) {
return $next($request);
Expand All @@ -64,19 +63,17 @@ public function handle(Request $request, Closure $next): SymfonyResponse

// If the response is already cached, return it.
if ($this->hasCache()) {
$cache = $this->getCache();

return response((string) $cache['content'], (int) $cache['status'], (array) $cache['headers'])
return response(...$this->getCache())
->header($this->idempotenceKey, $idempotenceKey)
->header($this->statusKey, 'HIT')
->header($this->replayKey, 'true');
}

// Store the response in cache.
$this->setCache([
'content' => $response->getContent(),
'status' => $response->getStatusCode(),
'headers' => $response->headers->all(),
'content' => (string) $response->getContent(),
'status' => (int) $response->getStatusCode(),
'headers' => (array) $response->headers->all(),
]);

$response->headers->set($this->idempotenceKey, $idempotenceKey);
Expand Down Expand Up @@ -105,7 +102,7 @@ protected function hasCache(): bool
*/
protected function getCache(): array
{
return (array) Cache::get($this->resolveCacheKey());
return Cache::get($this->resolveCacheKey());

Check failure on line 105 in app/Http/Middleware/Idempotency.php

View workflow job for this annotation

GitHub Actions / static-analysis

Method App\Http\Middleware\Idempotency::getCache() should return array but returns mixed.
}

/**
Expand Down

0 comments on commit a504ec1

Please sign in to comment.