Skip to content

Commit

Permalink
fix human-readable file size (#204) (#205)
Browse files Browse the repository at this point in the history
  • Loading branch information
benwalch committed Sep 6, 2023
1 parent 456689e commit 62ac811
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 19 deletions.
28 changes: 11 additions & 17 deletions src/ToolboxBundle/Twig/Extension/DownloadExtension.php
Expand Up @@ -150,23 +150,17 @@ public function getDownloadInfo(

public function getOptimizedFileSize(mixed $bytes, int $precision): string
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2);
$format = 'gb';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2);
$format = 'mb';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2);
$format = 'kb';
} elseif ($bytes > 1) {
$format = 'bytes';
} elseif ($bytes === 1) {
$format = 'byte';
} else {
$format = 'bytes';
if ($bytes === 1) {
return '1 Byte';
}

return round((float) $bytes, $precision) . ' ' . $format;
// https://gist.github.com/liunian/9338301?permalink_comment_id=1804497#gistcomment-1804497
static $units = ['Bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$step = 1024;
$i = 0;
while (($bytes / $step) > 0.9) {
$bytes = $bytes / $step;
$i++;
}
return round($bytes, $precision) . ' ' . ($units[$i] ?? '');
}
}
4 changes: 2 additions & 2 deletions tests/unit.default/Areas/DownloadTest.php
Expand Up @@ -206,13 +206,13 @@ private function getCompareWithFileInfo($path1, $path2)
<li>
<a href="' . $path1 . '" target="_blank" class="icon-download-jpg">
<span class="title">Download</span>
<span class="file-info">(<span class="file-type">jpg</span>, 337 kb)</span>
<span class="file-info">(<span class="file-type">jpg</span>, 337 kB)</span>
</a>
</li>
<li>
<a href="' . $path2 . '" target="_blank" class="icon-download-jpg">
<span class="title">Download</span>
<span class="file-info">(<span class="file-type">jpg</span>, 337 kb)</span>
<span class="file-info">(<span class="file-type">jpg</span>, 337 kB)</span>
</a>
</li>
</ul>
Expand Down

0 comments on commit 62ac811

Please sign in to comment.