Skip to content

PHP's current()/reset() on Media[] may return false - no warning when expecting it to be SomeObject|null only. #2539

@gnutix

Description

@gnutix

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions