Skip to content

Commit

Permalink
Improve support of assertArrayHasKey()
Browse files Browse the repository at this point in the history
  • Loading branch information
villfa authored and ondrejmirtes committed Aug 25, 2023
1 parent abc6e12 commit f2118db
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
10 changes: 8 additions & 2 deletions src/Type/PHPUnit/Assert/AssertTypeSpecifyingExtensionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,14 @@ private static function getExpressionResolvers(): array
]
);
},
'ArrayHasKey' => static function (Scope $scope, Arg $key, Arg $array): FuncCall {
return new FuncCall(new Name('array_key_exists'), [$key, $array]);
'ArrayHasKey' => static function (Scope $scope, Arg $key, Arg $array): Expr {
return new Expr\BinaryOp\BooleanOr(
new Expr\BinaryOp\BooleanAnd(
new Expr\Instanceof_($array->value, new Name('ArrayAccess')),
new Expr\MethodCall($array->value, 'offsetExists', [$key])
),
new FuncCall(new Name('array_key_exists'), [$key, $array])
);
},
'ObjectHasAttribute' => static function (Scope $scope, Arg $property, Arg $object): FuncCall {
return new FuncCall(new Name('property_exists'), [$object, $property]);
Expand Down
10 changes: 8 additions & 2 deletions tests/Type/PHPUnit/data/assert-function.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,21 @@ public function assertInstanceOfWorksWithTemplate($o, $class): void
assertType(\DateTimeInterface::class, $o);
}

public function arrayHasNumericKey(array $a): void {
public function arrayHasNumericKey(array $a, \ArrayAccess $b): void {
assertArrayHasKey(0, $a);
assertType('array&hasOffset(0)', $a);

assertArrayHasKey(0, $b);
assertType('ArrayAccess', $b);
}

public function arrayHasStringKey(array $a): void
public function arrayHasStringKey(array $a, \ArrayAccess $b): void
{
assertArrayHasKey('key', $a);
assertType("array&hasOffset('key')", $a);

assertArrayHasKey('key', $b);
assertType("ArrayAccess", $b);
}

public function objectHasAttribute(object $a): void
Expand Down

0 comments on commit f2118db

Please sign in to comment.