46 lines
1.0 KiB
PHP
46 lines
1.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Template;
|
|
|
|
use Symfony\Component\DependencyInjection\ContainerInterface;
|
|
use Twig\Extension\AbstractExtension;
|
|
use Twig\TwigFilter;
|
|
|
|
/**
|
|
* Twig extension
|
|
*
|
|
* Additional formatters for templates
|
|
*/
|
|
final class TwigExtension extends AbstractExtension
|
|
{
|
|
/**
|
|
* Extend the filters
|
|
*
|
|
* @return TwigFilter[]
|
|
*/
|
|
#[\Override]
|
|
public function getFilters(): array
|
|
{
|
|
return [
|
|
new TwigFilter('formatBytes', [$this, 'formatBytes']),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Format a file size to be human readable
|
|
*
|
|
* @param int $bytes Number of bytes
|
|
* @param int $precision Precision
|
|
*
|
|
* @return string Formatted string
|
|
*/
|
|
public function formatBytes($bytes, $precision = 2)
|
|
{
|
|
$size = ['B','kB','MB','GB','TB','PB','EB','ZB','YB'];
|
|
$fact = (int)floor((strlen((string)$bytes) - 1) / 3);
|
|
return sprintf("%.{$precision}f", $bytes / pow(1024, $fact)) . $size[$fact];
|
|
}
|
|
}
|