Skip to content

Commit

Permalink
fix human-readable filesize (#204) (#206)
Browse files Browse the repository at this point in the history
  • Loading branch information
benwalch authored Sep 6, 2023
1 parent 1ddd6d5 commit 830e71f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 19 deletions.
28 changes: 11 additions & 17 deletions src/Service/DownloadInfoService.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,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/UnitDefault/Areas/DownloadTest.php
Original file line number Diff line number Diff line change
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 830e71f

Please sign in to comment.