open-southeners/byte-unit-converter
PHP 8.1+ utility to convert byte sizes between multiple units with no dependencies. Inspired by macOS ByteCountFormatter, it helps format and convert storage values consistently for apps and libraries.
Installation:
composer require open-southeners/byte-unit-converter
Ensure your project uses PHP 8.1+ (required by the package).
First Use Case: Convert a file size to a human-readable format in a Laravel controller or service:
use OpenSoutheners\ByteUnitConverter\ByteUnitConverter;
$fileSize = ByteUnitConverter::new('1500000')->toMB();
echo (string) $fileSize; // Output: "1.43 MB"
Key Classes:
ByteUnitConverter: Main class for conversions.MetricSystem: Enum for binary (Binary) or decimal (Decimal) systems.ByteUnit: Enum for units like B, KB, MB, etc.DataUnit: Enum for Bytes or Bits.Where to Look First:
Use to* methods (e.g., toKB(), toMB(), toGB()) to convert to specific units. Returns an instance; cast to (string) for display:
$bytes = ByteUnitConverter::new('1024');
echo (string) $bytes->toKiB(); // "1.00 KiB"
Automatically find the most appropriate unit for display:
echo (string) ByteUnitConverter::new('1500')->nearestUnit();
// Output: "1.46 KB" (binary system default)
Perform immutable additions/subtractions:
$result = ByteUnitConverter::new('1024')->add('512')->toMB();
echo (string) $result; // "1.50 MB"
Toggle between binary/decimal systems or bytes/bits:
$bytes = ByteUnitConverter::new('1024')->usingBits();
echo (string) $bytes->toKibit(); // "8.00 Kibit"
$decimal = ByteUnitConverter::new('1000')->using(MetricSystem::Decimal);
echo (string) $decimal->toKB(); // "1.00 KB"
Round results to integers or specify decimal places:
// Default: rounds to 2 decimal places
echo (string) ByteUnitConverter::new('1924')->asRound()->toKiB(); // "2 KiB"
// Custom precision (v3.0.0+)
echo (string) ByteUnitConverter::new('1924')->asRound(1)->toKiB(); // "2.0 KiB"
Bind the converter globally for easy access:
// In AppServiceProvider::boot()
$this->app->singleton('byteConverter', function () {
return ByteUnitConverter::new();
});
Usage:
$converter = app('byteConverter')->new('1024');
Validate file sizes in requests:
use Illuminate\Validation\Rule;
public function rules()
{
return [
'file' => [
'required',
'max:1048576', // 1MB in bytes
Rule::function('max_size', function ($attribute, $value) {
$maxBytes = ByteUnitConverter::new('1MB')->toBytes();
return $value->getSize() <= $maxBytes;
}),
],
];
}
Add human-readable size attributes to Eloquent models:
// In User model
public function getDiskUsageAttribute()
{
return (string) ByteUnitConverter::new($this->disk_usage)->nearestUnit();
}
Format numeric responses (e.g., storage metrics) for APIs:
return response()->json([
'storage' => [
'total' => (string) ByteUnitConverter::new($totalBytes)->toGB(),
'used' => (string) ByteUnitConverter::new($usedBytes)->toGB(),
],
]);
Use in CLI tools for system monitoring:
$bytes = ByteUnitConverter::new(disk_free_space('/'));
$this->info("Free space: {$bytes->nearestUnit()}");
Use strings for values > PHP_INT_MAX (e.g., "1000000000000" instead of 1000000000000):
$largeFile = ByteUnitConverter::new('1000000000000'); // String literal
Disable rounding for monetary values:
$amount = ByteUnitConverter::new('123456789')->usingBits()->asRound(false);
Mock the converter in unit tests:
$this->partialMock(ByteUnitConverter::class, 'new')
->shouldReceive('toMB')
->andReturn(ByteUnitConverter::new('1.5'));
Override number formatting (e.g., for European decimal commas):
ByteUnitConverter::numberFormat('de_DE'); // Set locale
Cache frequent conversions (e.g., for dashboard metrics):
$cacheKey = 'storage_metrics_' . $userId;
$metrics = Cache::remember($cacheKey, now()->addHours(1), function () use ($userId) {
return [
'used' => (string) ByteUnitConverter::new($usedBytes)->toGB(),
'total' => (string) ByteUnitConverter::new($totalBytes)->toGB(),
];
});
asRound Method:
bool (e.g., asRound(true)).int|bool (e.g., asRound(2) or asRound(false)).// Old (breaks in v3.0.0)
$converter->asRound(true);
// New
$converter->asRound(); // Default: 2 decimals
$converter->asRound(1); // Round to 1 decimal
$converter->asRound(false); // No rounding
add(), sub(), and subtract() return new instances, which can impact performance in loops.// Bad: Creates new instances in loop
foreach ($files as $file) {
$size = ByteUnitConverter::new($file->size)->toMB();
}
// Good: Reuse converter
$converter = ByteUnitConverter::new();
foreach ($files as $file) {
$size = (string) $converter->new($file->size)->toMB();
}
php -m | grep bcmath to verify. If missing, install via:
# Ubuntu/Debian
sudo apt-get install php-bcmath
# RHEL/CentOS
sudo yum install php-bcmath
How can I help you explore Laravel packages today?