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.

54 line
1.1KB

  1. <?php
  2. declare(strict_types=1);
  3. namespace Core;
  4. use Throwable;
  5. class Dispatcher
  6. {
  7. protected Router $router;
  8. protected App $app;
  9. public function __construct(Router $router, App $app)
  10. {
  11. $this->router = $router;
  12. $this->app = $app;
  13. }
  14. public function dispatch(Request $request): Response
  15. {
  16. Request::setCurrent($request);
  17. try {
  18. $route = $this->router->match($request->method(), $request->path());
  19. if (!$route) {
  20. return Response::notFound('Page not found.');
  21. }
  22. $result = $route->dispatch($this->app);
  23. return $this->normalizeResponse($result);
  24. } catch (Throwable $e) {
  25. return Response::serverError($e->getMessage());
  26. } finally {
  27. Request::clearCurrent();
  28. }
  29. }
  30. protected function normalizeResponse(mixed $result): Response
  31. {
  32. if ($result instanceof Response) {
  33. return $result;
  34. }
  35. if (is_array($result)) {
  36. return Response::json($result);
  37. }
  38. return new Response((string) $result);
  39. }
  40. }

Powered by TurnKey Linux.