Skip to content

Commit cbae561

Browse files
committed
Add support for assertContainsOnlyInstancesOf
1 parent c006a38 commit cbae561

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/Type/PHPUnit/Assert/AssertTypeSpecifyingExtensionHelper.php

+21
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
use PhpParser\Node\Expr\FuncCall;
1414
use PhpParser\Node\Expr\Instanceof_;
1515
use PhpParser\Node\Name;
16+
use PhpParser\Node\Param;
1617
use PhpParser\Node\Scalar\LNumber;
18+
use PhpParser\Node\Stmt;
1719
use PHPStan\Analyser\Scope;
1820
use PHPStan\Analyser\SpecifiedTypes;
1921
use PHPStan\Analyser\TypeSpecifier;
@@ -274,6 +276,25 @@ private static function getExpressionResolvers(): array
274276
'ObjectHasAttribute' => static function (Scope $scope, Arg $property, Arg $object): FuncCall {
275277
return new FuncCall(new Name('property_exists'), [$object, $property]);
276278
},
279+
'ContainsOnlyInstancesOf' => static function (Scope $scope, Arg $className, Arg $haystack): Identical {
280+
return new Identical(
281+
$haystack->value,
282+
new FuncCall(new Name('array_filter'), [
283+
$haystack,
284+
new Arg(new Expr\Closure([
285+
'static' => true,
286+
'params' => [
287+
new Param(new Expr\Variable('_')),
288+
],
289+
'stmts' => [
290+
new Stmt\Return_(
291+
new FuncCall(new Name('is_a'), [new Arg(new Expr\Variable('_')), $className])
292+
),
293+
],
294+
])),
295+
])
296+
);
297+
},
277298
];
278299
}
279300

tests/Type/PHPUnit/data/assert-function.php

+7
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use function PHPStan\Testing\assertType;
66
use function PHPUnit\Framework\assertArrayHasKey;
7+
use function PHPUnit\Framework\assertContainsOnlyInstancesOf;
78
use function PHPUnit\Framework\assertEmpty;
89
use function PHPUnit\Framework\assertInstanceOf;
910
use function PHPUnit\Framework\assertObjectHasAttribute;
@@ -43,4 +44,10 @@ public function testEmpty($a): void
4344
assertType("0|0.0|''|'0'|array{}|Countable|EmptyIterator|false|null", $a);
4445
}
4546

47+
public function containsOnlyInstancesOf(array $a): void
48+
{
49+
assertContainsOnlyInstancesOf(\stdClass::class, $a);
50+
assertType('array<stdClass>', $a);
51+
}
52+
4653
}

0 commit comments

Comments
 (0)