Skip to content

Fix assertNotContains() narrowing a Traversable haystack to never - #372

Open
APX403 wants to merge 1 commit into
phpstan:2.1.xfrom
APX403:fix-assert-not-contains-traversable
Open

APX403 wants to merge 1 commit into
phpstan:2.1.xfrom
APX403:fix-assert-not-contains-traversable

Conversation

@APX403

@APX403 APX403 commented Nov 29, 2026

Copy link
Copy Markdown

assertNotContains() and assertNotContainsEquals() turn a Traversable haystack into *NEVER*, so the next use of the same expression is reported. With a Doctrine collection:

self::assertNotContains($tag, $post->getTags());
self::assertCount(0, $post->getTags());

PHPStan 2.3.7 with phpstan-phpunit 2.1.4 reports on the second line:

Call to static method PHPUnit\Framework\Assert::assertCount() with 0 and *NEVER* will always evaluate to false.

The Contains and ContainsEquals resolvers build $haystack instanceof Traversable || in_array(...), so that only arrays are narrowed. For the negated assertions, createExpression() wraps the whole expression in BooleanNot, which turns the guard into "the haystack is not Traversable" and removes every Traversable type from the haystack. This has been the case since #191; #197 stopped the report on the assertion call itself, but not the narrowing.

NotContains and NotContainsEquals now have their own resolvers that keep the guard and negate only the in_array() call, and createExpression() uses such a Not resolver when one exists. The existing NotCount resolver becomes reachable through the same lookup. It builds the same expression as the generic negation, so assertNotCount() does not change.

Fixes #262

The Contains and ContainsEquals resolvers accept any Traversable
haystack and only narrow arrays. Negating the whole expression for
assertNotContains() and assertNotContainsEquals() turned that guard into
"the haystack is not Traversable", so a Doctrine collection or an
ArrayObject became *NEVER* after the assertion.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

assertNotContains appears to be messing something up.

1 participant