Issue
I am having issue getting the return type for this function as I have mixed types in the switch. I have used mixed, it blew up. I have used string|bool and several type for union type.
* @param $value
* @param string $type
public function __construct(string $type, $value)
{
$this->type = $type;
$this->value = $value;
}
I have tried everything but it didn't pass the CI/CD pipeline (AWS)
public function getValue(bool $typed = false)
{
if (false === $typed) {
return $this->value;
}
switch ($this->type) {
case 'boolean':
return (bool) $this->value;
case 'datetime':
if (empty($this->value)) {
return null;
}
return new \DateTime($this->value);
case 'option_tags':
return json_decode($this->value);
default:
return $this->value;
}
}
ERROR The following are the error
Method App\Model\Resources::getValue() has no return typehint specified.
Parameter #1 $time of class DateTime constructor expects string, string|true given.
Parameter #1 $json of function json_decode expects string, bool|string given.
Solution
In modern PHP you can either provide a list of all possible types:
// Tweak type list your exact needs
public function getValue(bool $typed = false): bool|DateTime|null
... or use mixed
if the method can indeed return anything:
public function getValue(bool $typed = false): mixed
In older versions, you can only use the @return
tag in the docblock:
/**
* @param bool $typed
* @return mixed
* @throws Exception
*/
I understand PHPStan will be happy with all options.
Answered By - Álvaro González Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.