Route.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace Src;
  3. use Error;
  4. class Route
  5. {
  6. private static array $routes = [];
  7. private static string $prefix = '';
  8. public static function setPrefix($value)
  9. {
  10. self::$prefix = $value;
  11. }
  12. public static function add(string $route, array $action): void
  13. {
  14. if (!array_key_exists($route, self::$routes)) {
  15. self::$routes[$route] = $action;
  16. }
  17. }
  18. public function start(): void
  19. {
  20. $path = explode('?', $_SERVER['REQUEST_URI'])[0];
  21. $path = substr($path, strlen(self::$prefix) + 1);
  22. if (!array_key_exists($path, self::$routes)) {
  23. throw new Error('Path does not exist');
  24. }
  25. $class = self::$routes[$path][0];
  26. $action = self::$routes[$path][1];
  27. if (!class_exists($class)) {
  28. throw new Error('Class does not exist');
  29. }
  30. if (!method_exists($class, $action)) {
  31. throw new Error('Method does not exist');
  32. }
  33. call_user_func([new $class, $action], new Request());
  34. }
  35. }