Skip to content

Commit d10ddd1

Browse files
committed
minor #6980 Fix fileSize() method in Twig extension (javiereguiluz)
This PR was squashed before being merged into the 4.x branch. Discussion ---------- Fix fileSize() method in Twig extension ## Summary - handle zero and large numbers in `fileSize()` - return scaled value with correct unit - test `fileSize()` using a data provider with edge cases Commits ------- e44322d Fix fileSize() method in Twig extension
2 parents c797f70 + e44322d commit d10ddd1

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/Twig/EasyAdminTwigExtension.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,17 @@ public function flattenArray($array, $parentKey = null): array
9797
public function fileSize(int $bytes): string
9898
{
9999
$size = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
100+
101+
if (0 === $bytes) {
102+
return '0B';
103+
}
104+
100105
$factor = (int) floor(log($bytes) / log(1024));
106+
$factor = min($factor, \count($size) - 1);
107+
108+
$scaledValue = (int) ($bytes / (1024 ** $factor));
101109

102-
return (int) ($bytes / (1024 ** $factor)).@$size[$factor];
110+
return sprintf('%d%s', $scaledValue, $size[$factor]);
103111
}
104112

105113
/**

tests/Twig/EasyAdminTwigExtensionTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,32 @@ public function testRepresentAsStringException(): void
5353
$twigExtensionInstance->representAsString(new class {}, 'someMethod');
5454
}
5555

56+
/**
57+
* @dataProvider provideValuesForFileSize
58+
*/
59+
public function testFileSize(int $bytes, string $expected): void
60+
{
61+
$reflectedClass = new \ReflectionClass(EasyAdminTwigExtension::class);
62+
$twigExtensionInstance = $reflectedClass->newInstanceWithoutConstructor();
63+
64+
$result = $twigExtensionInstance->fileSize($bytes);
65+
66+
$this->assertSame($expected, $result);
67+
}
68+
69+
public function provideValuesForFileSize(): iterable
70+
{
71+
yield [0, '0B'];
72+
yield [1, '1B'];
73+
yield [1024, '1K'];
74+
yield [1024 ** 2, '1M'];
75+
yield [1024 ** 3, '1G'];
76+
yield [1024 ** 4, '1T'];
77+
yield [1024 ** 5, '1P'];
78+
yield [1024 ** 6, '1E'];
79+
yield [\PHP_INT_MAX, '8E'];
80+
}
81+
5682
public function provideValuesForRepresentAsString(): iterable
5783
{
5884
yield [null, ''];

0 commit comments

Comments
 (0)