Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positive: RedundantCondition - $foo is not in-array-Foo has already been asserted #7416

Open
BenMorel opened this issue Jan 17, 2022 · 3 comments
Labels

Comments

@BenMorel
Copy link
Contributor

Checking in_array() twice on two different arrays produces a wrong RedundantCondition error:

class User {}

interface UserRepository {
    /**
     * @return User[]
     */
    public function findBy(array $criteria): array;
}

function test(User $user, UserRepository $userRepository): void {
    $a = $userRepository->findBy(['foo' => 1]);
    $b = $userRepository->findBy(['bar' => 2]);

    if (!in_array($user, $a, true) && !in_array($user, $b, true)) {
        throw new Exception();
    }
}

ERROR: RedundantCondition - 16:9 - $user is not in-array-User has already been asserted

https://psalm.dev/r/6d5c4d5b60

Notes:

  • using a single !in_array() works fine
  • using in_array() without strict: true works fine
@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/6d5c4d5b60
<?php

class User {}

interface UserRepository {
    /**
     * @return User[]
     */
    public function findBy(array $criteria): array;
}

function test(User $user, UserRepository $userRepository): void {
    $a = $userRepository->findBy(['foo' => 1]);
    $b = $userRepository->findBy(['bar' => 2]);

    if (!in_array($user, $a, true) && !in_array($user, $b, true)) {
        throw new Exception();
    }
}
Psalm output (using commit e1d2da7):

ERROR: RedundantCondition - 16:9 - $user is not in-array-User has already been asserted

@orklah orklah added the bug label Jan 17, 2022
@orklah
Copy link
Collaborator

orklah commented Jan 17, 2022

has already been asserted errors should probably be disabled on in-array- assertions.

It's useful to know for example that $a is in an array that contains only strings (because we can infer $a is a string). However, checking that it's in another array containing other strings is not redundant

@orklah
Copy link
Collaborator

orklah commented Jan 17, 2022

This error is handled in AlgebraAnalyzer, which is a pretty generic piece of code except for this ugly thing:

if (preg_match('@^!?in-array-@', $possibility)) {

I really want to wait for #7410 to fix that properly... I'll see

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants