Ip\Internal\FormatHelper::formatBytes PHP Method

formatBytes() public static method

public static formatBytes ( $bytes, $context, $precision, null $languageCode = null ) : mixed | null | string
$bytes
$context
$precision
$languageCode null
return mixed | null | string
    public static function formatBytes($bytes, $context, $precision, $languageCode = null)
    {
        $data = array('bytes' => $bytes, 'context' => $context, 'precision' => $precision, 'languageCode' => $languageCode);
        $formattedBytes = ipJob('ipFormatBytes', $data);
        if ($formattedBytes !== null) {
            return $formattedBytes;
        }
        $sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        $decimal = array('au', 'bn', 'bw', 'ch', 'cn', 'do', 'eg', 'gt', 'hk', 'hn', 'ie', 'il', 'in', 'jp', 'ke', 'kp', 'kr', 'lb', 'lk', 'mn', 'mo', 'mt', 'mx', 'my', 'ng', 'ni', 'np', 'nz', 'pa', 'ph', 'pk', 'sg', 'th', 'tw', 'tz', 'ug', 'uk', 'us', 'zw');
        if ($languageCode === null) {
            $languageCode = ipContent()->getCurrentLanguage()->getCode();
        }
        for ($i = 0; $bytes >= 1024; $i++) {
            $bytes /= 1024;
            if ($i < 1) {
                $bytes = round($bytes, 0);
            } else {
                $bytes = round($bytes, $precision);
            }
        }
        if (in_array(strtolower($languageCode), $decimal)) {
            $formattedBytes = $bytes;
        } else {
            $formattedBytes = str_replace('.', ',', $bytes);
        }
        $formattedBytes .= ' ' . $sizes[$i];
        return $formattedBytes;
    }

Usage Example

Example #1
0
/**
 * Get formatted byte string
 *
 * Returns a string containing a rounded numeric value and appropriate 'B', 'KB', 'MB', 'GB', 'TB', 'PB' modifiers.
 *
 * @param int $bytes Size in bytes.
 * @param string $context plugin name
 * @param int $precision number of digits after the decimal point
 * @param string $languageCode
 * @return string A string formatted in byte size units.
 */
function ipFormatBytes($bytes, $context, $precision = 0, $languageCode = null)
{
    return \Ip\Internal\FormatHelper::formatBytes($bytes, $context, $precision, $languageCode);
}