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
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 thearrayreturn, 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
This returns the following in the schema:
If I extract the map into a method with an
arrayreturn type:It gets rendered as this in the schema:
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