Skip to content

Commit

Permalink
feat: preparing for new version with full Laravel 10 and Livewire sup…
Browse files Browse the repository at this point in the history
…port
  • Loading branch information
izniburak committed Nov 10, 2023
1 parent 4a556f1 commit b38eb1e
Show file tree
Hide file tree
Showing 8 changed files with 106 additions and 91 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
/node_modules
/vendor
.phpunit.result.cache
.phpunit.cache/
composer.lock
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@ Automatically Route Generator & Discovery Package for Laravel.
- AJAX supported HTTP Methods (XMLHttpRequest)
- Custom patterns for parameters with Regex
- kebab-case and snake_case supported URLs
- Livewire routes support [included Volt] _(in v2.x)_

## Install

*Supported Laravel Versions:* **>= 6.x**
Supported Laravel Versions:
- v2.x: Laravel 10 and later
- v1.x: Laravel 6 and later

Run the following command directly in your Project path:
```
Expand All @@ -32,7 +35,7 @@ $ composer require izniburak/laravel-auto-routes
```json
{
"require": {
"izniburak/laravel-auto-routes": "^1.0"
"izniburak/laravel-auto-routes": "^2.0"
}
}
```
Expand Down Expand Up @@ -65,10 +68,11 @@ All methods will be automatically generated by the AutoRoute Package.
* change main method.


- You can use `AutoRouteFacade` in `web.php` and `api.php` in order to simple code completion for the method while using an IDE or Editor.
You can add the following line to top of the file:
- You can use `Buki\AutoRoute\Facades\Route` in `web.php` and `api.php` in order to simple code completion for the method while using an IDE or Editor.
You can add/replace the following line to top of the file:
```php
use Buki\AutoRoute\AutoRouteFacade as Route;
// use Illuminate\Support\Facades\Route;
use Buki\AutoRoute\Facades\Route;
```
- All methods which will be auto generated must have `public` accessor to discovered by the **AutoRoute** Package.

Expand Down Expand Up @@ -358,5 +362,5 @@ You can use Issues
- [izniburak](https://github.com/izniburak) İzni Burak Demirtaş - creator, maintainer

[mit-url]: http://opensource.org/licenses/MIT
[author-url]: http://burakdemirtas.org
[author-url]: https://buki.dev
[twitter-url]: https://twitter.com/izniburak
8 changes: 4 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@
{
"name": "İzni Burak Demirtaş",
"email": "[email protected]",
"homepage": "https://burakdemirtas.org"
"homepage": "https://buki.dev"
}
],
"require": {
"php": "^7.2.5|^8.0.2"
"php": "^8.1"
},
"require-dev": {
"illuminate/routing": "^8.0",
"phpunit/phpunit": "^8.5 || ^9.4"
"illuminate/routing": "^10.0",
"phpunit/phpunit": "^10.1"
},
"autoload": {
"psr-4": {
Expand Down
32 changes: 12 additions & 20 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,22 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Laravel Auto Routes Tests">
<directory>tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="vendor/autoload.php" backupGlobals="false" colors="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<coverage/>
<testsuites>
<testsuite name="Laravel Auto Routes Tests">
<directory>tests/</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">src/</directory>
</include>
</source>
</phpunit>
102 changes: 60 additions & 42 deletions src/AutoRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,40 +10,33 @@
use ReflectionClass;
use ReflectionMethod;

// for Livewire support
use Livewire\{Volt\Volt, Component};

/**
* Class AutoRoute
*
* @package Buki\AutoRoute
* @author İzni Burak Demirtaş <info@burakdemirtasorg>
* @author İzni Burak Demirtaş <[email protected]>
* @web https://buki.dev
*/
class AutoRoute
{
/** @var Container */
protected $app;

/** @var Router */
protected $router;
protected Router $router;

/** @var string */
protected $namespace;
protected string $namespace;

/** @var string[] Laravel Routing Available Methods. */
protected $availableMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
protected array $availableMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];

/** @var string[] Custom methods for the package */
protected $customMethods = ['XGET', 'XPOST', 'XPUT', 'XPATCH', 'XDELETE', 'XOPTIONS', 'XANY'];
protected array $customMethods = ['XGET', 'XPOST', 'XPUT', 'XPATCH', 'XDELETE', 'XOPTIONS', 'XANY', 'VOLT', 'WIRE'];

/** @var string Main Method */
protected $mainMethod;
protected string $mainMethod;

/** @var string */
protected $defaultHttpMethods;
protected string|array $defaultHttpMethods;

/** @var string Ajax Middleware class for the Requests */
protected $ajaxMiddleware;
protected string $ajaxMiddleware;

/** @var string[] */
protected $defaultPatterns = [
protected array $defaultPatterns = [
':any' => '([^/]+)',
':int' => '(\d+)',
':float' => '[+-]?([0-9]*[.])?[0-9]+',
Expand All @@ -54,9 +47,8 @@ class AutoRoute
* AutoRoute constructor.
* @throws
*/
public function __construct(Container $app)
public function __construct(protected Container $app)
{
$this->app = $app;
$this->router = $app->get('router');
}

Expand Down Expand Up @@ -103,7 +95,7 @@ function () use ($controller, $only, $except, $patterns) {
if (in_array($method->class, [BaseController::class, "{$this->namespace}\\Controller"])
|| $method->getDeclaringClass()->getParentClass()->getName() === BaseController::class
|| !$method->isPublic()
|| strpos($method->name, '__') === 0) {
|| str_starts_with($method->name, '__')) {
continue;
}

Expand All @@ -116,46 +108,72 @@ function () use ($controller, $only, $except, $patterns) {
}

// Find the HTTP method which will be used and method name.
[$httpMethods, $methodName, $middleware] = $this->getHttpMethodAndName($methodName);
[$httpMethods, $path, $middleware] = $this->getHttpMethodAndName($methodName);

// Get endpoints and parameter patterns for Route
[$endpoints, $routePatterns] = $this->getRouteValues($method, $patterns);

$endpoints = implode('/', $endpoints);
$this->router->addRoute(
array_map(function ($method) {
return strtoupper($method);
}, $httpMethods),
($methodName !== $this->mainMethod ? $methodName : '') . "/{$endpoints}",
[$classRef->getName(), $method->name]
)->where($routePatterns)->name("{$method->name}")->middleware($middleware);

$handler = [$classRef->getName(), $method->name];
$routePath = ($path !== $this->mainMethod ? $path : '') . "/{$endpoints}";

// for volt
if (str_starts_with($method->name, 'volt')) {
if (class_exists(Volt::class) && $method->getReturnType()?->getName() === 'string') {
Volt::route($routePath, $method->invoke(new ($classRef->getName())))
->where($routePatterns)->name("{$method->name}")->middleware($middleware);
}

continue;
}

// for livewire
if (str_starts_with($method->name, 'wire')) {
if (!(class_exists(Component::class) && $method->getReturnType()?->getName() === 'string')) {
continue;
}

$handler = $method->invoke(new ($classRef->getName()));

if (!is_subclass_of($handler, Component::class)) {
continue;
}
}

$this->router
->addRoute(array_map(fn ($method) => strtoupper($method), $httpMethods), $routePath, $handler)
->where($routePatterns)->name("{$method->name}")->middleware($middleware);
}
}
);
}

private function getHttpMethodAndName(string $methodName): array
private function getHttpMethodAndName(string $controllerMethod): array
{
$httpMethods = $this->defaultHttpMethods;
$middleware = null;
foreach (array_merge($this->availableMethods, $this->customMethods) as $httpMethod) {
$httpMethod = strtolower($httpMethod);
if (stripos($methodName, $httpMethod, 0) === 0) {
if ($httpMethod !== 'xany') {
$httpMethods = [ltrim($httpMethod, 'x')];
foreach (array_merge($this->availableMethods, $this->customMethods) as $method) {
$method = strtolower($method);
if (stripos($controllerMethod, $method, 0) === 0) {
if (in_array($method, ['volt', 'wire'])) {
$httpMethods = ['GET', 'HEAD'];
} elseif ($method !== 'xany') {
$httpMethods = [ltrim($method, 'x')];
}
$middleware = strpos($httpMethod, 'x') === 0 ? $this->ajaxMiddleware : null;
$methodName = lcfirst(
preg_replace('/' . $httpMethod . '_?/i', '', $methodName, 1)

$middleware = str_starts_with($method, 'x') ? $this->ajaxMiddleware : null;
$controllerMethod = lcfirst(
preg_replace('/' . $method . '_?/i', '', $controllerMethod, 1)
);
break;
}
}

// Convert URL from camelCase to snake-case.
$methodName = strtolower(preg_replace('%([a-z]|[0-9])([A-Z])%', '\1-\2', $methodName));
$controllerMethod = strtolower(preg_replace('%([a-z]|[0-9])([A-Z])%', '\1-\2', $controllerMethod));

return [$httpMethods, $methodName, $middleware];
return [$httpMethods, $controllerMethod, $middleware];
}

private function getRouteValues(ReflectionMethod $method, array $patterns = []): array
Expand Down
15 changes: 0 additions & 15 deletions src/AutoRouteFacade.php

This file was deleted.

8 changes: 4 additions & 4 deletions src/AutoRouteServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* Class AutoRouteServiceProvider
*
* @package Buki\AutoRoute
* @author İzni Burak Demirtaş <info@burakdemirtasorg>
* @author İzni Burak Demirtaş <info@burakdemirtas.org>
*/
class AutoRouteServiceProvider extends ServiceProvider
{
Expand All @@ -18,7 +18,7 @@ class AutoRouteServiceProvider extends ServiceProvider
*
* @return void
*/
public function boot()
public function boot(): void
{
$this->publishes([
$this->configPath() => config_path('auto-route.php'),
Expand All @@ -30,7 +30,7 @@ public function boot()
*
* @return void
*/
public function register()
public function register(): void
{
$this->mergeConfigFrom($this->configPath(), 'auto-route');
$this->app->singleton(AutoRoute::class, function ($app) {
Expand Down Expand Up @@ -60,7 +60,7 @@ protected function configPath(): string
*
* @return array
*/
public function provides()
public function provides(): array
{
return [AutoRoute::class];
}
Expand Down
15 changes: 15 additions & 0 deletions src/Facades/Route.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Buki\AutoRoute\Facades;

/**
* Class Route
*
* @package Buki\AutoRoute
* @author İzni Burak Demirtaş <[email protected]>
*
* @method static void auto(string $prefix, string $controller, array $options = [])
*/
class Route extends \Illuminate\Support\Facades\Route
{
}

0 comments on commit b38eb1e

Please sign in to comment.