Skip to content

Commit d29fb8b

Browse files
committed
Add partial support for assertContainsOnlyInstancesOf
1 parent c006a38 commit d29fb8b

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/Type/PHPUnit/Assert/AssertTypeSpecifyingExtensionHelper.php

+24
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,28 @@ 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): Expr {
280+
return new Expr\BinaryOp\BooleanOr(
281+
new Expr\Instanceof_($haystack->value, new Name('Traversable')),
282+
new Identical(
283+
$haystack->value,
284+
new FuncCall(new Name('array_filter'), [
285+
$haystack,
286+
new Arg(new Expr\Closure([
287+
'static' => true,
288+
'params' => [
289+
new Param(new Expr\Variable('_')),
290+
],
291+
'stmts' => [
292+
new Stmt\Return_(
293+
new FuncCall(new Name('is_a'), [new Arg(new Expr\Variable('_')), $className])
294+
),
295+
],
296+
])),
297+
])
298+
)
299+
);
300+
},
277301
];
278302
}
279303

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

+10
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,13 @@ 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, \Traversable $b): void
48+
{
49+
assertContainsOnlyInstancesOf(\stdClass::class, $a);
50+
assertType('array<stdClass>', $a);
51+
52+
assertContainsOnlyInstancesOf(\stdClass::class, $b);
53+
assertType('Traversable', $b);
54+
}
55+
4656
}

0 commit comments

Comments
 (0)