|
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
|
|
|
/** |
|
27
|
|
|
* @param NumberHelper $numberHelper |
|
28
|
|
|
*/ |
|
29
|
|
|
public function __construct(NumberHelper $numberHelper) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->numberHelper = $numberHelper; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* {@inheritdoc} |
|
36
|
|
|
*/ |
|
37
|
|
|
public function getFilters() |
|
38
|
|
|
{ |
|
39
|
|
|
return [ |
|
40
|
|
|
new TwigFilter('format_bytes', [$this, 'formatBytes']), |
|
41
|
|
|
new TwigFilter('obfuscate', [$this, 'obfuscate']), |
|
42
|
|
|
]; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @param float $bytes |
|
47
|
|
|
* @param bool $si |
|
48
|
|
|
* @param int $fractionDigits |
|
49
|
|
|
* |
|
50
|
|
|
* @return string |
|
51
|
|
|
*/ |
|
52
|
|
|
public function formatBytes(float $bytes, bool $si = true, int $fractionDigits = 0): string |
|
53
|
|
|
{ |
|
54
|
|
|
$unit = $si ? 1000 : 1024; |
|
55
|
|
|
|
|
56
|
|
|
if ($bytes < $unit) { |
|
57
|
|
|
$pre = 'B'; |
|
58
|
|
|
$num = $bytes; |
|
59
|
|
|
} else { |
|
60
|
|
|
$exp = (int) (log($bytes) / log($unit)); |
|
61
|
|
|
$pre = ($si ? 'kMGTPE' : 'KMGTPE'); |
|
62
|
|
|
$pre = $pre[$exp - 1].($si ? '' : 'i'); |
|
63
|
|
|
|
|
64
|
|
|
$num = $bytes / ($unit ** $exp); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
return sprintf('%s %sB', $this->numberHelper->formatDecimal($num, [ |
|
68
|
|
|
'fraction_digits' => $fractionDigits, |
|
69
|
|
|
]), $pre); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* @param string $string |
|
74
|
|
|
* @param array $options |
|
75
|
|
|
* |
|
76
|
|
|
* @return string |
|
77
|
|
|
*/ |
|
78
|
|
|
public function obfuscate(string $string, array $options = []): string |
|
79
|
|
|
{ |
|
80
|
|
|
$options = array_merge([ |
|
81
|
|
|
'start' => 0, |
|
82
|
|
|
'end' => 3, |
|
83
|
|
|
'replacement' => '*', |
|
84
|
|
|
], $options); |
|
85
|
|
|
|
|
86
|
|
|
return StringUtils::obfuscate($string, $options['start'], $options['end'], $options['replacement']); |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|