Skip to content
This repository was archived by the owner on Feb 7, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
5e03f54
add validation for webhookUrl
mesilov Jan 15, 2022
1afa9de
fix demoDataGenerator
mesilov Jan 15, 2022
17b02ab
bump Symfony components version to 5.4.*
mesilov Jan 15, 2022
655834a
add Batch::deleteEntityItems
mesilov Jan 16, 2022
0eb45c9
add types for dto
mesilov Jan 17, 2022
4367647
add symfony/stopwatch
mesilov Jan 17, 2022
869a872
add transport layer debug info
mesilov Jan 18, 2022
eba8d90
add BulkItemsReader
mesilov Jan 18, 2022
b73426a
set info log level for apiClient
mesilov Feb 5, 2022
f8cf02b
add info level for Response
mesilov Feb 5, 2022
96017d4
fix BulkItemsReaderBuilder
mesilov Feb 5, 2022
6cd2c4b
add BulkItemsReaderBuilder for services
mesilov Feb 5, 2022
7e32e88
add BulkItemsReaderBuilder for integration test
mesilov Feb 5, 2022
b4cdbdd
add getTraversableList for batch
mesilov Feb 5, 2022
8d10bab
add fixes in batch system
mesilov Feb 5, 2022
d9e60a5
add DeletedItemResultInterface
mesilov Feb 5, 2022
edecbde
fix phpstan typecheck errors on level 5
mesilov Feb 5, 2022
9012764
add memory limit to phpstan
mesilov Feb 5, 2022
3e7a95e
add phpstan github action bage
mesilov Feb 5, 2022
fb8efc5
update readme
mesilov Feb 5, 2022
b3ba42b
update readme build status
mesilov Feb 5, 2022
4daed6f
add integration test for FilterWithBatchWithoutCountOrderTest
mesilov Feb 5, 2022
8aed9e2
fix integration tests for read strategies
mesilov Feb 5, 2022
bb6be7a
fix demo generator for contact
mesilov Feb 5, 2022
bb617f7
update performance benchmark
mesilov Feb 5, 2022
72a880d
fix integration tests
mesilov Feb 5, 2022
3cda0f8
add integration-tests workflow
mesilov Feb 5, 2022
80f6234
add integration-tests workflow2
mesilov Feb 5, 2022
93ac535
add integration-tests workflow settings
mesilov Feb 5, 2022
bb75c17
set secrets for integration-tests
mesilov Feb 5, 2022
87b9f18
обновили документацию
mesilov Feb 5, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/workflows/integration-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: "Integration tests"

on:
push:
branches:
- 'master'
- 'dev'
- '2.x'
paths:
- 'src/**'
- 'tests/**'

env:
COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist"
BITRIX24_PHP_SDK_PLAYGROUND_WEBHOOK: ${{ secrets.BITRIX24_PHP_SDK_PLAYGROUND_WEBHOOK }}
jobs:
tests:
name: "Integration tests"

runs-on: ubuntu-latest

strategy:
matrix:
php-version:
- "7.4"
dependencies: [ highest ]

steps:
- name: "Checkout"
uses: "actions/checkout@v2"

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

- name: "Install dependencies"
run: |
composer update ${{ env.COMPOSER_FLAGS }}

- name: "run unit tests"
run: "composer phpunit-run-integration-tests"
28 changes: 27 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
# bitrix24-php-sdk change log

## 2.0-alpha.6 — 20.01.2021

### Added

* add «fast» batch-query without counting elements in result
recordset [Добавить поддержку выгрузки большого количества данных без подсчёта элементов (-1](https://github.com/mesilov/bitrix24-php-sdk/issues/248)
* add method `Core\Batch::deleteEntityItems` for delete items in batch mode and integration test
* add integration test for read strategy `FilterWithBatchWithoutCountOrderTest`
* add type check in method `Core\Batch::deleteEntityItems` - only integer id allowed
* add interface `Core\Contracts\DeletedItemResultInterface`
* add in scope «CRM» `Services\CRM\Deal\Service\Batch::delete` batch delete deals
* add `symfony/stopwatch` component for integration tests
* add `/Infrastructure/HttpClient/TransportLayer/NetworkTimingsParser` for parse `curl_info` network data structures for debug logs
in `Bitrix24\SDK\Core\Response::__destruct()`
* add `/Infrastructure/HttpClient/TransportLayer/ResponseInfoParser` for parse `bitrix24_rest_api` timing info for debug logs
in `Bitrix24\SDK\Core\Response::__destruct()`
* add `Bitrix24\SDK\Core\BulkItemsReader` for data-intensive applications for bulk export data from Bitrix24, read strategies located in
folder `ReadStrategies`, in services read model **must** use most effective read strategy.

### Changed

* switch `symfony/http-client` to `5.4.*` version requirement.
* switch `symfony/http-client-contracts` to `^2.5` version requirement.
* switch `symfony/event-dispatcher` to `5.4.*` version requirement.
* switch `ramsey/uuid` to `^4.2.3` version requirement.

## 2.0-alpha.5 – 28.11.2021

### Added
Expand All @@ -11,7 +37,7 @@
issue [Добавить сервис по работе с юзерфилдами контакта #231](https://github.com/mesilov/bitrix24-php-sdk/issues/231)
* add method getUserfieldByFieldName for `ContactItemResult`
* add in scope «CRM» DealUserfield service and integration test, see
issue [Добавить сервис по работе с юзерфилдами cделки #232](https://github.com/mesilov/bitrix24-php-sdk/issues/232)
issue [Добавить сервис по работе с юзерфилдами cделки #232](https://github.com/mesilov/bitrix24-php-sdk/issues/232)
* add method getUserfieldByFieldName for `DealItemResult`
* add exception `UserfieldNotFoundException`

Expand Down
47 changes: 30 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
bitrix24-php-sdk [![Build Status](https://travis-ci.org/mesilov/bitrix24-php-sdk.svg?branch=master)](https://travis-ci.org/mesilov/bitrix24-php-sdk)
bitrix24-php-sdk – Bitrix24 REST API PHP SDK
================
[![License](https://poser.pugx.org/mesilov/bitrix24-php-sdk/license.svg)](https://packagist.org/packages/mesilov/bitrix24-php-sdk) [![Total Downloads](https://poser.pugx.org/mesilov/bitrix24-php-sdk/downloads.svg)](https://packagist.org/packages/mesilov/bitrix24-php-sdk)
[![Latest Stable Version](https://img.shields.io/packagist/v/mesilov/bitrix24-php-sdk.svg)](https://packagist.org/packages/mesilov/bitrix24-php-sdk)

A powerful PHP library for the Bitrix24 REST API

### Build status

[![phpstan check](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/phpstan.yml/badge.svg)](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/phpstan.yml)
[![phpunit unit-tests status](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/phpunit.yml/badge.svg)](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/phpunit.yml)

### BITRIX24-PHP-SDK Documentation

- [Russian](/docs/RU/documentation.md)
Expand Down Expand Up @@ -42,23 +49,23 @@ Performance improvements 🚀
### Development principles

- Good developer experience
- auto-completion of methods at the IDE
- typed method call signatures
- typed results of method calls
- helpers for typical operations
- auto-completion of methods at the IDE
- typed method call signatures
- typed results of method calls
- helpers for typical operations
- Good documentation
- documentation on the operation of a specific method containing a link to the official documentation
- documentation for working with the SDK
- documentation on the operation of a specific method containing a link to the official documentation
- documentation for working with the SDK
- Performance first:
- minimal impact on client code
- ability to work with large amounts of data with constant memory consumption
- efficient operation of the API using butch requests
- minimal impact on client code
- ability to work with large amounts of data with constant memory consumption
- efficient operation of the API using butch requests
- Modern technology stack
- based on [Symfony HttpClient](https://symfony.com/doc/current/http_client.html)
- actual PHP versions language features
- based on [Symfony HttpClient](https://symfony.com/doc/current/http_client.html)
- actual PHP versions language features
- Reliable:
- test coverage: unit, integration, contract
- typical examples typical for different modes of operation and they are optimized for memory \ performance
- test coverage: unit, integration, contract
- typical examples typical for different modes of operation and they are optimized for memory \ performance

### Architecture

Expand Down Expand Up @@ -107,47 +114,53 @@ Performance improvements 🚀
Add `"mesilov/bitrix24-php-sdk": "2.x"` to `composer.json` of your application. Or clone repo to your project.

### Tests

Tests locate in folder `tests` and we have two test types

#### Unit tests
**Fast**, in-memory tests without a network I\O
For run unit tests you must call in command line

**Fast**, in-memory tests without a network I\O For run unit tests you must call in command line

```shell
composer phpunit-run-unit-test
```

#### Integration tests

**Slow** tests with full lifecycle with your **test** Bitrix24 portal via webhook.

❗️Do not run integration tests with production portals ❗️

For run integration test you must:

1. Create [new Bitrix24 portal](https://www.bitrix24.ru/create.php?p=255670) for development tests
2. Go to left menu, click «Sitemap»
3. Find menu item «Developer resources»
4. Click on menu item «Other»
5. Click on menu item «Inbound webhook»
6. Assign all permisions with webhook and click «save» button
7. Create file `/tests/.env.local` with same settings, see comments in `/tests/.env` file.

```yaml
APP_ENV=dev
BITRIX24_WEBHOOK=https:// your portal webhook url
INTEGRATION_TEST_LOG_LEVEL=500
```

8. call in command line

```shell
composer composer phpunit-run-integration-tests
```

#### PHP Static Analysis Tool – phpstan

Call in command line

```shell
composer phpstan-analyse
```


### Submitting bugs and feature requests

Bugs and feature request are tracked on [GitHub](https://github.com/mesilov/bitrix24-php-sdk/issues)
Expand Down
17 changes: 9 additions & 8 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,19 @@
"ext-curl": "*",
"psr/log": "1.1.3",
"fig/http-message-util": "1.1.*",
"symfony/http-client": "5.3.*",
"symfony/http-client-contracts": "^2.4",
"symfony/event-dispatcher": "5.3.*",
"ramsey/uuid": "^4.0"
"symfony/http-client": "5.4.*",
"symfony/http-client-contracts": "^2.5",
"symfony/event-dispatcher": "5.4.*",
"ramsey/uuid": "^4.2.3"
},
"require-dev": {
"monolog/monolog": "2.1.*",
"symfony/console": "5.3.*",
"symfony/dotenv": "5.3.*",
"symfony/debug-bundle": "5.3.*",
"symfony/console": "5.4.*",
"symfony/dotenv": "5.4.*",
"symfony/debug-bundle": "5.4.*",
"phpstan/phpstan": "1.1.*",
"phpunit/phpunit": "9.5.*",
"symfony/stopwatch": "5.4.*",
"roave/security-advisories": "dev-master"
},
"autoload": {
Expand All @@ -55,7 +56,7 @@
"phpunit --testsuite integration_tests"
],
"phpstan-analyse": [
"vendor/bin/phpstan analyse"
"vendor/bin/phpstan analyse --memory-limit 1G"
]
}
}
31 changes: 15 additions & 16 deletions docs/RU/Core/Batch/batch-read-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,22 +88,21 @@ Help:

Режим | отдельные поля | вся сущность | вся сущность + UF_*
--- | --- | --- | ---
сортировка, подсчёт количества элементов в выборке | 0.1724 | 1.9875 | 2.3136
сортировка, без подсчёта количества элементов в выборке | 0.1173 | 1.3289 | 1.476
сортировка по умолчанию, подсчёт количества элементов в выборке | 0.0936 | 0.926 | 1.0272
сортировка по умолчанию, без подсчёта количества элементов в выборке | 0.0362 | 0.2701 | 0.2688
сортировка, подсчёт количества элементов в выборке | 0.3786 | 2.6767 | 3.1891
сортировка, без подсчёта количества элементов в выборке | 0.3125 | 1.745 | 1.956
сортировка по умолчанию, подсчёт количества элементов в выборке | 0.3129 | 1.3176 | 1.523
сортировка по умолчанию, без подсчёта количества элементов в выборке | **0.2241** | **0.458** | **0.4858**

### Чтение 6000 элементов отдельные поля \ вся сущность \ вся сущность + пользовательские поля
### Чтение 2700 элементов в batch-режиме отдельные поля \ вся сущность \ вся сущность + пользовательские поля

В данном примере используются batch-запросы, которые выбирают данные чанками по 2500, 2500 и 1000 элементов. Сами батч запросы реализуются
сервисом `Bitrix24\SDK\Core\Batch` Время — секунды, округление до 4 знаков.
Сами запросы строятся сервисом `Bitrix24\SDK\Core\Batch` Время — секунды, округление до 4 знаков.

Режим | отдельные поля | вся сущность | вся сущность + UF_*
--- | --- | --- | ---
сортировка, подсчёт количества элементов в выборке | 17.8018 | 239.8081 | 274.9921
сортировка, без подсчёта количества элементов в выборке | **not implemented** | **not implemented** | **not implemented**
сортировка по умолчанию, подсчёт количества элементов в выборке | 8.2121 | 110.0122 | 125.7331
сортировка по умолчанию, без подсчёта количества элементов в выборке | **not implemented** | **not implemented** | **not implemented**
сортировка, подсчёт количества элементов в выборке | 19.7924 | 131.3065 | 168.753
сортировка, без подсчёта количества элементов в выборке | 27.0083 | **30.8689** | **32.6827**
сортировка по умолчанию, подсчёт количества элементов в выборке | **14.3636** | 70.5149 | 79.5987
сортировка по умолчанию, без подсчёта количества элементов в выборке | 26.5045 | 31.1381 | 33.8329

## Подготовка тестового окружения

Expand All @@ -115,8 +114,8 @@ Help:
1. В текущей версии статьи в портале было 100к элементов в сущности, эта ситуация характерна для небольшого количества порталов
2. Замеры производились когда на портале отсутствовала операционная нагрузка характерная для рабочего дня
3. По возможности старайтесь избегать выборки всех данных
4. Сортировка данных при больших выборках тоже слишком дорогая операция
5. В roadmap SDK будет добавлена задача на поддержку batch-запросов в режиме «отключенный подсчёт количества» элементов, сейчас там
указано **not implemented**
6. Замеры будут проведены для кейсов от 10к до 200к элементов с шагом 10к элементов.
7. В коробочной версии Битрикс24 показатели могут существенно отличаться
4. Сортировка данных при больших выборках тоже дорогая операция
5. Имеет смысл сделать замеры при изменении количества элементов на портале 10к до 500к элементов с шагом 20к элементов.
6. В коробочной версии Битрикс24 показатели могут существенно отличаться
7. В SDK выделен отдельный сервис `Core\BulkItemsReader` который реализует более эффективные стратегии чем простой batch, на текущий момент
оптимизация скорости чтения данных не производилась, используется стратегия «батч без подсчёта количества элементов»
1 change: 0 additions & 1 deletion phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@ parameters:
level: 5
paths:
- src/
# - tests/
bootstrapFiles:
- tests/bootstrap.php
16 changes: 9 additions & 7 deletions src/Core/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function __construct(Credentials\Credentials $credentials, HttpClientInte
}

/**
* @return array
* @return array<string,string>
*/
protected function getDefaultHeaders(): array
{
Expand Down Expand Up @@ -112,18 +112,19 @@ public function getNewAccessToken(): RenewedAccessToken
}

/**
* @param string $apiMethod
* @param array $parameters
* @param string $apiMethod
* @param array<mixed> $parameters
*
* @return ResponseInterface
* @throws TransportExceptionInterface
* @throws InvalidArgumentException
*/
public function getResponse(string $apiMethod, array $parameters = []): ResponseInterface
{
$this->logger->debug(
sprintf('getResponse.start %s', $apiMethod),
$this->logger->info(
'getResponse.start',
[
'apiMethod' => $apiMethod,
'domainUrl' => $this->credentials->getDomainUrl(),
'parameters' => $parameters,
]
Expand All @@ -147,9 +148,10 @@ public function getResponse(string $apiMethod, array $parameters = []): Response
];
$response = $this->client->request($method, $url, $requestOptions);

$this->logger->debug(
sprintf('getResponse.end [%s]', $apiMethod),
$this->logger->info(
'getResponse.end',
[
'apiMethod' => $apiMethod,
'responseInfo' => $response->getInfo(),
]
);
Expand Down
2 changes: 1 addition & 1 deletion src/Core/ApiLevelErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function __construct(LoggerInterface $logger)
}

/**
* @param array $responseBody
* @param array<string,string> $responseBody
*
* @throws QueryLimitExceededException
* @throws BaseException
Expand Down
Loading