1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* (c) Christian Gripp <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Core23\Twig\Extension; |
13
|
|
|
|
14
|
|
|
use Core23\Twig\Util\StringUtils; |
15
|
|
|
use Sonata\IntlBundle\Templating\Helper\NumberHelper; |
16
|
|
|
use Twig\Extension\AbstractExtension; |
17
|
|
|
use Twig\TwigFilter; |
18
|
|
|
|
19
|
|
|
final class StringTwigExtension extends AbstractExtension |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var NumberHelper |
23
|
|
|
*/ |
24
|
|
|
private $numberHelper; |
25
|
|
|
|
26
|
|
|
public function __construct(NumberHelper $numberHelper) |
27
|
|
|
{ |
28
|
|
|
$this->numberHelper = $numberHelper; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function getFilters() |
32
|
|
|
{ |
33
|
|
|
return [ |
34
|
|
|
new TwigFilter('format_bytes', [$this, 'formatBytes']), |
35
|
|
|
new TwigFilter('obfuscate', [$this, 'obfuscate']), |
36
|
|
|
]; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function formatBytes(float $bytes, bool $si = true, int $fractionDigits = 0): string |
40
|
|
|
{ |
41
|
|
|
$unit = $si ? 1000 : 1024; |
42
|
|
|
|
43
|
|
|
if ($bytes < $unit) { |
44
|
|
|
$pre = 'B'; |
45
|
|
|
$num = $bytes; |
46
|
|
|
} else { |
47
|
|
|
$exp = (int) (log($bytes) / log($unit)); |
48
|
|
|
$pre = ($si ? 'kMGTPE' : 'KMGTPE'); |
49
|
|
|
$pre = $pre[$exp - 1].($si ? '' : 'i'); |
50
|
|
|
|
51
|
|
|
$num = $bytes / ($unit ** $exp); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return sprintf('%s %sB', $this->numberHelper->formatDecimal($num, [ |
55
|
|
|
'fraction_digits' => $fractionDigits, |
56
|
|
|
]), $pre); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function obfuscate(string $string, array $options = []): string |
60
|
|
|
{ |
61
|
|
|
$options = array_merge([ |
62
|
|
|
'start' => 0, |
63
|
|
|
'end' => 3, |
64
|
|
|
'replacement' => '*', |
65
|
|
|
], $options); |
66
|
|
|
|
67
|
|
|
return StringUtils::obfuscate($string, $options['start'], $options['end'], $options['replacement']); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|