From c8ba485edc223e4a5ddb7e0a7e33986ce2bea0bf Mon Sep 17 00:00:00 2001 From: ghost Date: Thu, 14 Dec 2023 01:48:45 +0200 Subject: [PATCH] add formatBytes filter --- src/Twig/AppExtension.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/Twig/AppExtension.php b/src/Twig/AppExtension.php index 98c20ba..5ab94b9 100644 --- a/src/Twig/AppExtension.php +++ b/src/Twig/AppExtension.php @@ -31,6 +31,13 @@ class AppExtension extends AbstractExtension 'formatAgo' ] ), + new TwigFilter( + 'format_bytes', + [ + $this, + 'formatBytes' + ] + ), new TwigFilter( 'message_to_markdown', [ @@ -140,6 +147,28 @@ class AppExtension extends AbstractExtension } } + public function formatBytes( + int $bytes, + int $precision = 2 + ): string + { + $size = [ + $this->translator->trans('B'), + $this->translator->trans('Kb'), + $this->translator->trans('Mb'), + $this->translator->trans('Gb'), + $this->translator->trans('Tb'), + $this->translator->trans('Pb'), + $this->translator->trans('Eb'), + $this->translator->trans('Zb'), + $this->translator->trans('Yb') + ]; + + $factor = floor((strlen($bytes) - 1) / 3); + + return sprintf("%.{$precision}f", $bytes / pow(1024, $factor)) . ' ' . @$size[$factor]; + } + public function messageToMarkdown( string $text ): string