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

Add partial support for assertContainsOnlyInstancesOf #180

Merged
merged 1 commit into from
Jul 20, 2023
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
24 changes: 24 additions & 0 deletions src/Type/PHPUnit/Assert/AssertTypeSpecifyingExtensionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Instanceof_;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Scalar\LNumber;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifier;
Expand Down Expand Up @@ -274,6 +276,28 @@ private static function getExpressionResolvers(): array
'ObjectHasAttribute' => static function (Scope $scope, Arg $property, Arg $object): FuncCall {
return new FuncCall(new Name('property_exists'), [$object, $property]);
},
'ContainsOnlyInstancesOf' => static function (Scope $scope, Arg $className, Arg $haystack): Expr {
return new Expr\BinaryOp\BooleanOr(
new Expr\Instanceof_($haystack->value, new Name('Traversable')),
new Identical(
$haystack->value,
new FuncCall(new Name('array_filter'), [
$haystack,
new Arg(new Expr\Closure([
'static' => true,
'params' => [
new Param(new Expr\Variable('_')),
],
'stmts' => [
new Stmt\Return_(
new FuncCall(new Name('is_a'), [new Arg(new Expr\Variable('_')), $className])
),
],
])),
])
)
);
},
];
}

Expand Down
10 changes: 10 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,7 @@

use function PHPStan\Testing\assertType;
use function PHPUnit\Framework\assertArrayHasKey;
use function PHPUnit\Framework\assertContainsOnlyInstancesOf;
use function PHPUnit\Framework\assertEmpty;
use function PHPUnit\Framework\assertInstanceOf;
use function PHPUnit\Framework\assertObjectHasAttribute;
Expand Down Expand Up @@ -43,4 +44,13 @@ public function testEmpty($a): void
assertType("0|0.0|''|'0'|array{}|Countable|EmptyIterator|false|null", $a);
}

public function containsOnlyInstancesOf(array $a, \Traversable $b): void
{
assertContainsOnlyInstancesOf(\stdClass::class, $a);
assertType('array<stdClass>', $a);

assertContainsOnlyInstancesOf(\stdClass::class, $b);
assertType('Traversable', $b);
}

}