diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3939724 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +/.phpunit.cache +/vendor +composer.phar +composer.lock +.DS_Store +Thumbs.db +/phpunit.xml +/.idea +/.fleet +/.vscode +.phpunit.result.cache diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 0000000..68b67c7 --- /dev/null +++ b/.styleci.yml @@ -0,0 +1,4 @@ +php: + preset: laravel + version: 0.1 + diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d99a131 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +All notable changes to `laravel-otp` will be documented in this file + +## 0.0.1 - 201X-XX-XX + +- initial release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b4ae1c4 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code +held within. They make the code freely available in the hope that it will be of use to other developers. It would be +extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the +world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient +quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open +source projects are used by many developers, who may have entirely different needs to your own. Think about +whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +If the project maintainer has any additional requirements, you will find them listed here. + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..e5af579 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Mustafa Khaled + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..6bcf975 --- /dev/null +++ b/README.md @@ -0,0 +1,142 @@ +# Laravel Fast-API + +[![Latest Version](https://img.shields.io/github/v/release/mustafakhaleddev/laravel-fast-api.svg?style=flat-square)](https://github.com/mustafakhaleddev/laravel-fast-api/releases) +[![Issues](https://img.shields.io/github/issues/mustafakhaleddev/laravel-fast-api.svg?style=flat-square)](https://github.com/mustafakhaleddev/laravel-fast-api/issues) +[![License](https://img.shields.io/github/license/mustafakhaleddev/laravel-fast-api.svg?style=flat-square)](https://github.com/mustafakhaleddev/laravel-fast-api/blob/main/LICENSE) + +Laravel FastAPI is a PHP attribute-based routing solution for building APIs quickly and efficiently. With FastAPI attributes, you can define routes, methods, and middlewares directly in your controller classes, reducing the need for complex route files and enabling better organization and clarity. + +This package also integrates seamlessly with Laravel's `route:cache` for enhanced performance, ensuring your APIs are as fast as possible. + +## Features + +- **Attribute-Based Routing**: Define your API routes using PHP attributes. +- **Support for Advanced Routing Options**: Middleware, where clauses, route options, and more! +- **Enum-Based HTTP Methods**: Use the predefined `FastApiMethod` for your HTTP methods. +- **API Caching**: Leverage Laravel's `route:cache` for optimal performance. +- **Clear API Cache**: Quickly clear cached API routes with simple Artisan commands. + +## Installation + +You can install the package via Composer: + +```bash +composer require mkd/laravel-fast-api +``` + +## Usage + +### Define FastAPI Routes + +Use the `#[FastAPIGroup]` and `#[FastAPI]` attributes to define routes inside your controller classes. + +```php +use MKD\FastAPI\Attributes\FastAPI; +use MKD\FastAPI\Attributes\FastAPIGroup; + +#[FastAPIGroup(prefix: '/items', options: ['name' => 'items'], middlewares: ['auth'])] +class ItemsController extends Controller +{ + #[FastAPI(method: FastApiMethod::GET, path: '/data/{id}', options: ['functions' => [ + 'whereIn' => ['id', ['2']], + ], 'name' => 'item_id'])] + public function getItem($id) + { + return response()->json(['item' => $id]); + } +} +``` + +This simple attribute-based approach automatically handles routing logic, allowing you to focus on building your API logic. + +### Supported Methods and Functions + +You can define routes with the following HTTP methods: + +```php +enum FastApiMethod +{ + case GET; + case POST; + case PUT; + case PATCH; + case OPTION; + case DELETE; + case ANY; + case REDIRECT; + case MATCH; +} +``` + +In addition, you can leverage these functions to customize your routes: + +```php +private array $supportedFunctions = [ + 'middleware', + 'where', + 'whereNumber', + 'whereAlpha', + 'whereAlphaNumeric', + 'whereUuid', + 'whereUlid', + 'whereIn', + 'name', + 'withTrashed', + 'scopeBindings', + 'withoutScopedBindings', +]; +``` + +### Configurations + +In your configuration file, you can specify paths and controllers to be scanned for FastAPI attributes. + +```php +return [ + //Paths to check for controllers that use fast-api + 'paths' => [ + app_path('Http/Controllers'), + ], + + //Specify controllers that are not included in the paths + 'controllers' => [ + \App\Http\Controllers\CustomController::class + ], +]; +``` + +### Artisan Commands + +FastAPI provides useful commands for caching and clearing controllers: + +- Cache the controllers for better scanning performance: + + ```bash + php artisan fast-api:cache + ``` + +- Clear the cached controllers: + + ```bash + php artisan fast-api:clear-cache + ``` + +### Performance + +By using Laravel's `route:cache`, the FastAPI routes are cached to ensure high performance. It is recommended to always cache your routes in production environments for faster API responses. + +```bash +php artisan route:cache +``` + +## Contributing + +Feel free to submit issues and pull requests. Contributions are welcome! + +## License + +The MIT License (MIT). Please see [License File](LICENSE) for more information. + +--- + +This `README.md` gives a clear overview of your package's purpose, usage, features, and installation steps, ensuring potential users and contributors understand it quickly. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..9fa7446 --- /dev/null +++ b/composer.json @@ -0,0 +1,48 @@ +{ + "name": "mkd/laravel-fast-api", + "description": "Laravel package for generating and verifying One-Time Passwords (OTPs) using TOTP (Time-based One-Time Password) and HOTP (HMAC-based One-Time Password) algorithms.", + "keywords": [ + "laravel" + + ], + "homepage": "https://github.com/mustafakhaleddev/laravel-fast-api", + "license": "MIT", + "type": "library", + "authors": [ + { + "name": "Mustafa Khaled", + "email": "mustafakhaled.dev@gmail.com", + "role": "Developer" + } + ], + "require": { + "php": "^8.0", + "laravel/framework": "^7.0|^8.0|^9.0|^10.0|^11.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.5" + }, + "autoload": { + "psr-4": { + "MKD\\FastAPI\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "MKD\\FastAPI\\": "tests/" + } + }, + "config": { + "sort-packages": true + }, + "extra": { + "laravel": { + "providers": [ + "MKD\\FastAPI\\LaravelFastAPIServiceProvider" + ], + "aliases": { + + } + } + } +} diff --git a/config/config.php b/config/config.php new file mode 100644 index 0000000..ebb4216 --- /dev/null +++ b/config/config.php @@ -0,0 +1,19 @@ + [ + app_path('Http/Controllers'), + ], + + //specify controllers that not included on the paths + 'controllers' => [ + \App\Http\Controllers\CustomController::class + ], +]; diff --git a/src/Attributes/FastAPI.php b/src/Attributes/FastAPI.php new file mode 100644 index 0000000..bcd3b63 --- /dev/null +++ b/src/Attributes/FastAPI.php @@ -0,0 +1,27 @@ +method = $method; + $this->path = $path; + $this->options = $options; + } + + public function setGroup(FastAPIGroup $group){ + $this->group = $group; + } + +} diff --git a/src/Attributes/FastAPIGroup.php b/src/Attributes/FastAPIGroup.php new file mode 100644 index 0000000..ad77e50 --- /dev/null +++ b/src/Attributes/FastAPIGroup.php @@ -0,0 +1,22 @@ +prefix = $prefix; + $this->middlewares = $middlewares; + $this->options = $options; + } + +} diff --git a/src/Enums/FastApiMethod.php b/src/Enums/FastApiMethod.php new file mode 100644 index 0000000..319f219 --- /dev/null +++ b/src/Enums/FastApiMethod.php @@ -0,0 +1,18 @@ +getControllers()); + // Define controllers to scan for route groups + $controllers = $this->getControllers(); + + foreach ($controllers as $controller) { + $reflectionClass = new \ReflectionClass($controller); + + // Check if the class has the RouteGroup attribute + $groupAttributes = $reflectionClass->getAttributes(FastAPIGroup::class); + + if (count($groupAttributes) > 0) { + // Create an instance of the RouteGroup attribute + $groupAttribute = $groupAttributes[0]->newInstance(); + + $this->registerGroup($groupAttribute, $reflectionClass, $controller); + + } else { + $this->registerMethods($reflectionClass, $controller); + } + } + } + + private function registerGroup(FastAPIGroup $groupAttribute, \ReflectionClass $reflectionClass, string $controller): void + { + // Define the route group with prefix, middleware, and options + Route::group([ + 'prefix' => $groupAttribute->prefix, + 'middleware' => $groupAttribute->middlewares, + ...$groupAttribute->options // Spread operator to merge additional options + ], function () use ($reflectionClass, $controller, $groupAttribute) { + $this->registerMethods($reflectionClass, $controller, $groupAttribute); + }); + } + + private function registerMethods(\ReflectionClass $reflectionClass, string $controller, FastAPIGroup $group = null): void + { + foreach ($reflectionClass->getMethods() as $method) { + $this->registerMethod($method, $controller, $group); + } + } + + private function registerMethod(\ReflectionMethod $method, string $controller, FastAPIGroup $group = null): void + { + foreach ($method->getAttributes(FastAPI::class) as $routeAttribute) { + // Create an instance of the FastAPI attribute + $route = $routeAttribute->newInstance(); + $routeRegister = false; + // Register the route dynamically within the group + if ($route->method == FastApiMethod::REDIRECT) { + if (isset($route->options['to'])) { + $routeRegister = Route::redirect($route->path, $route->options['to'], $route->options['code'] ?? 301); + } + } elseif ($route->method == FastApiMethod::MATCH) { + if (isset($route->options['methods'])) { + $routeRegister = Route::match($route->options['methods'], $route->path, [$controller, $method->getName()]); + } + + } else { + $routeRegister = Route::{$route->method->name}($route->path, [$controller, $method->getName()]); + } + + if ($routeRegister) { + if (isset($route->options['middleware'])) { + $routeRegister->middleware($route->options['middleware']); + } + + if (isset($route->options['name'])) { + $routeName = $route->options['name']; + if ($group != null && isset($group->options['name'])) { + $routeName = $group->options['name'] . '.' . $routeName; + } + $routeRegister->name($routeName); + } + + if (isset($route->options['functions']) && is_array($route->options['functions'])) { + foreach ($route->options['functions'] as $functionName => $parameters) { + if ($this->supportedFunction($functionName)) { + $routeRegister->{$functionName}(...$parameters ?? []); + } + } + } + } + + } + } + + final public function getControllers(bool $cache = true): array + { + if (Cache::has('fast-api-controllers') && $cache) { + return Cache::get('fast-api-controllers'); + } + + $controllersPaths = config('fast-api.paths', []); + $fastAPIControllers = []; + + foreach ($controllersPaths as $path) { + $controllers = File::allFiles($path); + foreach ($controllers as $controller) { + $filePath = $controller->getRealPath(); + $fileContents = File::get($filePath); + + + // Search for the usage of MKD\FastAPI\Attributes\FastAPI + if (strpos($fileContents, 'MKD\\FastAPI\\Attributes\\FastAPI') !== false) { + // Extract namespace + $namespace = $this->getNamespace($fileContents); + + // Get the class name from the file path + $className = $namespace . '\\' . $controller->getBasename('.php'); + $fastAPIControllers[] = $className; + } + } + + } + + return array_unique(array_merge($fastAPIControllers, config('fast-api.controllers', []))); + } + + private function getNamespace($fileContents): string + { + // Match the namespace declaration + if (preg_match('/namespace\s+([^\s;]+);/', $fileContents, $matches)) { + return trim($matches[1]); + } + return 'App\\Http\\Controllers'; // Default namespace if none is found + } + + private function supportedFunction(string $functionName): bool + { + return in_array($functionName, $this->supportedFunctions); + } +} diff --git a/src/LaravelFastAPIServiceProvider.php b/src/LaravelFastAPIServiceProvider.php new file mode 100644 index 0000000..60147dd --- /dev/null +++ b/src/LaravelFastAPIServiceProvider.php @@ -0,0 +1,42 @@ +app->runningInConsole()) { + $this->publishes([ + __DIR__ . '/../config/config.php' => config_path('fast-api.php'), + ], 'config'); + } + (new FastAPIService())->registerRoutes(); + + + $this->commands([ + FastAPICacheCommand::class, + FastAPIClearCacheCommand::class, + ]); + } + + public function register() + { + // Automatically apply the package configuration + $this->mergeConfigFrom(__DIR__ . '/../config/config.php', 'fast-api'); + + } + +} diff --git a/src/commands/FastAPICacheCommand.php b/src/commands/FastAPICacheCommand.php new file mode 100644 index 0000000..0c5a20a --- /dev/null +++ b/src/commands/FastAPICacheCommand.php @@ -0,0 +1,28 @@ +getControllers()); + $this->info('FastAPI Controllers cached successfully!'); + + } +} diff --git a/src/commands/FastAPIClearCacheCommand.php b/src/commands/FastAPIClearCacheCommand.php new file mode 100644 index 0000000..9f5a888 --- /dev/null +++ b/src/commands/FastAPIClearCacheCommand.php @@ -0,0 +1,25 @@ +info('FastAPI routes cache cleared!'); + } +}