Skip to content

Commit 2742e1c

Browse files
villfaondrejmirtes
authored andcommitted
Add partial support for assertContainsOnlyInstancesOf
1 parent f2118db commit 2742e1c

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

‎src/Type/PHPUnit/Assert/AssertTypeSpecifyingExtensionHelper.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
usePhpParser\Node\Expr\FuncCall;
1414
usePhpParser\Node\Expr\Instanceof_;
1515
usePhpParser\Node\Name;
16+
usePhpParser\Node\Param;
1617
usePhpParser\Node\Scalar\LNumber;
18+
usePhpParser\Node\Stmt;
1719
usePHPStan\Analyser\Scope;
1820
usePHPStan\Analyser\SpecifiedTypes;
1921
usePHPStan\Analyser\TypeSpecifier;
@@ -274,6 +276,28 @@ private static function getExpressionResolvers(): array
274276
'ObjectHasAttribute' => staticfunction (Scope$scope, Arg$property, Arg$object): FuncCall {
275277
returnnewFuncCall(newName('property_exists'), [$object, $property]);
276278
},
279+
'ContainsOnlyInstancesOf' => staticfunction (Scope$scope, Arg$className, Arg$haystack): Expr {
280+
returnnewExpr\BinaryOp\BooleanOr(
281+
newExpr\Instanceof_($haystack->value, newName('Traversable')),
282+
newIdentical(
283+
$haystack->value,
284+
newFuncCall(newName('array_filter'), [
285+
$haystack,
286+
newArg(newExpr\Closure([
287+
'static' => true,
288+
'params' => [
289+
newParam(newExpr\Variable('_')),
290+
],
291+
'stmts' => [
292+
newStmt\Return_(
293+
newFuncCall(newName('is_a'), [newArg(newExpr\Variable('_')), $className])
294+
),
295+
],
296+
])),
297+
])
298+
)
299+
);
300+
},
277301
];
278302
}
279303

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
usefunctionPHPStan\Testing\assertType;
66
usefunctionPHPUnit\Framework\assertArrayHasKey;
7+
usefunctionPHPUnit\Framework\assertContainsOnlyInstancesOf;
78
usefunctionPHPUnit\Framework\assertEmpty;
89
usefunctionPHPUnit\Framework\assertInstanceOf;
910
usefunctionPHPUnit\Framework\assertObjectHasAttribute;
@@ -60,4 +61,13 @@ public function testEmpty($a): void
6061
assertType("0|0.0|''|'0'|array{}|Countable|EmptyIterator|false|null", $a);
6162
}
6263

64+
publicfunctioncontainsOnlyInstancesOf(array$a, \Traversable$b): void
65+
{
66+
assertContainsOnlyInstancesOf(\stdClass::class, $a);
67+
assertType('array<stdClass>', $a);
68+
69+
assertContainsOnlyInstancesOf(\stdClass::class, $b);
70+
assertType('Traversable', $b);
71+
}
72+
6373
}

0 commit comments

Comments
 (0)