diff --git a/composer.json b/composer.json index 084b89c..d9b95c9 100644 --- a/composer.json +++ b/composer.json @@ -27,6 +27,7 @@ "cache/array-adapter": "^1.0", "cache/chain-adapter": "^1.0", "cache/redis-adapter": "^1.0", + "doctrine/annotations": "^1.10", "duncan3dc/fork-helper": "^2.0", "friendsofphp/php-cs-fixer": "^2.0", "fzaninotto/faker": "^1.9", diff --git a/src/Annotations/Route.php b/src/Annotations/Route.php new file mode 100644 index 0000000..cff474c --- /dev/null +++ b/src/Annotations/Route.php @@ -0,0 +1,31 @@ +cachePoolChain = $cachePoolChain; } + public function loadRoutesFromAnnotations( + array $controllerPaths, + string $baseNamespace = null + ): void { + AnnotationRegistry::registerLoader('class_exists'); + + $reader = new AnnotationReader(); + + foreach ($controllerPaths as $controllerPath) { + foreach (new \RecursiveDirectoryIterator($controllerPath) as $controllerFile) { + if ($controllerFile->isDot() || !$controllerFile->isFile() || !$controllerFile->isReadable()) { + continue; + } + + $fileClassName = str_replace('.php', '', $controllerFile->getFilename()); + $expectedClasses = [ + $baseNamespace . '\\Controllers\\' . $fileClassName, + 'Benzine\\Controllers\\' . $fileClassName, + ]; + + foreach ($expectedClasses as $expectedClass) { + if (!class_exists($expectedClass)) { + continue; + } + + $rc = new \ReflectionClass($expectedClass); + if ($rc->isAbstract()) { + continue; + } + + foreach ($rc->getMethods() as $method) { + if (!$method->isPublic()) { + continue; + } + + $routeAnnotation = $reader->getMethodAnnotation($method, \Benzine\Annotations\Route::class); + if (!($routeAnnotation instanceof \Benzine\Annotations\Route)) { + continue; + } + + foreach($routeAnnotation->methods as $httpMethod) { + $newRoute = new Route($this->logger); + + $newRoute + ->setHttpMethod($httpMethod) + ->setRouterPattern('/' . ltrim($routeAnnotation->path, '/')) + ->setCallback($method->class . ':' . $method->name) + ->setWeight($routeAnnotation->weight); + + foreach ($routeAnnotation->domains as $domain) { + $newRoute->addValidDomain($domain); + } + + $this->addRoute($newRoute); + } + } + } + } + } + } + public function weighRoutes(): Router { $allocatedRoutes = [];