scramble icon indicating copy to clipboard operation
scramble copied to clipboard

ReflectionUnionType error

Open mikield opened this issue 2 years ago • 2 comments

Cannot generate docs if controller parameter is a union type.

In my project I have a union type for Report system, user can report a User, Comment or a Post. I have that solved with a type parameter in route, and creating a custom model binding in RouteServiceProvider.

Maybe I can somehow describe my types in doc-block above the method in controller? Cause it can be string (if that a User username) or a int (if else).

mikield avatar Sep 04 '23 13:09 mikield

Just to give more context - that's how I have that solved.

  1. RouteServiceProvider
Route::bind('reportable', function (string|int $id, \Illuminate\Routing\Route $route) {
            $type = $route->parameter('type');
            return match ($type) {
                'post' => Post::query()->find($id),
                'comment' => Comment::query()->find($id),
                'user' => User::query()->where('username', $id)->firstOrFail()
            };
        });
  1. Routes
$router->post('report/{type}/{reportable}', [RestrictionsController::class, 'report']);

To temporary get over api.json generation error, I localy added

->filter(fn(\ReflectionParameter $v) => !$v->getType() instanceof \ReflectionUnionType)

to RequestEssentialsExtension.php file (line 144)

mikield avatar Sep 04 '23 18:09 mikield

I have the same issue, it does look like it has something to do with double types of a variable on the controller.

If we have, in my case Route::get('subproducts/{pivotId}/{productId?}', [GeneralApiController::class, 'getSubProductByProductId']); and in the controller we put public function getSubProductByProductId(string|int $pivotId, string|null $productId) the "double typed" variables will throw an exception because they can be 2 types and don't have that function "getName" since they come from "ReflectionUnionType" and not the expected "ReflectionParameter".

The filter mentioned did fix the issue tho! Thanks!

alexandre433 avatar Apr 01 '24 18:04 alexandre433