Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -1581,6 +1581,12 @@ parameters:
count: 1
path: src/Type/Php/FunctionExistsFunctionTypeSpecifyingExtension.php

-
rawMessage: 'Doing instanceof PHPStan\Type\Constant\ConstantArrayType is error-prone and deprecated. Use Type::getConstantArrays() instead.'
identifier: phpstanApi.instanceofType
count: 1
path: src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php

-
rawMessage: 'Doing instanceof PHPStan\Type\Constant\ConstantStringType is error-prone and deprecated. Use Type::getConstantStrings() instead.'
identifier: phpstanApi.instanceofType
Expand Down
81 changes: 70 additions & 11 deletions src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\FunctionTypeSpecifyingExtension;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function count;
use function strtolower;
Expand Down Expand Up @@ -113,25 +115,18 @@
}

$specifiedTypes = new SpecifiedTypes();
if (
$context->true()
|| (
$context->false()
&& count($arrayValueType->getFiniteTypes()) > 0
&& count($needleType->getFiniteTypes()) > 0
&& $arrayType->isIterableAtLeastOnce()->yes()
)
) {
$narrowingValueType = $this->computeNeedleNarrowingType($context, $needleType, $arrayType, $arrayValueType);
if ($narrowingValueType !== null) {
$specifiedTypes = $this->typeSpecifier->create(
$needleExpr,
$arrayValueType,
$narrowingValueType,
$context,
$scope,
);
if ($needleExpr instanceof AlwaysRememberedExpr) {
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
$needleExpr->getExpr(),
$arrayValueType,
$narrowingValueType,
$context,
$scope,
));
Expand Down Expand Up @@ -171,4 +166,68 @@
return $specifiedTypes;
}

/**
* Computes the type to narrow the needle against, or null if no narrowing should occur.
* In true context, returns the array value type directly.
* In false context, returns only the values guaranteed to be in every possible variant of the array.
*/
private function computeNeedleNarrowingType(TypeSpecifierContext $context, Type $needleType, Type $arrayType, Type $arrayValueType): ?Type
{
if ($context->true()) {
return $arrayValueType;
}

if (
!$context->false()

Check warning on line 181 in src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrueTruthyFalseFalseyTypeSpecifierContextMutator": @@ @@ } if ( - !$context->false() + !$context->falsey() || count($needleType->getFiniteTypes()) === 0 || !$arrayType->isIterableAtLeastOnce()->yes() ) {

Check warning on line 181 in src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrueTruthyFalseFalseyTypeSpecifierContextMutator": @@ @@ } if ( - !$context->false() + !$context->falsey() || count($needleType->getFiniteTypes()) === 0 || !$arrayType->isIterableAtLeastOnce()->yes() ) {
|| count($needleType->getFiniteTypes()) === 0
|| !$arrayType->isIterableAtLeastOnce()->yes()

Check warning on line 183 in src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ if ( !$context->false() || count($needleType->getFiniteTypes()) === 0 - || !$arrayType->isIterableAtLeastOnce()->yes() + || $arrayType->isIterableAtLeastOnce()->no() ) { return null; }

Check warning on line 183 in src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ if ( !$context->false() || count($needleType->getFiniteTypes()) === 0 - || !$arrayType->isIterableAtLeastOnce()->yes() + || $arrayType->isIterableAtLeastOnce()->no() ) { return null; }
) {
return null;
}

$arrays = $arrayType->getArrays();
$guaranteedValueTypePerArray = [];
foreach ($arrays as $array) {
if ($array instanceof ConstantArrayType) {
$innerGuaranteeValueType = [];
foreach ($array->getValueTypes() as $i => $valueType) {
if ($array->isOptionalKey($i)) {
continue;
}

$finiteTypes = $valueType->getFiniteTypes();
if (count($finiteTypes) !== 1) {
continue;
}

$innerGuaranteeValueType[] = $finiteTypes[0];
}

if (count($innerGuaranteeValueType) === 0) {
return null;
}

$guaranteedValueTypePerArray[] = TypeCombinator::union(...$innerGuaranteeValueType);
} else {
$finiteValueType = $array->getIterableValueType()->getFiniteTypes();
if (count($finiteValueType) !== 1) {
return null;
}

$guaranteedValueTypePerArray[] = $finiteValueType[0];
}
}

if (count($guaranteedValueTypePerArray) === 0) {
return null;
}

$guaranteedValueType = TypeCombinator::intersect(...$guaranteedValueTypePerArray);
if (count($guaranteedValueType->getFiniteTypes()) === 0) {
return null;
}

return $guaranteedValueType;
}

}
26 changes: 26 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-13421.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php // lint >= 8.1

declare(strict_types = 1);

namespace Bug13421;

use function PHPStan\Testing\assertType;

enum Bar
{
case Bar1;
case Bar2;
case Bar3;
}

/**
* @param non-empty-array<Bar> $nonEmptyFilterArray
*/
function test(array $nonEmptyFilterArray): void
{
$bars = [Bar::Bar1, Bar::Bar2, Bar::Bar3];

$filteredBars = array_filter($bars, fn (Bar $bar) => in_array($bar, $nonEmptyFilterArray));

assertType("array{0?: Bug13421\Bar::Bar1, 1?: Bug13421\Bar::Bar2, 2?: Bug13421\Bar::Bar3}", $filteredBars);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the origin example contains a error like

Strict comparison using === between 0 and 0 will always evaluate to true

we should have a rule-test, this no longer happens.

use the tests/PHPStan/Analyser/nsrt/bug-13421.php file in the rule-test - don't create another copy of this file.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Full test suite also passed. All 11710 tests green, static analysis clean. The review feedback from staabm has been addressed and pushed.

}
100 changes: 100 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-14407.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php // lint >= 8.1

declare(strict_types = 1);

namespace Bug14407;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the origin example contains a error like

Strict comparison using === between NEVER and SomeEnum::A will always evaluate to false.

we should have a rule-test, this no longer happens.

use the tests/PHPStan/Analyser/nsrt/bug-14407.php file in the rule-test - don't create another copy of this file.


use function PHPStan\Testing\assertType;

enum SomeEnum {
case A;
case B;
}

function () {
$arr = [];

if (rand(0, 1) === 0) {
$arr[] = SomeEnum::A;
} else {
$arr[] = SomeEnum::B;
}

if (rand(0, 1) === 0) {
$x = SomeEnum::A;
} else {
$x = SomeEnum::B;
}

if (!in_array($x, $arr)) {
// either $x=A, $arr=[B] or $x=B, $arr=[A]
assertType('Bug14407\SomeEnum::A|Bug14407\SomeEnum::B', $x);
}

if (!in_array($x, $arr) && $x === SomeEnum::A) {
// $x=A, $arr=[B]
assertType('Bug14407\SomeEnum::A', $x);
}
};

function () {
$arr = [SomeEnum::A, SomeEnum::B];

if (rand(0, 1) === 0) {
$x = SomeEnum::A;
} else {
$x = SomeEnum::B;
}

if (!in_array($x, $arr)) {
// array always contains both A and B, so this is correctly *NEVER*
assertType('*NEVER*', $x);
}
};

function () {
$arr = [];

$r = rand(0, 2);

if ($r === 0) {
$arr[] = SomeEnum::A;
} elseif ($r === 1) {
$arr[] = SomeEnum::B;
}

if (rand(0, 1) === 0) {
$x = SomeEnum::A;
} else {
$x = SomeEnum::B;
}

// arr might be empty, so no narrowing possible
if (!in_array($x, $arr) && $x === SomeEnum::A) {
assertType('Bug14407\SomeEnum::A', $x);
}
};

/**
* @param 'a'|'b'|'c' $x
* @param array{a: 'a', c: 'c'}|array{a?:'a', b: 'b'} $a
*/
function testUnionWithOptionalKeys($x, $a): void
{
assertType("array{a: 'a', c: 'c'}|array{a?: 'a', b: 'b'}", $a);
if (!\in_array($x, $a, true)) {
assertType("'a'|'b'|'c'", $x);
}
};

/**
* @param 'a'|'b'|'c' $x
* @param non-empty-array<'a'|'b'> $a
*/
function testNonConstantArray($x, $a): void
{
assertType("non-empty-array<'a'|'b'>", $a);
if (!\in_array($x, $a, true)) {
assertType("'a'|'b'|'c'", $x);
}
};
37 changes: 37 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-8864.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types = 1);

namespace Bug8864;

use function PHPStan\Testing\assertType;

/**
* @param array{0: 1, 1?: 2} $a
*/
function test(array $a): void
{
if (in_array(2, $a, true)) {
assertType('array{0: 1, 1?: 2}', $a);
}

if (!in_array(2, $a, true)) {
assertType('array{0: 1, 1?: *NEVER*}', $a);
}
}

/**
* @param 1|2 $x
* @param array{0: 1, 1?: 2} $a
*/
function testNeedle($x, array $a): void
{
if (in_array($x, $a, true)) {
assertType('1|2', $x);
}

if (!in_array($x, $a, true)) {
// 1 is guaranteed in the array, so if not in_array, x must be 2
assertType('2', $x);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1172,4 +1172,16 @@ public function testBug11054(): void
]);
}

#[RequiresPhp('>= 8.1')]
public function testBug14407(): void
{
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-14407.php'], []);
}

#[RequiresPhp('>= 8.1')]
public function testBug13421(): void
{
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-13421.php'], []);
}

}
Loading