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

Iso4217 Laravel Package

alcohol/iso4217

Lightweight PHP library with ISO 4217 currency data. Look up currencies by alpha-3 (e.g., EUR) or numeric code (978), or retrieve the full list, including name, minor unit exponent, and associated country codes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require alcohol/iso4217
    

    Add to composer.json under require or require-dev if only for testing.

  2. First Use:

    use Alcohol\ISO4217;
    
    $iso4217 = new ISO4217();
    $currency = $iso4217->getByAlpha3('USD');
    

    Verify the response structure:

    // Expected output:
    // [
    //     'name' => 'US Dollar',
    //     'alpha3' => 'USD',
    //     'numeric' => '840',
    //     'exp' => 2,
    //     'country' => ['US', 'EC', 'PA', ...]
    // ]
    
  3. Key Methods:

    • getByAlpha3(string $code): Fetch by 3-letter code (e.g., 'EUR').
    • getByNumeric(string $code): Fetch by numeric code (e.g., '978').
    • getAll(): Return all currencies as an associative array (keyed by alpha3).

Implementation Patterns

Core Workflows

  1. Currency Validation:

    $iso4217 = new ISO4217();
    try {
        $currency = $iso4217->getByAlpha3('XYZ'); // Throws \InvalidArgumentException
    } catch (\InvalidArgumentException $e) {
        // Handle invalid currency (e.g., log or show user-friendly message)
    }
    
  2. Country-Currency Mapping:

    // Get all countries using a specific currency (e.g., EUR)
    $eurCountries = $iso4217->getByAlpha3('EUR')['country'];
    
  3. Dynamic Formatting:

    // Format currency symbol dynamically (e.g., for display)
    $currency = $iso4217->getByAlpha3('JPY');
    $symbol = $currency['alpha3']; // 'JPY' (use a separate library like `moneyphp/money` for rendering)
    
  4. Integration with Laravel:

    • Service Provider:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(ISO4217::class);
      }
      
    • Facade (Optional):
      // app/Facades/Iso4217.php
      public static function getByAlpha3(string $code) {
          return app(ISO4217::class)->getByAlpha3($code);
      }
      
      Register in config/app.php under aliases.
  5. Caching:

    // Cache all currencies for performance (e.g., in a command or service)
    $currencies = Cache::remember('iso4217.all', now()->addYear(), function () {
        return app(ISO4217::class)->getAll();
    });
    
  6. Testing:

    // Example test case
    public function testGetByAlpha3()
    {
        $iso4217 = new ISO4217();
        $this->assertEquals('US Dollar', $iso4217->getByAlpha3('USD')['name']);
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Currencies:

    • The package excludes deprecated codes (e.g., VEF for Venezuelan Bolívar Fuerte). Use VES instead.
    • Check the excluded list for edge cases.
  2. Case Sensitivity:

    • Alpha3 codes are case-sensitive (e.g., 'USD' works, 'Usd' throws an exception).
    • Numeric codes are strings (e.g., '840' not 840).
  3. PHP Version:

    • Requires PHP 8+ (dropped support for PHP 7.3 and lower in v4.0.0).
    • Test thoroughly if using older PHP versions (though unlikely in Laravel).
  4. Data Accuracy:

    • The library is static (data is bundled with the package). For real-time updates, consider:
      • Forking the repo and updating the data manually.
      • Using an API like ISO 4217 JSON as a fallback.
  5. Performance:

    • getAll() loads ~180 currencies into memory. Cache the result if called frequently:
      Cache::rememberForever('iso4217.all', fn() => $iso4217->getAll());
      

Debugging Tips

  1. Invalid Codes:

    • Use getAll() to inspect available codes during development.
    • Log the full response for debugging:
      error_log(print_r($iso4217->getAll(), true));
      
  2. Type Hints:

    • Methods return array or throw \InvalidArgumentException. Use PHP 8’s strict typing (declare(strict_types=1)) to catch issues early.
  3. Testing Edge Cases:

    • Test with excluded codes (e.g., 'XDR' for Special Drawing Rights) to ensure your app handles them gracefully.

Extension Points

  1. Custom Data Sources:

    • Override the ISO4217 class to load data from an external API or database:
      class CustomISO4217 extends ISO4217 {
          protected function loadData(): array {
              return Cache::get('custom_iso4217_data') ?? [];
          }
      }
      
  2. Validation Rules:

    • Integrate with Laravel’s validation:
      use Illuminate\Validation\Rule;
      
      $rules = [
          'currency' => ['required', Rule::in(array_keys($iso4217->getAll()))],
      ];
      
  3. Localization:

    • Extend the response to include localized names (e.g., 'name_es' for Spanish):
      $currency = $iso4217->getByAlpha3('EUR');
      // Manually merge localized data if needed
      $currency['name_es'] = 'Euro';
      
  4. Event Listeners:

    • Trigger events when currencies are fetched (e.g., for analytics):
      event(new CurrencyFetched($currency));
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui