Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
FileUtility
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
0.00% covered (danger)
0.00%
0 / 1
 formatFileSize
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2declare(strict_types=1);
3
4namespace App\Utility;
5
6/**
7 * File Utility
8 *
9 * Provides common file-related utility functions.
10 */
11class FileUtility
12{
13    /**
14     * Format file size in bytes to human readable format
15     *
16     * @param int $bytes File size in bytes
17     * @param int $precision Number of decimal places
18     * @return string Formatted file size (e.g., "1.2 MB", "345 KB")
19     */
20    public static function formatFileSize(int $bytes, int $precision = 1): string
21    {
22        if ($bytes === 0) {
23            return '0 B';
24        }
25
26        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
27        $unitsCount = count($units);
28        $unitIndex = 0;
29        $size = (float)$bytes;
30
31        while ($size >= 1024 && $unitIndex < $unitsCount - 1) {
32            $size /= 1024;
33            $unitIndex++;
34        }
35
36        // Don't show decimals for bytes
37        if ($unitIndex === 0) {
38            $precision = 0;
39        }
40
41        return round($size, $precision) . ' ' . $units[$unitIndex];
42    }
43}