PHP API, Hooks & CLI
Core PHP Entry Points
Section titled “Core PHP Entry Points”<?php namespace ProcessWire;
$currency = Currency::requireInstance($wire);
// Definitions & options$base = $currency->baseCurrency();$activeList = $currency->activeCurrencies();$allowed = $currency->resolveAllowedCurrencies(['EUR', 'USD', 'GBP'], activeOnly: true);$options = $currency->currencyOptions($allowed, activeOnly: true);
// Visitor preference$code = $currency->activeCurrency();$currency->setActiveCurrency('USD');
// Money, conversion & formatting$money = $currency->money('14700.00', 'EUR');$rate = $currency->exchangeRate('EUR', 'USD', date: null, applySpread: false);$result = $currency->convert($money, 'USD', date: null, applySpread: true);$formatted = $currency->format($result->converted, 'en_US', ['show_code' => true]);
// Sync & extension points$sync = $currency->syncRates(providerKey: 'ecb', date: null, dryRun: false);$pruned = $currency->rateHistory()->pruneOlderThan(365);$currency->registerExchangeRateProvider($customProvider);$currency->setHttpTransport($customTransport);$providers = $currency->providerOptions();Hookable Methods & Registered Entries Hooks
Section titled “Hookable Methods & Registered Entries Hooks”Currency Hookable Methods (3)
Section titled “Currency Hookable Methods (3)”| Hook | Arguments & Return | Timing | What It Does |
|---|---|---|---|
Currency::resolveBlueprint |
(string $type, array $definition): array |
After | Inspects or extends internal currency-settings, currency-currencies, or currency-rate-history blueprint schemas before registration. |
Currency::afterSync |
(SyncResult $result): void |
After | Fires after a live exchange-rate synchronization completes (skipped during --dry-run). Ideal for cache invalidation or Slack/email rate alerts. |
ProcessCurrency::translations |
(): array |
After | Returns localized UI strings for the Setup -> Currencies React workspace. |
Hook Examples (site/ready.php)
Section titled “Hook Examples (site/ready.php)”<?php
declare(strict_types=1);
namespace ProcessWire;
use Totoglu\Currency\Sync\SyncResult;
// 1. Flush pricing page caches after a live exchange-rate sync$wire->addHookAfter('Currency::afterSync', function (HookEvent $event): void { /** @var SyncResult $result */ $result = $event->arguments(0); $event->wire()->cache->deleteFor('charter-pricing'); $event->wire()->log->save( 'currency-sync', sprintf('Synced %d rate(s) via %s.', count($result->updatedCodes), $result->provider) );});
// 2. Add a custom accounting code field to currency records$wire->addHookAfter('Currency::resolveBlueprint', function (HookEvent $event): void { $type = (string) $event->arguments(0); $definition = (array) $event->return; if ($type === 'currency-currencies') { $definition['fields']['erp_ledger_code'] = [ 'type' => 'text', 'label' => 'ERP Ledger Code', ]; $event->return = $definition; }});Registered Entries Lifecycle Hooks (12)
Section titled “Registered Entries Lifecycle Hooks (12)”Currency declares pull-discovery for 12 Entries::* hooks (Entries::saveReady, Entries::saved, Entries::cloneItem, Entries::trash, Entries::delete, Entries::deleteMany, Entries::restore, Entries::emptyTrash, Entries::restoreRevision, Entries::restoreRevisionFields, Entries::collectEditorExtensions, and Entries::resolveReferenceEditUrl) to enforce base-currency integrity and RBAC-checked reference links.
CLI Commands (3) & Scheduled Task (1)
Section titled “CLI Commands (3) & Scheduled Task (1)”| Command / Task | Options / Schedule | Purpose |
|---|---|---|
currency:sync |
-p/--provider, -d/--date, --dry-run, --json |
Synchronizes live or historical exchange rates from the configured or specified provider. |
currency:list |
-a/--all, --json |
Lists active currencies (or all configured currencies including drafts with --all) with spot rates and spreads. |
currency:doctor |
--json |
Audits PHP extensions (bcmath, intl, curl), blueprints, base currency integrity, and provider readiness. |
SyncExchangeRatesTask |
hourly() (schedule/SyncExchangeRatesTask.php) |
Automatically syncs rates when autoSyncEnabled is true, activeProvider !== 'manual', and syncIntervalHours has elapsed. |
Automated Testing, Mocking & Localization
Section titled “Automated Testing, Mocking & Localization”- Mocking Live FX Providers in Pest/PHPUnit: Inject a fake transport implementing
Totoglu\Currency\Contract\HttpTransportInterfacevia$currency->setHttpTransport($fakeTransport)so tests never hit live ECB or TCMB endpoints. - 6-Locale Translation Packs: Bundled CSV packs (
en,tr,de,fr,es,ru) live insite/modules/Currency/languages/. Import the matching.csvfile under Setup -> Languages -> [Language] -> Site Translation Files.
Troubleshooting
Section titled “Troubleshooting”Money::fromMajor() Throws a TypeError for a Float Value
Section titled “Money::fromMajor() Throws a TypeError for a Float Value”Money::fromMajor()intentionally rejects PHPfloatvalues to prevent IEEE-754 binary rounding drift. Pass a numeric string ('14700.00') or integer minor units (Money::fromMinor(1470000, 'EUR')).
currency:sync Fails With an Extension or SSRF Error
Section titled “currency:sync Fails With an Extension or SSRF Error”- Confirm
ext-bcmath,ext-intl, andext-curlare enabled viaphp vendor/bin/wire currency:doctor --json. - Custom
ExchangeRateProviderInterfaceendpoints must use public HTTPS URLs (WireHttpTransportblocks plain HTTP and private/loopback IPs).
Historical Date Lookup Returns a Slightly Earlier Date
Section titled “Historical Date Lookup Returns a Slightly Earlier Date”- Central banks (ECB and TCMB) do not publish rates on weekends or public holidays.
findRateOnOrBefore()andfindCrossRateOnOrBefore()automatically resolve the latest published rate on or before the requestedYYYY-MM-DDdate.
Base Currency Cannot Be Deleted or Unpublished
Section titled “Base Currency Cannot Be Deleted or Unpublished”CurrencyEntryGuardprotects the active base currency from accidental deletion, trashing, or unpublishing. Promote another currency to base first via Setup -> Currencies (./set-base/) or$currency->converter()->setBaseCurrency('USD').