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 Units Laravel Package

gabrielelana/byte-units

View on GitHub
Deep Wiki
Context7
## Getting Started
### Minimal Setup
1. **Installation**
   ```bash
   composer require gabrielelana/byte-units

No service provider or facade needed—use the ByteUnits class directly.

  1. First Use Case: Parsing Bytes

    use ByteUnits\ByteUnits;
    
    $bytes = ByteUnits::parse('1.5GB'); // Returns integer (1610612736)
    $bytes = ByteUnits::parse('1KB');   // Returns integer (1024)
    
  2. 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)
    
  3. First Use Case: Conversion

    $kb = ByteUnits::convert(1500000000, 'MB', 'KB'); // Returns integer (1464800000)
    

Where to Look First

  • API Docs: The package is self-documenting. Check the 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).
  • Unit Constants: Supported units are defined as class constants (e.g., ByteUnits::KB, ByteUnits::TB). Use these for type safety in conversions.
  • Type Hinting: The new release adds PHP 7.2+ type hints for better IDE autocompletion and static analysis. IDEs will now suggest valid method signatures and parameters.

Implementation Patterns

Common Workflows

1. File Size Handling in Controllers/Requests

// 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]);

2. Database Storage Optimization

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

3. CLI/Artisan Commands

Parse command-line arguments for byte values:

$limit = ByteUnits::parse($this->argument('limit')); // e.g., `--limit=500MB`

4. API Responses

Normalize byte values in responses:

return [
    'files' => array_map(fn($file) => [
        'name' => $file->name,
        'size' => ByteUnits::format($file->size),
    ], $files)
];

Integration Tips

  • 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).


Gotchas and Tips

Pitfalls

  1. 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 */ }
      
    • Leading/trailing whitespace in strings may cause parsing failures. Trim inputs:
      $bytes = ByteUnits::parse(trim($input));
      
  2. Unit Case Sensitivity

    • Units are case-insensitive (e.g., "gb" = "GB"), but mixed case (e.g., "Gb") may fail silently. Standardize units:
      $bytes = ByteUnits::parse(strtoupper($input));
      
  3. Floating-Point Precision

    • Parsing values like "1.5GB" may introduce floating-point inaccuracies when converted to bytes. Round results if needed:
      $bytes = round(ByteUnits::parse('1.5GB'));
      
  4. Unsupported Units

    • Only standard units (B, KB, MB, GB, TB, PB) are supported. Custom units (e.g., "MiB") will fail. Use ByteUnits::B for binary units if needed.
  5. Decimal Places in Formatting

    • The 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.

Debugging Tips

  • Check Parsed Values: Log parsed bytes to verify correctness:
    $bytes = ByteUnits::parse('10MB');
    \Log::debug("Parsed bytes: {$bytes} (expected: " . (10 * 1024 * 1024) . ")");
    
  • Unit Conversion Debugging: Validate conversions with known values:
    $mbToBytes = ByteUnits::convert(1, 'MB', 'B'); // Should be 1048576
    $bytesToMb = ByteUnits::convert(1048576, 'B', 'MB'); // Should be 1
    

Extension Points

  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,
        ];
    }
    
  2. Unit Aliases Add aliases for common abbreviations:

    ByteUnits::parse('1M'); // Treat as 1MB
    

    Override the parse() method to handle aliases before standard parsing.

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

Config Quirks

  • No Configuration File: The package is stateless and requires no configuration. All behavior is controlled via method calls.
  • Static Usage: Methods are static, so no dependency injection is needed. However, for testing, mock the ByteUnits class directly.
  • PHP Version Compatibility: The package now explicitly supports PHP 7.2+ due to added type hints
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium