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

Base Convert Laravel Package

phlib/base_convert

Drop-in replacement for PHP base_convert that supports arbitrarily large numbers without silent failures. Convert big numeric strings between bases (e.g., 10↔36) reliably via Phlib\base_convert, and round-trip large values correctly.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require phlib/base_convert
    

    Ensure your project uses PHP 7.4+ (required for this package).

  2. First Usage: Replace native base_convert() calls with the fully qualified namespace:

    use function Phlib\base_convert;
    
    // Example: Convert a large base-10 number to base-36
    $largeNumber = '12345678901234567890';
    $base36 = base_convert($largeNumber, 10, 36);
    
  3. Verify Round-Trip:

    $reconverted = base_convert($base36, 36, 10);
    var_dump($largeNumber === $reconverted); // Should return `true`
    

Where to Look First

  • README.md: Confirms the package’s purpose (handling large numbers beyond PHP’s native limits).
  • Changelog: Notes PHP 7.4+ requirement and type validation (throws InvalidArgumentException for invalid inputs).
  • Usage Examples: Demonstrates correct handling of large numbers (e.g., 20+ digits) where native base_convert() fails silently.

Implementation Patterns

Core Workflows

1. Replacing Native base_convert()

  • Pattern: Replace all base_convert() calls with the package’s version.
  • Example:
    // Before (fails for large numbers)
    $result = base_convert($largeInput, 10, 36);
    
    // After (works for large numbers)
    $result = Phlib\base_convert($largeInput, 10, 36);
    
  • Tip: Use IDE refactoring (e.g., PHPStorm’s "Rename") to replace calls globally.

2. Handling User Input

  • Pattern: Validate inputs before conversion to avoid InvalidArgumentException.
  • Example:
    use function Phlib\base_convert;
    
    function safeConvert(string $number, int $fromBase, int $toBase): string {
        if (!ctype_alnum($number)) {
            throw new \InvalidArgumentException("Input must be alphanumeric.");
        }
        return base_convert($number, $fromBase, $toBase);
    }
    

3. Base-36 for URLs/IDs

  • Pattern: Use base-36 for compact, URL-safe IDs (e.g., Laravel’s Str::uuid() or custom slugs).
  • Example:
    $id = '1234567890abcdef1234567890abcdef';
    $base36Id = base_convert($id, 10, 36); // Shorter, URL-friendly
    

4. Legacy Data Migration

  • Pattern: Migrate legacy systems storing numbers as strings (e.g., databases, APIs).
  • Example:
    $legacyData = '99999999999999999999'; // Stored as string to avoid overflow
    $processed = base_convert($legacyData, 10, 16); // Convert to hex for storage
    

Integration Tips

Laravel-Specific

  1. Service Provider Binding (Optional): Bind the function to Laravel’s container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind('base_convert', function () {
            return Phlib\base_convert(...);
        });
    }
    

    Usage:

    $result = app('base_convert')($number, $fromBase, $toBase);
    
  2. Helper Function: Add a global helper in app/Helpers/base_convert.php:

    if (!function_exists('app_base_convert')) {
        function app_base_convert(string $number, int $fromBase, int $toBase): string {
            return Phlib\base_convert($number, $fromBase, $toBase);
        }
    }
    

    Require it in composer.json autoload:

    "autoload": {
        "files": ["app/Helpers/base_convert.php"]
    }
    

Performance Considerations

  • Batch Processing: For large datasets, process conversions in chunks to avoid memory issues.
    $chunkSize = 1000;
    foreach (array_chunk($largeNumbers, $chunkSize) as $chunk) {
        array_map(fn($n) => base_convert($n, 10, 36), $chunk);
    }
    
  • Caching: Cache frequent conversions (e.g., static IDs) to avoid redundant computations.

Testing

  • Unit Tests: Test edge cases (e.g., max 64-bit integer, 100-digit numbers).
    use Phlib\base_convert;
    use PHPUnit\Framework\TestCase;
    
    class BaseConvertTest extends TestCase {
        public function testLargeNumberConversion() {
            $largeNumber = str_repeat('9', 50); // 50-digit number
            $converted = base_convert($largeNumber, 10, 36);
            $this->assertEquals($largeNumber, base_convert($converted, 36, 10));
        }
    }
    
  • Benchmarking: Compare performance against native base_convert() for small/medium numbers (should be similar).

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch:

    • Error: Class 'Phlib\base_convert' not found or TypeError on PHP <7.4.
    • Fix: Upgrade PHP to 7.4+ or use a polyfill for older versions (though none exists for this package).
  2. Silent Failures vs. Exceptions:

    • Gotcha: Native base_convert() fails silently for invalid inputs (e.g., non-alphanumeric strings). This package throws InvalidArgumentException.
    • Fix: Wrap calls in try-catch or validate inputs upstream:
      try {
          $result = base_convert($input, 10, 36);
      } catch (InvalidArgumentException $e) {
          // Handle error (e.g., log, fallback, or rethrow)
      }
      
  3. Base Limitations:

    • Gotcha: The package only supports bases 2–36. Attempting to use bases outside this range will throw an exception.
    • Fix: Validate bases before calling:
      if ($fromBase < 2 || $fromBase > 36 || $toBase < 2 || $toBase > 36) {
          throw new \InvalidArgumentException("Bases must be between 2 and 36.");
      }
      
  4. Memory Issues:

    • Gotcha: Extremely large inputs (e.g., >1MB strings) may cause memory exhaustion.
    • Fix: Process in chunks or use streaming for very large data.
  5. Laravel Facade Conflicts:

    • Gotcha: If your app uses use function base_convert, the package’s function may not override it due to function aliasing.
    • Fix: Use the fully qualified namespace (Phlib\base_convert) or alias it in composer.json:
      "extra": {
          "aliases": {
              "base_convert": "Phlib\\base_convert"
          }
      }
      

Debugging Tips

  1. Validate Inputs:

    • Ensure inputs are strictly alphanumeric (no spaces, symbols, or signs):
      if (!ctype_alnum($number)) {
          throw new \InvalidArgumentException("Input must be alphanumeric.");
      }
      
  2. Check Base Ranges:

    • Confirm $fromBase and $toBase are between 2 and 36:
      if ($fromBase < 2 || $fromBase > 36 || $toBase < 2 || $toBase > 36) {
          throw new \InvalidArgumentException("Bases must be between 2 and 36.");
      }
      
  3. Round-Trip Testing:

    • Verify conversions are lossless by reconverting back:
      $original = '12345678901234567890';
      $converted = base_convert($original, 10, 36);
      $reconverted = base_convert($converted, 36, 10);
      assert($original === $reconverted, "Round-trip conversion failed!");
      
  4. Log Large Conversions:

    • Log inputs/outputs for large or critical conversions to debug issues:
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony