Skip to content

[Bug]: toArray() on a mapped collection breaks inference #1125

Description

@rossbearman

What happened?

We have a large number of resources that include data that is mapped over a collection. Due to reasons lost to time, the resulting Collection is cast to an array before being returned, with toArray().

If this happens directly in the Resource's toArray() method, Scramble infers it as a string. If the mapping happens in a separate method which type hints the array return, it's inferred as an array with no defined properties.

We're just going to work through the codebase and remove all the toArray() castings, as they're unnecessary, but I thought this report might help identify an issue in the inference engine, as the type data is all there in the AST.

How to reproduce the bug

class ProductEditResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'variations' => $this->variations->map(function (Variation $variation) {
                return [
                    'id' => $variation->id,
                    'name' => $variation->name,
                    'product_variation_id' => $variation->pivot->id,
                ];
           })->toArray(),
        ];
    }
}

This returns the following in the schema:

"variations": {
  "type": "string"
}

If I extract the map into a method with an array return type:

class ProductEditResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'variations' => $this->variations(),
        ];
    }

    private function variations(): array
    {
        return $this->variations->map(function (Variation $variation) {
            return [
                'id' => $variation->id,
                'name' => $variation->name,
                'product_variation_id' => $variation->pivot->id,
            ];
        })->toArray(),
    }
}

It gets rendered as this in the schema:

"variations": {
  "type": "array",
  "items": {}
}

If the toArray() is dropped from the map, it correctly infers the shape of the data.

Package Version

0.13.17

PHP Version

8.4

Laravel Version

10

Which operating systems does with happen with?

Linux

Notes

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions