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

Iso Currencies Laravel Package

moneyphp/iso-currencies

Up-to-date ISO 4217 currency list for MoneyPHP, sourced from the official ISO 4217 Maintenance Agency (currency-iso.org). Includes tooling to fetch and update the currency dataset via Composer for use with moneyphp/money.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package Add to your composer.json and run:

    composer require moneyphp/iso-currencies
    
  2. Fetch Latest Currencies Update the currency data from the official ISO source:

    composer fetch-update
    

    (This populates the data/current.json file with the latest ISO 4217 definitions.)

  3. Basic Usage with MoneyPHP If using moneyphp/money, integrate the CurrencyRepository:

    use Money\Currency\CurrencyRepository;
    use Money\Currency\ISOCurrency;
    
    $repository = new CurrencyRepository();
    $eur = $repository->getCurrency('EUR'); // Returns ISOCurrency instance
    
  4. Standalone Validation For non-MoneyPHP use (e.g., form validation), access the raw data:

    $currencies = include __DIR__.'/vendor/moneyphp/iso-currencies/data/current.php';
    $isValid = isset($currencies['EUR']); // Check if currency exists
    

Implementation Patterns

Core Workflows

1. Currency Validation in Laravel

Use the package to validate user inputs (e.g., API payloads, forms):

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'currency' => [
        'required',
        function ($attribute, $value, $fail) {
            $currencies = include __DIR__.'/vendor/moneyphp/iso-currencies/data/current.php';
            if (!isset($currencies[$value])) {
                $fail('Invalid currency code.');
            }
        },
    ],
]);

2. Service Container Binding (Laravel)

Bind the CurrencyRepository for dependency injection:

// config/app.php
'bindings' => [
    Money\Currency\CurrencyRepository::class => function ($app) {
        return new Money\Currency\CurrencyRepository();
    },
];

Now inject it into controllers/services:

public function __construct(private CurrencyRepository $currencyRepo) {}

3. Historical Currency Handling

Check if a currency is historic (e.g., BGN post-2026):

$currency = $currencyRepo->getCurrency('BGN');
if ($currency->isHistorical()) {
    // Handle legacy logic (e.g., log warning, redirect to EUR)
}

4. Dynamic Currency Lists

Fetch all currencies for dropdowns or reporting:

$allCurrencies = $currencyRepo->getAll();
$currencyCodes = array_keys($allCurrencies);

Integration Tips

With MoneyPHP

  • Replace hardcoded currency arrays with CurrencyRepository calls.
  • Use ISOCurrency objects for type safety and metadata (e.g., getSymbol(), getSubUnit()).

With Laravel Validation

  • Create a custom rule for ISO 4217 compliance:
    use Illuminate\Validation\Rule;
    
    $rules = [
        'currency' => ['required', Rule::in(array_keys($currencies))],
    ];
    

Caching

  • Cache the current.php file to avoid repeated file reads:
    $currencies = Cache::remember('iso_currencies', now()->addDays(7), function () {
        return include __DIR__.'/vendor/moneyphp/iso-currencies/data/current.php';
    });
    

Testing

  • Mock the CurrencyRepository in tests:
    $this->app->instance(CurrencyRepository::class, $mockRepository);
    

Gotchas and Tips

Pitfalls

  1. Static Data Updates

    • Issue: composer fetch-update must be run manually or via CI/CD to sync with ISO changes.
    • Fix: Add a post-install script to composer.json:
      "scripts": {
          "post-install-cmd": [
              "@php -r \"if (!file_exists(__DIR__.'/vendor/moneyphp/iso-currencies/data/current.json')) { shell_exec('composer fetch-update'); }\""
          ]
      }
      
  2. Historical Currency Logic

    • Issue: Historical flags (e.g., BGN) may break legacy code expecting active currencies.
    • Fix: Validate historical status before processing:
      if ($currency->isHistorical() && $request->is('admin')) {
          throw new \RuntimeException('Currency deprecated; use EUR instead.');
      }
      
  3. File Path Assumptions

    • Issue: The package assumes data/current.php is in vendor/. Custom paths require manual inclusion.
    • Fix: Use realpath() or environment variables for paths.
  4. PHP Version Lock

    • Issue: Requires PHP 8.1+. Older versions will fail.
    • Fix: Update php-version in composer.json or use a wrapper for legacy apps.

Debugging

  1. Missing Currencies

    • Run composer fetch-update to sync with ISO.
    • Check data/current.json for errors (e.g., malformed YAML).
  2. Deprecated Currency Errors

    • Use isHistorical() to handle transitions gracefully:
      if ($currency->isHistorical()) {
          logger()->warning("Using deprecated currency: {$currency->getCode()}");
      }
      
  3. Performance Bottlenecks

    • Avoid loading current.php on every request. Cache the result or lazy-load:
      static $currencies = null;
      if (is_null(self::$currencies)) {
          self::$currencies = include __DIR__.'/vendor/.../current.php';
      }
      

Extension Points

  1. Custom Currency Metadata

    • Extend ISOCurrency or wrap the repository to add fields (e.g., getRegion()):
      class ExtendedCurrency extends ISOCurrency {
          public function getRegion(): string {
              return $this->getAttribute('region', 'Global');
          }
      }
      
  2. Database Sync

    • Seed a currencies table on app boot:
      $currencies = include __DIR__.'/vendor/.../current.php';
      foreach ($currencies as $code => $data) {
          DB::table('currencies')->updateOrCreate(
              ['code' => $code],
              ['name' => $data['name'], 'symbol' => $data['symbol']]
          );
      }
      
  3. API Wrapper

    • Expose currency data via a Laravel API resource:
      Route::get('/api/currencies', function () {
          return response()->json(
              include __DIR__.'/vendor/moneyphp/iso-currencies/data/current.php'
          );
      });
      
  4. Localization

    • Override currency names/symbols for specific locales:
      $currencyRepo->setLocale('fr_FR'); // Hypothetical; may require custom logic
      

Configuration Quirks

  1. Composer Scripts

    • Ensure composer fetch-update has write permissions to vendor/.
    • For CI/CD, add to composer.json:
      "scripts": {
          "fetch-update": "php -r \"file_put_contents(__DIR__.'/vendor/moneyphp/iso-currencies/data/current.json', file_get_contents('https://raw.githubusercontent.com/moneyphp/iso-currencies/main/data/current.json'));\""
      }
      
  2. Symfony YAML Support

    • If using Symfony, ensure symfony/yaml is installed (v8.0+):
      composer require symfony/yaml:^8.0
      
  3. Historical Data Retention

    • The package does not store historical versions. For auditing, log changes:
      $oldCurrencies = include __DIR__.'/vendor/.../current.php';
      $newCurrencies = include __DIR__.'/vendor/.../current.php';
      $changes = array_diff_assoc($oldCurrencies, $newCurrencies);
      logger()->info('Currency changes detected:', $changes);
      
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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