psalm / psalm-plugin-doctrine

Stubs to let Psalm understand Doctrine better
86 stars 44 forks source link

Support reduced type inferring from Collection::reduce #154

Open laurentmuller opened 1 month ago

laurentmuller commented 1 month ago

Plugin should add capability to infer reduced type from Collection::reduce based on assertions in a callback, similarly as Psalm currently does for array_reduce.

This is the the same as #58.

This is the current annotation: https://github.com/doctrine/collections/blob/b1f7c33ebb2d73a4860d6b65a11b9662b9904ebd/src/ReadableCollection.php#L241

For example, the following code must not raise any error:

class Item {
    public float $value = 0.0;
}

/** 
 * @param Collection<array-key, Item> $collection
 */
function foo(Collection $collection): float {
    return $collection->reduce(
        fn (float $carry, Item $item): float => $carry + $item->value,
        0.0
    );
}

See example: https://psalm.dev/r/80735e2f8d

The Collections.phpstub file must updated to reflect changes.

psalm-github-bot[bot] commented 1 month ago

I found these snippets:

https://psalm.dev/r/80735e2f8d ```php $collection */ function foo(Collection $collection): float { return $collection->reduce( fn (float $carry, Item $item): float => $carry + $item->value, 0.0 ); } ``` ``` Psalm output (using commit 16b24bd): No issues! ```
laurentmuller commented 1 month ago

It's correct. But no definition exist for the reduce() function in the collections stub.