PHPackages                             kosmosafive/kosmosafive.cbrrates - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. kosmosafive/kosmosafive.cbrrates

ActiveBitrix-d7-module[API Development](/categories/api)

kosmosafive/kosmosafive.cbrrates
================================

Курсы валют ЦБ РФ

2.0.0(1mo ago)034Apache-2.0PHPPHP &gt;=8.4

Since Nov 14Pushed 1mo agoCompare

[ Source](https://github.com/kosmosafive/kosmosafive.cbrrates)[ Packagist](https://packagist.org/packages/kosmosafive/kosmosafive.cbrrates)[ Docs](https://github.com/kosmosafive/kosmosafive.cbrrates)[ RSS](/packages/kosmosafive-kosmosafivecbrrates/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (18)Versions (5)Used By (0)

Kosmosafive: CBR Rates
======================

[](#kosmosafive-cbr-rates)

Получение котировок валют Центрального банка Российской Федерации.

Установка
---------

[](#установка)

В composer.json (пример для директории local) проекта добавьте

```
{
  "require": {
    "wikimedia/composer-merge-plugin": "dev-master"
  },
  "config": {
    "allow-plugins": {
      "wikimedia/composer-merge-plugin": true
    }
  },
  "extra": {
    "merge-plugin": {
      "require": [
        "../bitrix/composer-bx.json",
        "modules/*/composer.json"
      ],
      "recurse": true,
      "replace": true,
      "ignore-duplicates": false,
      "merge-dev": true,
      "merge-extra": false,
      "merge-extra-deep": false,
      "merge-scripts": false
    },
    "installer-paths": {
      "modules/{$name}/": [
        "type:bitrix-d7-module"
      ]
    }
  }
}
```

- установить модуль

Конфигурация модуля
-------------------

[](#конфигурация-модуля)

Конфигурацию рекомендуется указывать в файле /bitrix/.settings\_extra.php.

- *adapter* — настройки адаптера

```
return [
    'kosmosafive.cbrrates' => [
        'value' => [
            'adapter' => [
                'bitrix' => [
                    'http_client_options' => [
                        'redirect' => true,
                    ],
                ],
            ],
        ]
    ]
];
```

Использование
-------------

[](#использование)

Отправлять запросы можно как напрямую (сервис Kosmosafive\\CBRRates\\CBRApiInterface::class), так и с помощью сервиса-обертки (сервис Kosmosafive\\CBRRates\\Service\\ApiServiceInterface::class).

### Использование напрямую

[](#использование-напрямую)

1. Получить клиент

```
use Bitrix\Main\Loader;
use Bitrix\Main\DI\ServiceLocator;
use Kosmosafive\CBRRates\CBRApiInterface;

$api = ServiceLocator::getInstance()->get(CBRApiInterface::class);
$client = $api->getClient();
```

2. Выполнить запрос

```
$rateCollection = (new Route\Scripts\XmlDaily($client))->get();
```

### Использование сервиса-обертки

[](#использование-сервиса-обертки)

Реализованы методы:

- получение котировок на заданный на день | getDailyRates(?Type\\Date $date = null)
- справочник по кодам валют | getCurrencies()
- обновление котировок на заданный день | updateDailyRates(Type\\Date $date)

1. Получить сервис

```
use Bitrix\Main\Loader;
use Bitrix\Main\DI\ServiceLocator;
use Kosmosafive\CBRRates\Service\ApiServiceInterface;

$apiService = ServiceLocator::getInstance()->get(ApiServiceInterface::class);
```

2. Выполнить запрос

```
$rateCollection = $apiService->getDailyRates();
```

### Клиент

[](#клиент)

Поддерживается множество клиентов. Клиент идентифицируется по ключу. По умолчанию создается клиент с ключом default. Добавить собственный клиент можно программно.

```
use Kosmosafive\CBRRates\Options;

$clientKey = 'custom';

$options = new Options();
$client = new Client($options);

$addClientResult = $apiService->addClient($clientKey, $client);

$client = $apiService->getClient($clientKey);
```

### События

[](#события)

#### onGetClient

[](#ongetclient)

Вызывается при вызове метода **$apiService-&gt;getClient**, когда клиент не был найден. В параметрах передается *key* — идентификатор запрошенного клиента. Обратно необходимо вернуть Клиент в параметре *client*.

### Маршруты

[](#маршруты)

- *Scripts*
- - XmlDaily: get
- - XmlValFul: get

### Логирование

[](#логирование)

Реализована поддержка логгера, реализующего интерфейс [PSR-3](https://www.php-fig.org/psr/psr-3/), указанного в конфигурации системы ([Разработчик Bitrix Framework: Логгеры](https://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=43&LESSON_ID=15330)).

Расширенный логгер доступен при реализации интерфейса *Kosmosafive\\CBRRates\\Diag\\Logger\\HttpLoggerInterface*:

```
namespace Kosmosafive\CBRRates\Diag\Logger;

use Kosmosafive\CBRRates\Http\RequestInterface;
use Kosmosafive\CBRRates\Http\ResponseInterface;

interface HttpLoggerInterface
{

    public function logRequest(string $level, RequestInterface $request): void;

    public function logResponse(string $level, ResponseInterface $response): void;
}
```

Модуль содержит расширенную файловую реализацию логгера — *Kosmosafive\\CBRRates\\Diag\\Logger\\FileHttpLogger*

Поиск логгера будет осуществлен по ключам *kosmosafive.cbrrates* и *default*.

### Исключения

[](#исключения)

- Kosmosafive\\CBRRates\\Exception\\Exception
- Kosmosafive\\CBRRates\\Http\\Exception\\RequestException

### Интерфейс командной строки

[](#интерфейс-командной-строки)

#### Обновление котировок за указанный день \\ период

[](#обновление-котировок-за-указанный-день--период)

```
kosmosafive.cbrrates:update-daily-rates  []
```

- *from* — Дата \\ Дата начала периода (YYYY-MM-DD)
- *to* — (опционально) Дата конца периода (YYYY-MM-DD)

###  Health Score

44

—

FairBetter than 91% of packages

Maintenance93

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~93 days

Total

3

Last Release

37d ago

Major Versions

1.0.1 → 2.0.02026-05-20

PHP version history (2 changes)1.0.0PHP &gt;=8.3

2.0.0PHP &gt;=8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/4149bcfcdcc947ad42afa006615812c8ea743bf76e0e10ef44ffb3d5ae2796f0?d=identicon)[kosmosafive](/maintainers/kosmosafive)

---

Top Contributors

[![kosmosafive](https://avatars.githubusercontent.com/u/14090839?v=4)](https://github.com/kosmosafive "kosmosafive (7 commits)")

---

Tags

apicurrencybitrixRaterdncbr

###  Code Quality

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/kosmosafive-kosmosafivecbrrates/health.svg)

```
[![Health](https://phpackages.com/badges/kosmosafive-kosmosafivecbrrates/health.svg)](https://phpackages.com/packages/kosmosafive-kosmosafivecbrrates)
```

###  Alternatives

[gabrielbull/ups-api

PHP UPS API

4582.4M10](/packages/gabrielbull-ups-api)[florianv/swap-bundle

Drop-in Symfony bundle for currency conversion: configurable services, multi-provider exchange rates with fallback and caching.

63425.7k1](/packages/florianv-swap-bundle)[stichoza/nbg-currency

National Bank of Georgia (NBG) currency service API wrapper

2925.4k1](/packages/stichoza-nbg-currency)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
