-
-
Notifications
You must be signed in to change notification settings - Fork 930
Closed
Labels
Milestone
Description
I encountered a bug in the following code :
<?php
class MediaManager
{
public function find(int $id): ?Media
{
$search = new MediaSearch();
$search->setId($id);
return current($this->mediaRepository->search($search));
}
}
interface MediaRepository
{
public function search(MediaSearch $search): array;
}
If $this->mediaRepository->search($search)
returns an empty array []
(because the provided int $id
does not exist), current()
will return false
and PHP will error because find
should return a Media
or null
, not false
. I refactored the code as such :
<?php
class MediaManager
{
public function find(int $id): ?Media
{
$search = new MediaSearch();
$search->setId($id);
$medias = $this->mediaRepository->search($search);
$media = current($medias);
if (!$media) {
return null;
}
return $media;
}
}
And this little story left me wondering if it shouldn't have been caught by PHPStan ? As we return the value of a function that potentially returns false
while expect only Media|null
. What do you think ? (I don't know the internals of PHPStan well enough to know if it's a bug or a missing feature).
adaamz