<?php

namespace AppBundle\Twig;

/**
 * Copy of the excellent Twig Extension Number
 *
 * @see https://github.com/thePanz/Twig-Extension-Number 
 */
class NumberExtension extends \Twig_Extension
{
    /**
     * Returns a list of filters.
     *
     * @return array
     */
    public function getFilters(): array
    {
        return [
            new \Twig_SimpleFilter('format_bytes',  [$this, 'format_bytes']),
        ];
    }

    /**
     * @param $number
     * @return bool
     */
    protected function is_valid_value($number): bool
    {
        return is_numeric($number);
    }

    /**
     * Filter for converting bytes to a human-readable format, as Unix command "ls -h" does.
     *
     * @param string|int $number          A string or integer number value to format.
     * @param bool       $base2conversion Defines if the conversion has to be strictly performed as binary values or
     *                                    by using a decimal conversion such as 1 KByte = 1000 Bytes.
     *
     * @return string The number converted to human readable representation.
     */
    public function format_bytes($number, bool $base2conversion = true): string
    {
        if (!$this->is_valid_value($number)) {
            return '';
        }

        $unit = $base2conversion ? 1024 : 1000;
        if ($number < $unit) {
            return $number.' B';
        }
        $exp = intval((log($number) / log($unit)));
        $pre = ($base2conversion ? 'kMGTPE' : 'KMGTPE');
        $pre = $pre[$exp - 1].($base2conversion ? '' : 'i');

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