Patrique Ouimet
Senior Product Engineer
Mon, Dec 16, 2019 8:42 AM
Recently I've been tickering with writing a routing package. While writing it I ran into issues where I need to explicitly check for 3 types for a single parameter. Here's the code snippet:
<?php
// Removed most of the code/comments to demonstration purposes.
/**
* @param null|array|object $data
* @return static
* @throws InvalidArgumentException
*/
public function withParsedBody($data)
{
if (! is_null($data) && ! is_object($data) && ! is_array($data)) {
throw new InvalidArgumentException(
'Parsed body must be of type: null, array, or object'
);
}
// more code here...
}
The above block of code would give me the following error from Psalm:
ERROR: TypeDoesNotContainType - src/ServerRequest.php:756:13 - Found a contradiction when evaluating $data and trying to reconcile type 'array<array-key, mixed>' to !array
if (! is_null($data) && ! is_object($data) && ! is_array($data)) {
ERROR: TypeDoesNotContainType - src/ServerRequest.php:756:57 - Found a contradiction when evaluating $data and trying to reconcile type 'array<array-key, mixed>' to !array
if (! is_null($data) && ! is_object($data) && ! is_array($data)) {
I tried a few different solutions to solve the issues described, nothing seemed to work.
After reading through PHP Psalm documentation (Dealing with code issues) I figured out I could suppress certain errors for a block of code.
<?php
// Removed most of the code/comments to demonstration purposes.
/**
* @param null|array|object $data
* @return static
* @throws InvalidArgumentException
*/
public function withParsedBody($data)
{
/**
* @psalm-suppress DocblockTypeContradiction
* @psalm-suppress TypeDoesNotContainType
*/
if (! is_null($data) && ! is_object($data) && ! is_array($data)) {
throw new InvalidArgumentException(
'Parsed body must be of type: null, array, or object'
);
}
// more code here...
}
If you happen to know why I'm getting this error message and how to fix it (without suppressing psalm errors) please let me know! Send me an email at patrique.ouimet@gmail.com or send me a direct message on Twitter @patoui2.
Useful links: