Created
June 14, 2013 11:21
-
-
Save bwaidelich/5781107 to your computer and use it in GitHub Desktop.
FileSizeViewHelper
This file contains hidden or 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 | |
namespace Your\Package\ViewHelpers\Format; | |
/* * | |
* This script belongs to the TYPO3 Flow package "Your.Package. * | |
* * | |
* */ | |
use TYPO3\Flow\Annotations as Flow; | |
use TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper; | |
/** | |
* ViewHelper rendering the size of a file | |
*/ | |
class FileSizeViewHelper extends AbstractViewHelper { | |
/** | |
* @var array | |
*/ | |
protected $units = array('B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB'); | |
/** | |
* Format the filesize | |
* | |
* @param mixed $size The file's size in bytes or an instance of \TYPO3\Flow\Resource\Resource. If NULL the child nodes are used as size | |
* @param integer $precision The optional number of decimal digits to round to | |
* @return string The filesize with SI unit appended | |
*/ | |
public function render($size = NULL, $precision = 2) { | |
if ($size === NULL) { | |
$size = $this->renderChildren(); | |
} | |
if ($size instanceof \TYPO3\Flow\Resource\Resource) { | |
$size = @filesize('resource://' . $size->getResourcePointer()->getHash()); | |
} | |
# determine the unit | |
$unit = reset($this->units); | |
while($size > 1024) { | |
$size /= 1024; | |
$unit = next($this->units); | |
} | |
return sprintf('%s %s', round($size, $precision), $unit); | |
} | |
} | |
?> |
FYI: Since Flow 2.1 this is shipped with Fluid and can be used like
{fileSize -> f:format.bytes()}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
{someResource -> x:format.fileSize()}
or
{x:format.fileSize(size: someFileSize)}