<?php

namespace KupShop\ComponentsBundle\Twig\Extension;

use Twig\Extension\RuntimeExtensionInterface;

class FilesizeRuntime implements RuntimeExtensionInterface
{
    public function formatFilesize(int $size, bool $si = true): string
    {
        $unit = $si ? 1000 : 1024;
        if ($size <= $unit) {
            return $size.' B';
        }
        $exp = intval(log($size) / log($unit));
        $pre = ($si ? 'kMGTPE' : 'KMGTPE');
        $pre = $pre[$exp - 1].($si ? '' : 'i');

        return sprintf('%.1f %sB', $size / pow($unit, $exp), $pre);
    }
}
