Skip to content

Commit

Permalink
Add support for assertContains and assertContainsEquals
Browse files Browse the repository at this point in the history
  • Loading branch information
villfa authored and ondrejmirtes committed Aug 25, 2023
1 parent 2742e1c commit e468b76
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Type/PHPUnit/Assert/AssertTypeSpecifyingExtensionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,21 @@ private static function getExpressionResolvers(): array
'ObjectHasAttribute' => static function (Scope $scope, Arg $property, Arg $object): FuncCall {
return new FuncCall(new Name('property_exists'), [$object, $property]);
},
'Contains' => static function (Scope $scope, Arg $needle, Arg $haystack): Expr {
return new Expr\BinaryOp\BooleanOr(
new Expr\Instanceof_($haystack->value, new Name('Traversable')),
new FuncCall(new Name('in_array'), [$needle, $haystack, new Arg(new ConstFetch(new Name('true')))])
);
},
'ContainsEquals' => static function (Scope $scope, Arg $needle, Arg $haystack): Expr {
return new Expr\BinaryOp\BooleanOr(
new Expr\Instanceof_($haystack->value, new Name('Traversable')),
new Expr\BinaryOp\BooleanAnd(
new Expr\BooleanNot(new Expr\Empty_($haystack->value)),
new FuncCall(new Name('in_array'), [$needle, $haystack, new Arg(new ConstFetch(new Name('false')))])
)
);
},
'ContainsOnlyInstancesOf' => static function (Scope $scope, Arg $className, Arg $haystack): Expr {
return new Expr\BinaryOp\BooleanOr(
new Expr\Instanceof_($haystack->value, new Name('Traversable')),
Expand Down
20 changes: 20 additions & 0 deletions tests/Type/PHPUnit/data/assert-function.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use function PHPStan\Testing\assertType;
use function PHPUnit\Framework\assertArrayHasKey;
use function PHPUnit\Framework\assertContains;
use function PHPUnit\Framework\assertContainsEquals;
use function PHPUnit\Framework\assertContainsOnlyInstancesOf;
use function PHPUnit\Framework\assertEmpty;
use function PHPUnit\Framework\assertInstanceOf;
Expand Down Expand Up @@ -61,6 +63,24 @@ public function testEmpty($a): void
assertType("0|0.0|''|'0'|array{}|Countable|EmptyIterator|false|null", $a);
}

public function contains(array $a, \Traversable $b): void
{
assertContains('foo', $a);
assertType('non-empty-array', $a);

assertContains('foo', $b);
assertType('Traversable', $b);
}

public function containsEquals(array $a, \Traversable $b): void
{
assertContainsEquals('foo', $a);
assertType('non-empty-array', $a);

assertContainsEquals('foo', $b);
assertType('Traversable', $b);
}

public function containsOnlyInstancesOf(array $a, \Traversable $b): void
{
assertContainsOnlyInstancesOf(\stdClass::class, $a);
Expand Down

0 comments on commit e468b76

Please sign in to comment.