Files
backupscript/src/Template/TwigExtension.php

46 lines
1.0 KiB
PHP
Raw Permalink Normal View History

2023-05-26 11:47:40 +00:00
<?php
declare(strict_types=1);
2023-06-15 14:10:17 +00:00
namespace App\Template;
2023-05-26 11:47:40 +00:00
use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
2023-06-05 09:40:04 +00:00
/**
* Twig extension
2023-06-08 12:44:59 +00:00
*
2023-06-05 09:40:04 +00:00
* Additional formatters for templates
*/
final class TwigExtension extends AbstractExtension
2023-05-26 11:47:40 +00:00
{
2023-06-05 09:40:04 +00:00
/**
* Extend the filters
2023-06-08 12:44:59 +00:00
*
* @return TwigFilter[]
2023-06-05 09:40:04 +00:00
*/
#[\Override]
2023-06-08 12:44:59 +00:00
public function getFilters(): array
2023-05-26 11:47:40 +00:00
{
2024-02-07 11:00:08 +00:00
return [
new TwigFilter('formatBytes', [$this, 'formatBytes']),
];
2023-05-26 11:47:40 +00:00
}
/**
2023-05-26 12:14:21 +00:00
* Format a file size to be human readable
2023-06-08 12:44:59 +00:00
*
2023-05-26 12:14:21 +00:00
* @param int $bytes Number of bytes
2023-06-01 09:16:19 +00:00
* @param int $precision Precision
2023-06-08 12:44:59 +00:00
*
2023-05-26 12:14:21 +00:00
* @return string Formatted string
2023-05-26 11:47:40 +00:00
*/
public function formatBytes($bytes, $precision = 2)
{
$size = ['B','kB','MB','GB','TB','PB','EB','ZB','YB'];
2023-11-03 12:02:44 +00:00
$fact = (int)floor((strlen((string)$bytes) - 1) / 3);
2023-05-26 12:14:21 +00:00
return sprintf("%.{$precision}f", $bytes / pow(1024, $fact)) . $size[$fact];
2023-05-26 11:47:40 +00:00
}
2023-06-08 12:44:59 +00:00
}