Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Byte Unit Converter Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require open-southeners/byte-unit-converter
    

    Ensure your project uses PHP 8.1+ (required by the package).

  2. 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"
    
  3. 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.
  4. Where to Look First:


Implementation Patterns

Core Workflows

1. Basic Conversions

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"

2. Nearest Unit Conversion

Automatically find the most appropriate unit for display:

echo (string) ByteUnitConverter::new('1500')->nearestUnit();
// Output: "1.46 KB" (binary system default)

3. Arithmetic Operations (v3.0.0+)

Perform immutable additions/subtractions:

$result = ByteUnitConverter::new('1024')->add('512')->toMB();
echo (string) $result; // "1.50 MB"

4. Switching Systems/Units

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"

5. Rounding Control

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"

Laravel-Specific Patterns

1. Service Container Binding

Bind the converter globally for easy access:

// In AppServiceProvider::boot()
$this->app->singleton('byteConverter', function () {
    return ByteUnitConverter::new();
});

Usage:

$converter = app('byteConverter')->new('1024');

2. Form Request Validation

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;
            }),
        ],
    ];
}

3. Model Observers/Accessors

Add human-readable size attributes to Eloquent models:

// In User model
public function getDiskUsageAttribute()
{
    return (string) ByteUnitConverter::new($this->disk_usage)->nearestUnit();
}

4. API Responses

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(),
    ],
]);

5. Artisan Commands

Use in CLI tools for system monitoring:

$bytes = ByteUnitConverter::new(disk_free_space('/'));
$this->info("Free space: {$bytes->nearestUnit()}");

Integration Tips

1. Handling Large Numbers

Use strings for values > PHP_INT_MAX (e.g., "1000000000000" instead of 1000000000000):

$largeFile = ByteUnitConverter::new('1000000000000'); // String literal

2. Precision for Financial Data

Disable rounding for monetary values:

$amount = ByteUnitConverter::new('123456789')->usingBits()->asRound(false);

3. Testing

Mock the converter in unit tests:

$this->partialMock(ByteUnitConverter::class, 'new')
     ->shouldReceive('toMB')
     ->andReturn(ByteUnitConverter::new('1.5'));

4. Localization

Override number formatting (e.g., for European decimal commas):

ByteUnitConverter::numberFormat('de_DE'); // Set locale

5. Caching

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(),
    ];
});

Gotchas and Tips

Pitfalls

1. Breaking Changes in v3.0.0

  • asRound Method:
    • Old: Accepted bool (e.g., asRound(true)).
    • New: Accepts int|bool (e.g., asRound(2) or asRound(false)).
    • Fix: Update all calls to use the new signature. Default now rounds to 2 decimals.
    • Example:
      // 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
      

2. Immutable Operations Overhead

  • Methods like add(), sub(), and subtract() return new instances, which can impact performance in loops.
  • Tip: Reuse instances where possible:
    // 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();
    }
    

3. BCMath Requirement

  • The package requires the BCMath extension for high-precision operations (e.g., large numbers).
  • Check: Run 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
    
  • Fallback: For environments without BCMath, handle large numbers manually or use strings.

4. String vs. Integer Inputs

  • The package accepts strings, integers, or floats for input, but floats may lose precision for large numbers.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor