Skip to content

Instantly share code, notes, and snippets.

@Ghostscypher
Created September 17, 2021 17:37
Show Gist options
  • Save Ghostscypher/bcc0981fa8840eba55896c554eed60b0 to your computer and use it in GitHub Desktop.
Save Ghostscypher/bcc0981fa8840eba55896c554eed60b0 to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Middleware;
use App\Traits\LockEventTrait;
use Closure;
use Illuminate\Http\Request;
class LockRouteMiddleware
{
use LockEventTrait;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @param string $key
* @param int $seconds
* @param bool $unlock_after_request
* @param bool $unlock_on_error
* @return mixed
* @throws \Throwable
*/
public function handle(Request $request, Closure $next, string $key, int $seconds = 200,
bool $unlock_after_request = true, bool $unlock_on_error = true)
{
// Get unique key
$key = $this->getKey($key);
if($this->isLocked($key)) {
abort(419, 'Another request is being processed, please wait and try again in a few seconds.');
}
// Lock before executing the request
$this->lock($key, $seconds);
try{
$response = $next($request);
if($unlock_after_request){
$this->unlock($key);
}
return $response;
} catch (\Throwable $th){
if($unlock_on_error){
$this->unlock($key);
}
// Rethrow the error
throw $th;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment