Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
22 / 22 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| AssetFacts | |
100.00% |
22 / 22 |
|
100.00% |
3 / 3 |
12 | |
100.00% |
1 / 1 |
| size | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
5 | |||
| extension | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| line | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\Panel; |
| 6 | |
| 7 | use Cosray\Assets\Asset; |
| 8 | use NumberFormatter; |
| 9 | |
| 10 | /** How the panel states an asset's file facts: size, extension, dimensions. */ |
| 11 | final class AssetFacts |
| 12 | { |
| 13 | /** A byte count in the largest fitting unit, formatted for the locale. */ |
| 14 | public static function size(int $bytes, string $locale): string |
| 15 | { |
| 16 | $units = ['B', 'KB', 'MB', 'GB', 'TB']; |
| 17 | $size = (float) max(0, $bytes); |
| 18 | $unit = 0; |
| 19 | |
| 20 | while ($size >= 1024 && $unit < (count($units) - 1)) { |
| 21 | $size /= 1024; |
| 22 | $unit++; |
| 23 | } |
| 24 | |
| 25 | $formatter = new NumberFormatter($locale, NumberFormatter::DECIMAL); |
| 26 | $digits = $unit === 0 ? 0 : 1; |
| 27 | $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $digits); |
| 28 | $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $digits); |
| 29 | $value = $formatter->format($size); |
| 30 | |
| 31 | return ($value === false ? (string) $size : $value) . ' ' . $units[$unit]; |
| 32 | } |
| 33 | |
| 34 | /** Up to five characters of the filename's extension, upper case. */ |
| 35 | public static function extension(string $filename): string |
| 36 | { |
| 37 | $dot = strrpos($filename, '.'); |
| 38 | |
| 39 | return $dot === false ? '' : strtoupper(substr($filename, $dot + 1, 5)); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * The one-line fact row under an asset name: pixel dimensions when |
| 44 | * known, otherwise the extension, then the size, as in |
| 45 | * "2400 × 1600 px · 842 KB". |
| 46 | */ |
| 47 | public static function line(Asset $asset, string $locale): string |
| 48 | { |
| 49 | $parts = []; |
| 50 | |
| 51 | if ($asset->width && $asset->height) { |
| 52 | $parts[] = "{$asset->width} × {$asset->height} px"; |
| 53 | } elseif (self::extension($asset->filename) !== '') { |
| 54 | $parts[] = self::extension($asset->filename); |
| 55 | } |
| 56 | |
| 57 | if ($asset->bytes !== null) { |
| 58 | $parts[] = self::size($asset->bytes, $locale); |
| 59 | } |
| 60 | |
| 61 | return implode(' · ', $parts); |
| 62 | } |
| 63 | } |