|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Runthis\Media\Attributes; |
| 4 | + |
| 5 | +use function floor; |
| 6 | +use function in_array; |
| 7 | +use function log; |
| 8 | +use function pow; |
| 9 | +use function sprintf; |
| 10 | +use function str_ireplace; |
| 11 | +use function str_replace; |
| 12 | +use function str_split; |
| 13 | +use function strtolower; |
| 14 | + |
| 15 | +class Size |
| 16 | +{ |
| 17 | + /** |
| 18 | + * Set the bytes. |
| 19 | + */ |
| 20 | + public function __construct(public int $bytes) |
| 21 | + { |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Format file size provided from bytes. |
| 26 | + * |
| 27 | + * Options: |
| 28 | + * l: lowercase suffix (12.45 mb instead of 12.45 MB) |
| 29 | + * s: spacing omitted (12.45MB instead of 12.45 MB) |
| 30 | + * b: Ending "B" removed (12.45 M instead of 12.45 MB) |
| 31 | + */ |
| 32 | + public function pretty(string $options = ''): string |
| 33 | + { |
| 34 | + $format = '%.02F %sB'; |
| 35 | + $suffix = 'BKMGTPEZY'; |
| 36 | + $options = str_split($options); |
| 37 | + |
| 38 | + // Set byte formatting |
| 39 | + $format = $this->bytes < 1024 ? (in_array('b', $options, true) ? '%.0F' : '%.0F %s') : $format; |
| 40 | + |
| 41 | + // Lowercase |
| 42 | + $suffix = in_array('l', $options, true) ? strtolower($suffix) : $suffix; |
| 43 | + $format = in_array('l', $options, true) ? str_replace('B', 'b', $format) : $format; |
| 44 | + |
| 45 | + // No ending "b" |
| 46 | + $format = in_array('b', $options, true) ? str_ireplace('b', '', $format) : $format; |
| 47 | + |
| 48 | + // No spacing |
| 49 | + $format = in_array('s', $options, true) ? str_replace(' ', '', $format) : $format; |
| 50 | + |
| 51 | + $index = floor(log($this->bytes) / log(1024)); |
| 52 | + |
| 53 | + return sprintf($format, $this->bytes / pow(1024, $index), str_split($suffix)[$index]); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Just send back the bytes. |
| 58 | + */ |
| 59 | + public function __toString(): string |
| 60 | + { |
| 61 | + return (string) $this->bytes; |
| 62 | + } |
| 63 | +} |
0 commit comments