Skip to content

Commit

Permalink
Merge pull request #25 from 27pchrisl/fix-union-types
Browse files Browse the repository at this point in the history
Fix issue where union typed parameters caused discovery errors
  • Loading branch information
freekmurze authored Dec 6, 2022
2 parents 0d06237 + c979417 commit 77b9d67
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/PendingRoutes/PendingRouteAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Support\Str;
use ReflectionAttribute;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionParameter;
use Spatie\RouteDiscovery\Attributes\DiscoveryAttribute;
use Spatie\RouteDiscovery\Attributes\Route;
Expand Down Expand Up @@ -50,8 +51,8 @@ public function relativeUri(): string
{
/** @var ReflectionParameter $modelParameter */
$modelParameter = collect($this->method->getParameters())->first(function (ReflectionParameter $parameter) {
/** @phpstan-ignore-next-line */
return is_a($parameter->getType()?->getName(), Model::class, true);
$type = $parameter->getType();
return $type instanceof ReflectionNamedType && is_a($type->getName(), Model::class, true);
});

$uri = '';
Expand Down
17 changes: 17 additions & 0 deletions tests/DiscoverControllersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use Spatie\RouteDiscovery\Discovery\Discover;
use Spatie\RouteDiscovery\Tests\Support\TestClasses\Controllers\CustomMethod\CustomMethodController;
use Spatie\RouteDiscovery\Tests\Support\TestClasses\Controllers\DefaultController\ControllerThatExtendsDefaultController;
use Spatie\RouteDiscovery\Tests\Support\TestClasses\Controllers\UsesUnionTypes\UnionController;
use Spatie\RouteDiscovery\Tests\Support\TestClasses\Controllers\Single\MyController;

it('can discover controller in a directory', function () {
Expand Down Expand Up @@ -67,3 +68,19 @@
uri: 'my-prefix/my',
);
});

it('can handle a union parameter', function() {
Discover::controllers()
->useRootNamespace('Spatie\RouteDiscovery\Tests\\')
->useBasePath($this->getTestPath())
->in(controllersPath('UsesUnionTypes'));

$this
->assertRegisteredRoutesCount(1)
->assertRouteRegistered(
UnionController::class,
controllerMethod: 'example',
uri: 'union/example',
);
});

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Spatie\RouteDiscovery\Tests\Support\TestClasses\Controllers\UsesUnionTypes;

use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;

class UnionController
{
public function example(Redirector|RedirectResponse $example): Redirector|RedirectResponse
{
return $example;
}
}

0 comments on commit 77b9d67

Please sign in to comment.