Created
October 20, 2012 17:34
-
-
Save baado/3924158 to your computer and use it in GitHub Desktop.
Smarty Byte Format Plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Smarty plugin | |
* | |
* @package Smarty | |
* @subpackage PluginsModifier | |
*/ | |
/** | |
* Smarty format_byte modifier plugin | |
* | |
* Type: modifier<br> | |
* Name: format_byte<br> | |
* Purpose: Format byte(s) | |
* | |
* @param integer $bytes | |
* @param integer $precision | |
* @param array $units | |
*/ | |
function smarty_modifier_format_byte($bytes, $precision = 2, array $units = null) { | |
if (!$bytes || !is_numeric($bytes)) { | |
return '0 B'; | |
} | |
$bytes = intval($bytes); | |
if (abs($bytes) < 1024) { | |
$precision = 0; | |
} | |
if (is_array($units) === false) { | |
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); | |
} | |
if ($bytes < 0) { | |
$sign = '-'; | |
$bytes = abs($bytes); | |
} else { | |
$sign = ''; | |
} | |
$exp = floor(log($bytes) / log(1024)); | |
if ($exp >= count($units)) { | |
$exp = count($units) - 1; | |
} | |
$unit = $units[$exp]; | |
$bytes = $bytes / pow(1024, floor($exp)); | |
if (!is_numeric($precision) || intval($precision) < 0) { | |
$precision = 2; | |
} | |
$precision = intval($precision); | |
$bytes = sprintf('%.' . $precision . 'f', $bytes); | |
return $sign . $bytes . ' ' . $unit; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Qiitaからのフォークです。
http://qiita.com/items/0090ab167bbdb3d77181
0バイトの時の処理、バイト数桁あふれ時の処理、引数のフールプルーフ処理を追加しています。
ファイルフォーマットもSmartyライクに変更しています。