Skip to content

Array shape with more than one optional key not respected #3192

@jaydiablo

Description

@jaydiablo

Bug report

I believe this is a new issue, as the related, open, array shape issues I've found don't quite describe this. I ran into an issue today where PHPStan isn't type-checking an array passed into a method properly.

As a simple example, here's the method's @param for the array it can accept:

@param array{sorton?:string,limit?:int} $test

Both the sorton and limit keys are optional, sorton accepts a string and limit accepts an int. However, if I call this method with this array:

['sorton' => 'test', 'limit' => 'true'] (limit can't be a string)

PHPStan doesn't complain at all: https://phpstan.org/r/b0a5113d-0734-41b3-8116-2c94f8bbb38e

If I make both sorton and limit required in the array shape, PHPStan will complain about limit not being the correct type: https://phpstan.org/r/5659a478-e7d7-48d1-bd37-b4a9ae3983d4

If I make either sorton or limit optional, PHPStan doesn't complain: https://phpstan.org/r/c002c5c1-743b-4df2-890c-4105c6417502

If limit is the only defined key in the array, it doesn't matter if it's required or not:
https://phpstan.org/r/48e74e89-abd7-4619-bfea-754eefaf8b94
https://phpstan.org/r/7704223b-ec37-4479-82be-7c49ed6031a5

It seems to be a combination of more than one defined key in the shape AND one or more of those keys being marked as optional.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions