You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.7KB

  1. <?php
  2. declare(strict_types=1);
  3. namespace Core;
  4. use Core\Auth\AuthMiddleware;
  5. use Throwable;
  6. class Dispatcher
  7. {
  8. protected Router $router;
  9. protected App $app;
  10. public function __construct(Router $router, App $app)
  11. {
  12. $this->router = $router;
  13. $this->app = $app;
  14. }
  15. public function dispatch(Request $request): Response
  16. {
  17. Request::setCurrent($request);
  18. try {
  19. $route = $this->router->match($request->method(), $request->path());
  20. if (!$route) {
  21. return Response::notFound('Page not found.');
  22. }
  23. if ($route->getMiddleware() !== null) {
  24. $early = $this->runMiddleware($route->getMiddleware(), $request, $route->getRequiredPermission());
  25. if ($early !== null) {
  26. return $early;
  27. }
  28. }
  29. $result = $route->dispatch($this->app);
  30. return $this->normalizeResponse($result);
  31. } catch (Throwable $e) {
  32. return Response::serverError($e->getMessage());
  33. } finally {
  34. Request::clearCurrent();
  35. }
  36. }
  37. protected function runMiddleware(string $name, Request $request, ?string $permission): ?Response
  38. {
  39. return match ($name) {
  40. 'auth' => (new AuthMiddleware())->handle($request, $permission),
  41. default => null,
  42. };
  43. }
  44. protected function normalizeResponse(mixed $result): Response
  45. {
  46. if ($result instanceof Response) {
  47. return $result;
  48. }
  49. if (is_array($result)) {
  50. return Response::json($result);
  51. }
  52. return new Response((string) $result);
  53. }
  54. }

Powered by TurnKey Linux.