Skip to content

Bug: CodeIgniter\Files\File::getSize() - wrong type of result #2476

Description

@WinterSilence

Describe the bug
CodeIgniter\Files\File::getSize() return int|string (+ error in doc @return integer|null), but this method extends SplFileInfo::getSize() and must return integer.

CodeIgniter 4 version
develop

Fix

/**
 * Size units ('b' - byte, 'kb' - kilobytes, 'mb' - megabytes).
 * 
 * @var array
 */
public const SIZE_UNITS = [
    'b' => 1,
    'kb' => 1024,
    'mb' => ‭1048576‬,
];

/**
 * The file size in bytes or null if unknown.
 *
 * @var int|null
 */
protected $size;

/**
/**
 * Retrieve the file size in bytes.
 *
 * Implementations SHOULD return the value stored in the "size" key of
 * the file in the $_FILES array if available, as PHP calculates this based
 * on the actual size transmitted.
 * 
 * @return int
 */
public function getSize(): int
{
    if ($this->size === null)
    {
        $this->size = parent::getSize() ?: @filesize($this->getPathname());
    }
    return (int) $this->size;
}

/**
 * Retrieve the file size by
 *
 * @param string $unit The unit to return.
 *
 * @return float|null
 */
public function getSizeByUnit(string $unit = 'b'): ?float
{
    if (! $this->getSize())
    {
        return null;
    }
    $unit = strtolower($unit);
    if (! isset(static::SIZE_UNITS[$unit]))
    {
        throw new InvalidArgumentException('Wrong unit');
    }
    return round($this->getSize() / static::SIZE_UNITS[$unit], 3);
}

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugVerified issues on the current code behavior or pull requests that will fix them

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions