update project
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Domain\SchoolCore\Context\SchoolContext;
|
||||
use App\Domain\SchoolCore\Context\SchoolContextException;
|
||||
use App\Domain\SchoolCore\Context\SchoolContextResolver;
|
||||
use App\Domain\SchoolCore\Context\SchoolContextStore;
|
||||
use App\Domain\SchoolCore\Context\SchoolContextValidator;
|
||||
use Closure;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class ResolveSchoolContext
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolContextResolver $resolver,
|
||||
private readonly SchoolContextValidator $validator,
|
||||
private readonly SchoolContextStore $store,
|
||||
) {
|
||||
}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
try {
|
||||
$context = $this->resolver->resolve($request);
|
||||
$this->validator->assertValid($context, $request->user());
|
||||
$this->store->set($context);
|
||||
$request->attributes->set(SchoolContext::class, $context);
|
||||
|
||||
return $next($request);
|
||||
} catch (SchoolContextException $exception) {
|
||||
return new JsonResponse([
|
||||
'message' => $exception->getMessage(),
|
||||
], $this->statusCodeFor($exception));
|
||||
} finally {
|
||||
// Avoid context bleeding in long-running workers such as Octane.
|
||||
$this->store->forget();
|
||||
}
|
||||
}
|
||||
|
||||
private function statusCodeFor(SchoolContextException $exception): int
|
||||
{
|
||||
$code = $exception->getCode();
|
||||
|
||||
return in_array($code, [401, 403, 422, 500], true) ? $code : 422;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user