Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

62 строки
1.4KB

  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. protected bool $debug;
  10. public function __construct(Router $router, App $app, bool $debug = false)
  11. {
  12. $this->router = $router;
  13. $this->app = $app;
  14. $this->debug = $debug;
  15. }
  16. public function dispatch(Request $request): Response
  17. {
  18. Request::setCurrent($request);
  19. try {
  20. $route = $this->router->match($request->method(), $request->path());
  21. if (!$route) {
  22. return Response::notFound('Page not found.');
  23. }
  24. $result = $route->dispatch($this->app);
  25. return $this->normalizeResponse($result);
  26. } catch (Throwable $e) {
  27. if (!$this->debug) {
  28. error_log($e->getMessage());
  29. }
  30. $message = $this->debug ? $e->getMessage() : 'An unexpected error occurred.';
  31. return Response::serverError($message);
  32. } finally {
  33. Request::clearCurrent();
  34. }
  35. }
  36. protected function normalizeResponse(mixed $result): Response
  37. {
  38. if ($result instanceof Response) {
  39. return $result;
  40. }
  41. if (is_array($result)) {
  42. return Response::json($result);
  43. }
  44. return new Response((string) $result);
  45. }
  46. }

Powered by TurnKey Linux.