lukaszzychal / nbp-api-client-php
PHP client library for National Bank of Poland (NBP) Web API. Provides access to Polish currency exchange rates, gold prices, and financial data. Features current and historical rates, XML/JSON support, error handling, and caching.
Package info
github.com/lukaszzychal/nbp-api-client-php
pkg:composer/lukaszzychal/nbp-api-client-php
Requires
- php: >=8.1
- ext-bcmath: *
- psr/cache: ^3.0
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.0 || ^2.0
- psr/log: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- nyholm/psr7: ^1.8
- phpstan/phpstan: ^1.10 || ^2.0
- phpunit/phpunit: ^10.0 || ^11.0
- symfony/http-client: ^6.0 || ^7.0
README
馃嚞馃嚙 English Version
A PHP library executing fast HTTP requests to the open API of the National Bank of Poland (NBP). Built with full compatibility with PHP-FIG standards (PSR-3, PSR-6, PSR-7, PSR-17, PSR-18) using modern Data Transfer Objects (DTOs) instead of raw JSON arrays.
Designed using a strict TDD environment, annotated for integration tests (Classicist Approach), maximum static analysis level (PHPStan: MAX), and compliant with PER-CS 2.0. It features a defensive fallback logic with a Retry Strategy (up to 3 retries on NBP server drops / 500+ status codes) and supports processing via injected PSR logger queues.
Installation
For proper operation, it requires a set of virtual clients implementing PSR-17 and PSR-18 standards. You can use Guzzle or the Symfony variant with Nyholm.
composer require lukaszzychal/nbp-api-client-php
composer require symfony/http-client nyholm/psr7 # Example client dependency using Symfony mechanics
Basic Client Usage
The library exposes a powerful classifier for operations with the main instance object NbpApiClient:
use LukaszZychal\NbpApiClient\Client\NbpApiClient; use Nyholm\Psr7\Factory\Psr17Factory; use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpClient\Psr18Client; $httpClient = new Psr18Client(HttpClient::create()); $requestFactory = new Psr17Factory(); $client = new NbpApiClient($httpClient, $requestFactory); // Injecting Cache and Logger // $client->setLogger($myPsr3Logger); // PSR-3: info, network errors, warnings // $client->setCache($myPsr6CacheItemPool, 21600); // Enable PSR-6 cache with 6h TTL // $client->disableCache(); // Disable cache at runtime // See docs/developer_usage_guide.md#5-psr-6-caching for full details
Features
Currently, the client supports:
- Currency Exchange Tables (
getCurrencyTable,getCurrencyTableForDate,getCurrencyTableForDateRange). Argument 1 in tables must indicate the table letter ("A", "B", "C"). - Gold Prices (
getGoldPrices,getGoldPricesForDate,getGoldPricesForDateRange).
All procedures returning a result set, e.g., $client->getGoldPrices(), are structured as native models rather than nested arrays:
- The returned record is
LukaszZychal\NbpApiClient\Model\CurrencyTableorGoldPrice. - Inside the Table, there are promoted attributes and an array holding repeated
CurrencyRateobjects.
Currency Calculator ("Cross-Rates")
The tool comes with a default pre-built currency calculator using the Polish Zloty (PLN) as the fixed point for NBP standard derivations. It requires an objective table generated from the classic client instantiated above.
use LukaszZychal\NbpApiClient\Calculator\CurrencyCalculator; // Assuming `$tables` was fetched by NbpApiClient from Table A... $calculator = new CurrencyCalculator(); $amount = 1000.0; $usdAmount = $calculator->convert($amount, 'PLN', 'USD', $tables[0]); # Calculates the exchange for 1000 PLN to USD using the NBP reference rate
Framework Integration
For detailed instructions on how to integrate this library with Laravel or Symfony, please refer to the Developer Usage Guide.
For complete information on PSR-6 caching (enabling, disabling, TTL, available adapters) see the Caching section.
Dev Mode (Integration Tests and Static Analysis)
The system is protected with a full integration suite using PHPUnit. Unit tests (for the calculator) and rigorous integration logic tested via injected Mock FakeHttpClient do not hit the external interface outside the designated Contract Tests area, operating mostly on simulated static files.
composer run test(Unit and integration DTO behavior testing)composer run test:contract(Real HTTP call against live NBP framework from Github Actions pipeline to verify contract compliance)composer run analyze(PHPStan 8/8)composer run csandcs:fix(PER CS-2.0 Control).
馃嚨馃嚤 Wersja Polska
Biblioteka PHP realizuj膮ca szybkie zapytania protoko艂em HTTP do otwartego interfejsu Narodowego Banku Polskiego. Skonstruowania z my艣l膮 o zachowaniu pe艂ni kompatybilno艣ci ze standardami (PSR-3, PSR-6, PSR-7, PSR-17, PSR-18) z nowoczesnym podej艣ciem wykorzystuj膮cym modele DTO bez surowych wynik贸w JSON.
Zaprojektowana w rygorystycznym 艣rodowisku TDD i zaanotowana pod k膮tem test贸w integracyjnych (Classicist Approach), statycznej analizy typu (PHPStan: MAX) oraz sprowadzona do zgodno艣ci z PER-CS 2.0. Posiada obronny mechanizm logiki awaryjnej z Retry Strategy (3 ponowienia w obliczu spadku serwer贸w NBP API / 500+ status code) jak i obrabianie za pomoc膮 logowania z wstrzykni臋tymi kolejkami PSR.
Instalacja
Do poprawnego dzia艂ania wymaga zestawu wirtualnych klient贸w w standardzie PSR-17 i PSR-18. Mo偶esz u偶y膰 Guzzle lub wariantu Symfony z Nyholm.
composer require lukaszzychal/nbp-api-client-php
composer require symfony/http-client nyholm/psr7 # Przyk艂ad zale偶no艣ci klienckiej z u偶yciem mechaniki Symfony
Podstawowe Wywo艂ania Klienta
Biblioteka eksponuje pot臋偶ny klasyfikator dla operacji z g艂贸wnym obiektem instancyjnym NbpApiClient:
use LukaszZychal\NbpApiClient\Client\NbpApiClient; use Nyholm\Psr7\Factory\Psr17Factory; use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpClient\Psr18Client; $httpClient = new Psr18Client(HttpClient::create()); $requestFactory = new Psr17Factory(); $client = new NbpApiClient($httpClient, $requestFactory); // Wstrzykiwanie Cache'a i Loggera // $client->setLogger($myPsr3Logger); // PSR-3: info, b艂臋dy sieciowe, ostrze偶enia // $client->setCache($myPsr6CacheItemPool, 21600); // Cache PSR-6 z TTL 6 godzin // $client->disableCache(); // Wy艂膮czenie cache w trakcie dzia艂ania // Pe艂na dokumentacja: docs/developer_usage_guide.md#5-psr-6-caching
Funkcjonalno艣膰
Klient na moment dzisiejszy implementuje wsparcie:
- Tabele kurs贸w Walut (
getCurrencyTable,getCurrencyTableForDate,getCurrencyTableForDateRange). Argument 1 w tabelach musi oznacza膰 liter臋 notowania ("A", "B", "C"). - Kruszce mro偶one / Z艂oto (
getGoldPrices,getGoldPricesForDate,getGoldPricesForDateRange).
Wszystkie procedury oddaj膮ce zbi贸r wynik贸w, np $client->getGoldPrices(), ustrukturyzowane s膮 jako instancje natywnych model贸w bez tablic po tablicach:
- Rekord ze zwrotki to
LukaszZychal\NbpApiClient\Model\CurrencyTableb膮d藕GoldPrice. - W 艣rodku Tabeli wyst臋puj膮 promowane atrybuty oraz tablica na powielone obiekty
CurrencyRate.
Kalkulator Przelicze艅 ("Krzy偶ak")
Narz臋dzie przychodzi z domy艣lnym pre-buildowanym kalkulatorem walutowym z pod艂o偶em waluty Polskiego Z艂otego jako punktu sta艂ego dla NBP. Wymaga wprowadzenia obiektywnej tabli wygenerowanej z klasyka klienta powo艂anego wy偶ej.
use LukaszZychal\NbpApiClient\Calculator\CurrencyCalculator; // Zak艂adaj膮c 偶e zmienn膮 `$tables` wyznaczono przez NbpApiClient z tabeli A... $calculator = new CurrencyCalculator(); $amount = 1000.0; $usdAmount = $calculator->convert($amount, 'PLN', 'USD', $tables[0]); # Oblicza kurs 1000 PLN do dolar贸w korzystaj膮c z notowania wyj艣ciowego NBP
Integracja z Frameworkami
Szczeg贸艂owe instrukcje dotycz膮ce integracji z Laravel oraz Symfony znajdziesz w dokumencie Developer Usage Guide.
Pe艂na dokumentacja cache PSR-6 (w艂膮czanie, wy艂膮czanie, TTL, dost臋pne adaptery) dost臋pna w sekcji Caching.
Tryb Dev (Testy integracji i analiza Statyczna)
System chroniony pe艂n膮 szat膮 integracji pod PHPUnit. Testy jednostkowe (kalkulator), jak i rygorystyczne integracje logiki bazy testowane przez wstrzykni臋ty Mock FakeHttpClient nie uderzaj膮 do interfejsu zewn臋trznego w testach poza wyznaczonym rejonem kontrolnym Contract Test贸w, a operuj膮 na statycznych plikach symulowanych.
composer run test(Jednostkowe i integracyjne testowanie zachowania DTO)composer run test:contract(Prawdziwe wywo艂anie HTTP z 偶ywym 偶ebrowaniem NBP z p臋tli Github Actions dla sprawdzania zgodno艣ci z umow膮)composer run analyze(PHPStan 8/8)composer run csorazcs:fix(Kontrola PER CS-2.0).
License / Licencja: MIT. Autor: NbpApiClient Developer.