diff --git a/src/RouterRegistry.php b/src/RouterRegistry.php index fbe9a48..c49cca4 100644 --- a/src/RouterRegistry.php +++ b/src/RouterRegistry.php @@ -11,6 +11,10 @@ class RouterRegistry protected $files = []; + public $routes = []; + + private $_routes = []; + public function __construct( protected Router $router ) { @@ -89,37 +93,57 @@ function recursiveGlob($directory, $pattern) return $files; } - function autoload($namespace = null) + function loadUserFunctions() { - $namespace = str_replace('/','\\', $namespace); // Extract routes from functions $functionRoutes = $this->extractRoutesFromFunctions(); foreach ($functionRoutes as $route) { - $this->router->{$route['method']}($route['pattern'], $route['callback']); + $this->_routes[] = $route; + $this->routes[] = "\$router->{$route['method']}('{$route['pattern']}', '{$route['callback']}');"; } - + } + + function autoload($namespace = null) + { + $namespace = str_replace('/', '\\', $namespace); // Extract routes from classes $declaredClasses = get_declared_classes(); foreach ($declaredClasses as $class) { if (strpos($class, $namespace) === 0) { $classRoutes = $this->extractRoutesFromClass($class); foreach ($classRoutes as $route) { - $this->router->{$route['method']}($route['pattern'], $route['callback']); + $this->_routes[] = $route; + $this->routes[] = "\$router->{$route['method']}('{$route['pattern']}', '{$route['callback']}');"; } } } return $this; } - function add($class) + function addClass($class) { // Extract routes from class $classRoutes = $this->extractRoutesFromClass($class); foreach ($classRoutes as $route) { - $this->router->{$route['method']}($route['pattern'], $route['callback']); + $this->_routes[] = $route; + $this->routes[] = "\$router->{$route['method']}('{$route['pattern']}', '{$route['callback']}');"; } return $this; } + + function addFunction($function) + { + $reflectionFunction = new ReflectionFunction($function); + $docComment = $reflectionFunction->getDocComment(); + if ($docComment) { + $routeInfo = $this->parseRouteAnnotation($docComment); + if ($routeInfo) { + $route = ['method' => $routeInfo['method'], 'pattern' => $routeInfo['pattern'], 'callback' => $function]; + $this->_routes[] = $route; + $this->routes[] = "\$router->{$route['method']}('{$route['pattern']}', '{$route['callback']}');"; + } + } + } function loadFrom($entry, $namespace = null) { @@ -150,4 +174,15 @@ protected function loadFile($file) $this->files[$file] = true; return $this; } + + public function run() { + foreach($this->_routes as $route) { + $this->router->{$route['method']}($route['pattern'], $route['callback']); + } + } + + public function save($filePath = 'routes.php') { + $routerClassName = get_class($this->router); + file_put_contents($filePath, "routes)); + } }