This commit is contained in:
20
src/Template/Twig.php
Normal file
20
src/Template/Twig.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Template;
|
||||
|
||||
use Twig\Environment;
|
||||
use Twig\Loader\ArrayLoader;
|
||||
use App\Template\TwigExtension;
|
||||
|
||||
class Twig extends Environment
|
||||
{
|
||||
/**
|
||||
* @param string[] $templates Array of templates
|
||||
*/
|
||||
public function __construct(array $templates)
|
||||
{
|
||||
$loader = new ArrayLoader($templates);
|
||||
parent::__construct($loader);
|
||||
$this->addExtension(new TwigExtension());
|
||||
}
|
||||
}
|
||||
42
src/Template/TwigExtension.php
Normal file
42
src/Template/TwigExtension.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Template;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Twig\Extension\AbstractExtension;
|
||||
use Twig\TwigFilter;
|
||||
|
||||
/**
|
||||
* Twig extension
|
||||
*
|
||||
* Additional formatters for templates
|
||||
*/
|
||||
class TwigExtension extends AbstractExtension
|
||||
{
|
||||
/**
|
||||
* Extend the filters
|
||||
*
|
||||
* @return TwigFilter[]
|
||||
*/
|
||||
public function getFilters(): array
|
||||
{
|
||||
return array(
|
||||
new TwigFilter('formatBytes', array($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];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user