## Getting Started
### Minimal Setup
1. **Installation**
```bash
composer require gabrielelana/byte-units
No service provider or facade needed—use the ByteUnits class directly.
First Use Case: Parsing Bytes
use ByteUnits\ByteUnits;
$bytes = ByteUnits::parse('1.5GB'); // Returns integer (1610612736)
$bytes = ByteUnits::parse('1KB'); // Returns integer (1024)
First Use Case: Formatting Bytes
$formatted = ByteUnits::format(1500000000); // Returns string "1.43GB"
$formatted = ByteUnits::format(1024, 2); // Returns string "1.00KB" (2 decimal places)
First Use Case: Conversion
$kb = ByteUnits::convert(1500000000, 'MB', 'KB'); // Returns integer (1464800000)
ByteUnits class methods:
parse(string $value) – Converts human-readable strings (e.g., "2.5TB") to bytes.format(int $bytes, int $decimals = 2) – Converts bytes to human-readable strings.convert(int $bytes, string $fromUnit, string $toUnit) – Converts between units (e.g., MB → GB).ByteUnits::KB, ByteUnits::TB). Use these for type safety in conversions.// Parse uploaded file size from request
$maxSize = ByteUnits::parse('10MB');
if ($request->file('avatar')->getSize() > $maxSize) {
throw new \Exception('File too large');
}
// Format file size for user feedback
$formattedSize = ByteUnits::format($fileSize, 1);
return response()->json(['size' => $formattedSize]);
Store file sizes in bytes (as integers) for accurate comparisons, but display formatted values to users:
// Model: App\Models\File
public function getFormattedSizeAttribute() {
return ByteUnits::format($this->attributes['size'], 2);
}
Parse command-line arguments for byte values:
$limit = ByteUnits::parse($this->argument('limit')); // e.g., `--limit=500MB`
Normalize byte values in responses:
return [
'files' => array_map(fn($file) => [
'name' => $file->name,
'size' => ByteUnits::format($file->size),
], $files)
];
Validation: Use the package in Laravel validation rules with type safety:
use Illuminate\Validation\Rule;
$validator = Validator::make($request->all(), [
'file_size' => [
'required',
function ($attribute, $value, $fail) {
$bytes = ByteUnits::parse($value);
if ($bytes === false || $bytes > ByteUnits::parse('5GB')) {
$fail('Invalid size format or exceeds limit.');
}
},
],
]);
Localization: Override formatting for non-English locales by extending the class:
class LocalizedByteUnits extends ByteUnits {
public static function format(int $bytes, int $decimals = 2): string {
$formatted = parent::format($bytes, $decimals);
return str_replace(['GB', 'MB', 'KB'], ['Go', 'Mo', 'Ko'], $formatted);
}
}
Caching: Cache parsed/format results if used frequently in loops (e.g., processing large file lists).
Parsing Edge Cases
ByteUnits::parse() returns false on invalid input (e.g., "1.5XB"). Always validate:
$bytes = ByteUnits::parse($input);
if ($bytes === false) { /* handle error */ }
$bytes = ByteUnits::parse(trim($input));
Unit Case Sensitivity
$bytes = ByteUnits::parse(strtoupper($input));
Floating-Point Precision
$bytes = round(ByteUnits::parse('1.5GB'));
Unsupported Units
ByteUnits::B for binary units if needed.Decimal Places in Formatting
format() method rounds to the specified decimal places. For exact values (e.g., invoicing), use convert() to an integer unit (e.g., bytes or KB) and avoid floating-point display.$bytes = ByteUnits::parse('10MB');
\Log::debug("Parsed bytes: {$bytes} (expected: " . (10 * 1024 * 1024) . ")");
$mbToBytes = ByteUnits::convert(1, 'MB', 'B'); // Should be 1048576
$bytesToMb = ByteUnits::convert(1048576, 'B', 'MB'); // Should be 1
Custom Units Extend the class to support non-standard units (e.g., "MiB"):
class ExtendedByteUnits extends ByteUnits {
protected static $units = [
...parent::$units,
'MiB' => 1024 * 1024,
'GiB' => 1024 * 1024 * 1024,
];
}
Unit Aliases Add aliases for common abbreviations:
ByteUnits::parse('1M'); // Treat as 1MB
Override the parse() method to handle aliases before standard parsing.
Localization Replace unit symbols in formatted output (e.g., "GB" → "Go"):
$formatted = ByteUnits::format($bytes);
$formatted = preg_replace('/(GB|MB|KB)/', ['Go', 'Mo', 'Ko'], $formatted);
Binary vs. Decimal The package uses decimal units (1KB = 1000B). For binary units (1KiB = 1024B), use a wrapper:
class BinaryByteUnits extends ByteUnits {
public static function parse(string $value) {
$value = str_replace(['KB', 'MB', 'GB', 'TB'], ['KiB', 'MiB', 'GiB', 'TiB'], $value);
return parent::parse($value);
}
protected static $units = [
'KiB' => 1024,
'MiB' => 1024 * 1024,
'GiB' => 1024 * 1024 * 1024,
'TiB' => 1024 * 1024 * 1024 * 1024,
];
}
ByteUnits class directly.How can I help you explore Laravel packages today?