Skip to content

Commit 62ac811

Browse files
authored
fix human-readable file size (#204) (#205)
1 parent 456689e commit 62ac811

File tree

2 files changed

+13
-19
lines changed

2 files changed

+13
-19
lines changed

src/ToolboxBundle/Twig/Extension/DownloadExtension.php

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -150,23 +150,17 @@ public function getDownloadInfo(
150150

151151
public function getOptimizedFileSize(mixed $bytes, int $precision): string
152152
{
153-
if ($bytes >= 1073741824) {
154-
$bytes = number_format($bytes / 1073741824, 2);
155-
$format = 'gb';
156-
} elseif ($bytes >= 1048576) {
157-
$bytes = number_format($bytes / 1048576, 2);
158-
$format = 'mb';
159-
} elseif ($bytes >= 1024) {
160-
$bytes = number_format($bytes / 1024, 2);
161-
$format = 'kb';
162-
} elseif ($bytes > 1) {
163-
$format = 'bytes';
164-
} elseif ($bytes === 1) {
165-
$format = 'byte';
166-
} else {
167-
$format = 'bytes';
153+
if ($bytes === 1) {
154+
return '1 Byte';
168155
}
169-
170-
return round((float) $bytes, $precision) . ' ' . $format;
156+
// https://gist.github.com/liunian/9338301?permalink_comment_id=1804497#gistcomment-1804497
157+
static $units = ['Bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
158+
$step = 1024;
159+
$i = 0;
160+
while (($bytes / $step) > 0.9) {
161+
$bytes = $bytes / $step;
162+
$i++;
163+
}
164+
return round($bytes, $precision) . ' ' . ($units[$i] ?? '');
171165
}
172166
}

tests/unit.default/Areas/DownloadTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,13 +206,13 @@ private function getCompareWithFileInfo($path1, $path2)
206206
<li>
207207
<a href="' . $path1 . '" target="_blank" class="icon-download-jpg">
208208
<span class="title">Download</span>
209-
<span class="file-info">(<span class="file-type">jpg</span>, 337 kb)</span>
209+
<span class="file-info">(<span class="file-type">jpg</span>, 337 kB)</span>
210210
</a>
211211
</li>
212212
<li>
213213
<a href="' . $path2 . '" target="_blank" class="icon-download-jpg">
214214
<span class="title">Download</span>
215-
<span class="file-info">(<span class="file-type">jpg</span>, 337 kb)</span>
215+
<span class="file-info">(<span class="file-type">jpg</span>, 337 kB)</span>
216216
</a>
217217
</li>
218218
</ul>

0 commit comments

Comments
 (0)