Skip to content

Instantly share code, notes, and snippets.

@hopeseekr
Created May 9, 2018 14:34
Show Gist options
  • Save hopeseekr/e4a4834c6cfbd508bda0b559a07b9234 to your computer and use it in GitHub Desktop.
Save hopeseekr/e4a4834c6cfbd508bda0b559a07b9234 to your computer and use it in GitHub Desktop.
Elusive Bug caught via declare(strict_type=true)

Here's a VERY HARD to find bug that declare(strict_types=1) found:

The Problem: Some note attachments were getting lost in the system. We could see them on GCS, but the API was returning 404s. We couldn't figure out why this was the case for a couple of weeks and the problem was only sporadically reported (not part of the main workflow).

As soon as I turned on strict typing, the problem manifested itself:

class NoteAttachmentHelper
{
    /** @var Symfony\Component\HttpFoundation\File\UploadedFile which is a grandchild of SplFileInfo */
    protected $file;
    
    protected function getFileSize(): int
    {
        return filesize($this->file);
    }
}

The bug reported by strict type:

[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Type error: filesize() expects parameter 1 to be a valid path, object given at /var/www/app/Helpers/NoteAttachme      ntHelper.php:67)

SplFileInfo::__toString() returns whatever was given in __construct($filePath), which in our case is a different temporary upload folder. If the user then requests the file and they get a different Google App Engine server, then the note will return 404, thus why it was inconsinent The correct fix is $this->file->getPathname() but this bug was in our system for 1.5 years before static typing caught it. (edited)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment