Skip to content

Instantly share code, notes, and snippets.

@bwaidelich
Created June 14, 2013 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwaidelich/5781107 to your computer and use it in GitHub Desktop.
Save bwaidelich/5781107 to your computer and use it in GitHub Desktop.
FileSizeViewHelper
<?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);
}
}
?>
@bwaidelich
Copy link
Author

Usage:

{someResource -> x:format.fileSize()}

or

{x:format.fileSize(size: someFileSize)}

@bwaidelich
Copy link
Author

FYI: Since Flow 2.1 this is shipped with Fluid and can be used like

{fileSize -> f:format.bytes()}

(see https://forge.typo3.org/issues/49128)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment