Skip to content

Commit

Permalink
Setup (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
liquetsoft authored Jul 12, 2022
1 parent 03f941c commit 3229c92
Show file tree
Hide file tree
Showing 35 changed files with 3,928 additions and 0 deletions.
50 changes: 50 additions & 0 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: cbrf_service

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
build:

name: CBRF service (PHP ${{ matrix.php-versions }})
runs-on: ubuntu-latest
strategy:
fail-fast: true
matrix:
php-versions: ['7.4', '8.0', '8.1']

steps:
- uses: actions/checkout@v2

- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}

- name: Check PHP Version
run: php -v

- name: Validate composer.json and composer.lock
run: composer validate

- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php-versions }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-
- name: Install dependencies
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest

- name: Run test suite
run: composer run-script test

- name: Run linters
run: composer run-script linter
12 changes: 12 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.idea
vendor
composer.lock
.php_cs.cache
.phpunit.result.cache
.php-cs-fixer.cache

tests/coverage
docker/.env
test.php

.~lock.*
35 changes: 35 additions & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

use PhpCsFixer\Config;

$finder = PhpCsFixer\Finder::create()->in(__DIR__);

$rules = [
'@Symfony' => true,
'new_with_braces' => true,
'concat_space' => ['spacing' => 'one'],
'array_syntax' => ['syntax' => 'short'],
'yoda_style' => false,
'phpdoc_no_empty_return' => false,
'no_superfluous_phpdoc_tags' => false,
'single_line_throw' => false,
'array_indentation' => true,
'declare_strict_types' => true,
'void_return' => true,
'non_printable_character' => true,
'modernize_types_casting' => true,
'ordered_interfaces' => ['order' => 'alpha', 'direction' => 'ascend'],
'date_time_immutable' => true,
'native_constant_invocation' => true,
'combine_nested_dirname' => true,
'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced', 'strict' => true],
'php_unit_construct' => true,
'php_unit_dedicate_assert' => true,
'php_unit_expectation' => true,
'php_unit_internal_class' => true,
'php_unit_mock_short_will_return' => true,
'php_unit_strict' => true,
'strict_comparison' => true,
];

return (new Config())->setRules($rules)->setFinder($finder);
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 liquetsoft

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
31 changes: 31 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/make

user_id := $(shell id -u)
docker_compose_bin := $(shell command -v docker-compose 2> /dev/null) --file "docker/docker-compose.yml"
php_container_bin := $(docker_compose_bin) run --rm -u "$(user_id)" "php"
php_composer_script := $(php_container_bin) composer run-script

.DEFAULT_GOAL := build

# --- [ Development tasks ] -------------------------------------------------------------------------------------------

build: ## Build container and install composer libs
$(docker_compose_bin) build --force-rm

install: ## Install all data
$(php_container_bin) composer update

shell: ## Runs shell in container
$(php_container_bin) bash

fixer: ## Run fixer to fix code style
$(php_composer_script) fixer

linter: ## Run linter to check project
$(php_composer_script) linter

test: ## Run tests
$(php_composer_script) test

coverage: ## Run tests with coverage
$(php_composer_script) coverage
185 changes: 185 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
Php курсы валют
===============

[![Latest Stable Version](https://poser.pugx.org/liquetsoft/cbrfservice/v/stable.png)](https://packagist.org/packages/liquetsoft/cbrfservice)
[![Total Downloads](https://poser.pugx.org/liquetsoft/cbrfservice/downloads.png)](https://packagist.org/packages/liquetsoft/cbrfservice)
[![License](https://poser.pugx.org/liquetsoft/cbrfservice/license.svg)](https://packagist.org/packages/liquetsoft/cbrfservice)
[![Build Status](https://github.com/liquetsoft/cbrfservice/workflows/cbrf_service/badge.svg)](https://github.com/liquetsoft/cbrfservice/actions?query=workflow%3A%22cbrf_service%22)

Php обертка для [сервиса Центробанка РФ](https://www.cbr.ru/development/DWS/).



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

Добавьте библиотеку в проект с помощью [Composer](https://getcomposer.org/doc/00-intro.md):

```bash
composer req liquetsoft/cbrfservice
```



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

```php
//инициируем новый объект сервиса
$cbrf = new \Liquetsoft\CbrfService\CbrfDaily();
```

```php
//получаем курсы всех валют
$rates = $cbrf->getCursOnDate(new \DateTimeImmutable());

//получаем курс валюты по ее буквенному коду
$rateEur = $cbrf->getCursOnDateByCharCode(new \DateTimeImmutable(), 'EUR');

//получаем курс валюты по ее цифровому коду
$rate978 = $cbrf->getCursOnDateByNumericCode(new \DateTimeImmutable(), 978);
```

```php
//получаем словарь всех доступных валют
$currencies = $cbrf->enumValutes();

//получаем описание валюты из словаря по буквенному коду
$enumEur = $cbrf->enumValuteByCharCode('EUR');

//получаем описание валюты из словаря по цифровому коду
$enum978 = $cbrf->enumValuteByNumericCode(978);

//получаем динамику курса для указанной валюты за последний месяц
$dynamic = $cbrf->getCursDynamic(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable(),
$enumEur
);
```

```php
//получаем динамику ключевой ставки за последний месяц
$keyRate = $cbrf->keyRate(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем динамику цен на драгоценные металлы за последний месяц
$metalsPrices = $cbrf->dragMetDynamic(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем валютный своп за последний месяц
$swap = $cbrf->swapDynamic(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем динамику ставок привлечения средств по депозитным операциям за последний месяц
$depo = $cbrf->depoDynamic(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем динамику сведений об остатках средств на корреспондентских счетах кредитных организаций
$leftovers = $cbrf->ostatDynamic(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем депозиты банков в Банке России
$leftovers = $cbrf->ostatDepo(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем международные резервы Российской Федерации, ежемесячные значения
$mrrf = $cbrf->mrrf(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем международные резервы Российской Федерации, еженедельные значения
$mrrf = $cbrf->mrrf7d(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем сальдо операций ЦБ РФ по предоставлению/абсорбированию ликвидности
$saldo = $cbrf->saldo(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем индекс и срочную версию RUONIA
$saldo = $cbrf->ruoniaSV(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем ставку RUONIA
$saldo = $cbrf->ruonia(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

```php
//получаем ставки межбанковского кредитного рынка
$mkr = $cbrf->mkr(
new \DateTimeImmutable('-1 month'),
new \DateTimeImmutable()
);
```

В случае, если необходимо передать сконфигурированный заранее транспорт, например для использования proxy:

```php
//инициируем новый объект SoapClient
$client = new SoapClient(
\Liquetsoft\CbrfService\CbrfSoapService::DEFAULT_WSDL,
[
'proxy_host' => 'localhost',
'proxy_port' => 8080
]
);

//инициируем новый объект сервиса
$cbrf = new \Liquetsoft\CbrfService\CbrfDaily($client);
```



Обработка ошибок
----------------

Все ошибки, которые будут перехвачены при запросах, будут выброшены как исключение `\Liquetsoft\CbrfService\CbrfException`. Если `\SoapClient` будет сконфигурирован с отключенными исключениями, то обработка ошибок остается на стороне клиентского скрипта.



Методы
------

Описание методов вы можете найти на [сайте банка России](https://www.cbr.ru/development/DWS/).
45 changes: 45 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "liquetsoft/cbrfservice",
"description": "Component for bank of Russia daily web service",
"type": "library",
"keywords": ["php", "banks", "currency rate", "soap", "service"],
"license": "MIT",
"require": {
"php": ">=7.4",
"ext-soap": "*",
"ext-SimpleXML": "*"
},
"require-dev": {
"phpunit/phpunit": "^9.0",
"friendsofphp/php-cs-fixer": "^2.11|^3.0",
"sebastian/phpcpd": "^6.0",
"vimeo/psalm": "^4.0",
"psalm/plugin-phpunit": "^0.15.1"
},
"autoload": {
"psr-4": {
"Liquetsoft\\CbrfService\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Liquetsoft\\CbrfService\\Tests\\": "tests/"
}
},
"scripts": {
"test": "vendor/bin/phpunit --configuration phpunit.xml.dist",
"coverage": "vendor/bin/phpunit --configuration phpunit.xml.dist --coverage-html=tests/coverage",
"fixer": "vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php -vv --allow-risky=yes",
"linter": [
"vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php -vv --allow-risky=yes --dry-run --stop-on-violation",
"vendor/bin/phpcpd ./ --exclude vendor --exclude tests",
"vendor/bin/psalm --show-info=true --php-version=$(php -r \"echo phpversion();\")"
]
},
"repositories": [
{
"type": "git",
"url": "https://github.com/liquetsoft/cbrfservice"
}
]
}
12 changes: 12 additions & 0 deletions docker/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: '3.7'


# container to run tests and other developer activities
services:
php:
container_name: cbrf-service-php
image: cbrf-service-php
build:
context: php
volumes:
- ./../:/var/app:cached
Loading

0 comments on commit 3229c92

Please sign in to comment.