psalm icon indicating copy to clipboard operation
psalm copied to clipboard

alter and InvalidFalsableReturnType can generate invalid PHP code

Open mttsch opened this issue 5 months ago • 1 comments

Consider the following code example

https://psalm.dev/r/1a9d2da1dd

which is a minimal reproducer based on https://github.com/symfony/symfony/blob/53e759a7dabe8aab882bb159548b24c868dbaf89/src/Symfony/Component/Form/FormErrorIterator.php.

Run ./vendor/bin/psalm --alter --issues=InvalidFalsableReturnType, which results in the following diff:

@@ -23,9 +23,11 @@ class PsalmTestIterator {
     /**
      * Returns the current element of the iterator.
      *
-     * @return T
+     * @return PsalmTest|self|false
+     *
+     * @psalm-return T|false
      */
-    public function current(): PsalmTest|self
+    public function current()|self
     {
         return current($this->tests);
     }

As you can see, the method signature becomes invalid: current()|self

mttsch avatar Aug 01 '25 17:08 mttsch

I found these snippets:

https://psalm.dev/r/1a9d2da1dd
<?php

class PsalmTest {}

/**
 * @template T of PsalmTest|PsalmTestIterator
 */
class PsalmTestIterator {
    /**
     * @var list<T>
     */
    private array $tests;

    /**
     * @param list<T> $tests
     */
    public function __construct(
        array $tests,
    ) {
        $this->tests = $tests;
    }

    /**
     * Returns the current element of the iterator.
     *
     * @return T
     */
    public function current(): PsalmTest|self
    {
        return current($this->tests);
    }
}
Psalm output (using commit cdceda0):

No issues!

psalm-github-bot[bot] avatar Aug 01 '25 17:08 psalm-github-bot[bot]