From 50caea688115cc100fc0188165bae134a97a1aff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB=20=D0=A5=D1=80=D0=B0?= =?UTF-8?q?=D0=BC=D0=BE=D0=B2?= Date: Sun, 8 Sep 2024 00:01:33 +0300 Subject: [PATCH 001/130] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=B9=D0=BD=D0=B5=D1=80?= =?UTF-8?q?=20=D1=81=20Postgres?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/ISSUE_TEMPLATE/{config.yml => config.yml} | 0 docker/Dockerfile | 0 docker/docker-compose.yaml | 13 +++++++++++++ 3 files changed, 13 insertions(+) rename .github/ISSUE_TEMPLATE/{config.yml => config.yml} (100%) create mode 100644 docker/Dockerfile create mode 100644 docker/docker-compose.yaml diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml similarity index 100% rename from .github/ISSUE_TEMPLATE/config.yml rename to .github/ISSUE_TEMPLATE/config.yml diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..e69de29 diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml new file mode 100644 index 0000000..8cb55ba --- /dev/null +++ b/docker/docker-compose.yaml @@ -0,0 +1,13 @@ +services: + db: + image: postgres + restart: always + + shm_size: 128mb + + environment: + POSTGRES_DB: bitrixAppDb + POSTGRES_USER: kirill + POSTGRES_PASSWORD: bitrix24lib + + From 507fb9fb35ea3ae5286586222da4f5aa8791ac58 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Tue, 24 Sep 2024 21:51:24 +0300 Subject: [PATCH 002/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=B9=D0=BD=D0=B5?= =?UTF-8?q?=D1=80=20=D1=81=20nginx,php-fpm=20=D0=B8=20postgres.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docker-compose.yaml | 25 +++++++++++++++++++++++++ docker/Dockerfile | 0 docker/docker-compose.yaml | 13 ------------- docker/nginx/Dockerfile | 5 +++++ docker/nginx/conf.d/nginx.conf | 20 ++++++++++++++++++++ docker/php-fpm/Dockerfile | 11 +++++++++++ docker/postgres/Dockerfile | 12 ++++++++++++ index.php | 17 +++++++++++++++++ 8 files changed, 90 insertions(+), 13 deletions(-) create mode 100644 docker-compose.yaml delete mode 100644 docker/Dockerfile delete mode 100644 docker/docker-compose.yaml create mode 100644 docker/nginx/Dockerfile create mode 100644 docker/nginx/conf.d/nginx.conf create mode 100644 docker/php-fpm/Dockerfile create mode 100644 docker/postgres/Dockerfile create mode 100644 index.php diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..ada4115 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,25 @@ +services: + php-fpm: + build: + context: ./docker/php-fpm + volumes: + - ./:/var/www/bitrix24-php-lib + nginx: + build: + context: ./docker/nginx + volumes: + - ./:/var/www/bitrix24-php-lib + ports: + - "8081:80" + depends_on: + - php-fpm + postgres-container: + image: postgres + build: + context: ./docker/postgres + ports: + - "5432:5432" + volumes: + - ./docker/postgres/data:/var/lib/postgresql/data + restart: always + diff --git a/docker/Dockerfile b/docker/Dockerfile deleted file mode 100644 index e69de29..0000000 diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml deleted file mode 100644 index 8cb55ba..0000000 --- a/docker/docker-compose.yaml +++ /dev/null @@ -1,13 +0,0 @@ -services: - db: - image: postgres - restart: always - - shm_size: 128mb - - environment: - POSTGRES_DB: bitrixAppDb - POSTGRES_USER: kirill - POSTGRES_PASSWORD: bitrix24lib - - diff --git a/docker/nginx/Dockerfile b/docker/nginx/Dockerfile new file mode 100644 index 0000000..922b636 --- /dev/null +++ b/docker/nginx/Dockerfile @@ -0,0 +1,5 @@ +FROM nginx:1.27-alpine + +RUN rm /etc/nginx/conf.d/default.conf + +COPY ./conf.d/nginx.conf /etc/nginx/conf.d/ \ No newline at end of file diff --git a/docker/nginx/conf.d/nginx.conf b/docker/nginx/conf.d/nginx.conf new file mode 100644 index 0000000..7ef599a --- /dev/null +++ b/docker/nginx/conf.d/nginx.conf @@ -0,0 +1,20 @@ +server { + listen 80; + server_name localhost; + + root /var/www/bitrix24-php-lib; + index index.html index.htm index.php; + + # Redirects requests to index.php if the file is not found + location / { + try_files $uri $uri/ /index.php?$query_string; + } + + # Passes PHP requests to PHP-FPM container + location ~ \.php$ { + include fastcgi_params; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + fastcgi_pass php-fpm:9000; # Replace with your PHP-FPM container name + fastcgi_index index.php; + } +} \ No newline at end of file diff --git a/docker/php-fpm/Dockerfile b/docker/php-fpm/Dockerfile new file mode 100644 index 0000000..7d707ee --- /dev/null +++ b/docker/php-fpm/Dockerfile @@ -0,0 +1,11 @@ +FROM php:8.2-fpm-alpine + + +RUN set -ex \ + && apk --no-cache add \ + postgresql-dev \ + && docker-php-ext-install pdo pdo_pgsql + +WORKDIR /bitrix24-php-lib + +COPY ./ ./ \ No newline at end of file diff --git a/docker/postgres/Dockerfile b/docker/postgres/Dockerfile new file mode 100644 index 0000000..8d7a370 --- /dev/null +++ b/docker/postgres/Dockerfile @@ -0,0 +1,12 @@ +FROM postgres:16.4-alpine + +# Устанавливаем переменные окружения для настройки базы данных +ENV POSTGRES_USER=kirill +ENV POSTGRES_PASSWORD=bitrix24lib +ENV POSTGRES_DB=bitrixAppDb + +# Копируем SQL-скрипты для инициализации базы данных (если есть) +# COPY init.sql /docker-entrypoint-initdb.d/ + +# Открываем порт PostgreSQL +EXPOSE 5432 \ No newline at end of file diff --git a/index.php b/index.php new file mode 100644 index 0000000..b70805a --- /dev/null +++ b/index.php @@ -0,0 +1,17 @@ +"; +$conn_string = "pgsql:host=localhost;port=5432;dbname=bitrixAppDb;user=kirill;password=bitrix24lib"; +try { + $db = new PDO($conn_string); + + // Установка режима обработки ошибок + $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + echo "Подключение к базе данных успешно установлено."; +}catch (PDOException $error) +{ + echo "Ошибка :". $error->getMessage(); +} + +?> From 6473c92ce8c704818538394fc7cc731d7c766be0 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 6 Oct 2024 09:57:54 +0300 Subject: [PATCH 003/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=80=D0=B0=D1=81=D1=88=D0=B8=D1=80=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20mbstring,zip,curl,bcmath?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 11 ++++++++++- docker/php-fpm/Dockerfile | 6 ++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index a1f253a..f48b8bc 100644 --- a/Makefile +++ b/Makefile @@ -22,4 +22,13 @@ test-unit: vendor/bin/phpunit --testsuite unit_tests --display-warnings test-integration: - vendor/bin/phpunit --testsuite integration_tests --display-warnings \ No newline at end of file + vendor/bin/phpunit --testsuite integration_tests --display-warnings + + +# docker file + +docker-up: + docker compose up --build -d + +docker-down: + docker compose down --remove-orphans \ No newline at end of file diff --git a/docker/php-fpm/Dockerfile b/docker/php-fpm/Dockerfile index 7d707ee..67daccf 100644 --- a/docker/php-fpm/Dockerfile +++ b/docker/php-fpm/Dockerfile @@ -1,10 +1,12 @@ FROM php:8.2-fpm-alpine - RUN set -ex \ && apk --no-cache add \ postgresql-dev \ - && docker-php-ext-install pdo pdo_pgsql + oniguruma-dev \ + libzip-dev \ + curl-dev \ + && docker-php-ext-install pdo pdo_pgsql mbstring zip curl bcmath WORKDIR /bitrix24-php-lib From ef8ab43698d55537b303b41346217974bce88a3b Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 6 Oct 2024 21:27:48 +0600 Subject: [PATCH 004/130] Add PHP CLI service and improve Docker setup Added a PHP CLI service definition in `docker-compose.yaml` and created the appropriate Dockerfile. Enhanced Composer dependencies and updated Makefile with new commands for initializing and managing the application containers. Updated `.gitignore` to exclude Docker database files. Signed-off-by: mesilov --- .gitignore | 1 + Makefile | 76 ++++++++++++++++++++++++++++++++++++++- composer.json | 25 +++++++++---- docker-compose.yaml | 26 +++++++++++++- docker/php-cli/Dockerfile | 9 +++++ 5 files changed, 129 insertions(+), 8 deletions(-) create mode 100644 docker/php-cli/Dockerfile diff --git a/.gitignore b/.gitignore index 66c3dc1..eb0a19d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ /.idea* /vendor /.cache +/docker/db composer.phar composer.lock .phpunit.result.cache diff --git a/Makefile b/Makefile index f48b8bc..46f7bba 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,10 @@ # # For the full copyright and license information, please view the MIT-LICENSE.txt # file that was distributed with this source code. +#!/usr/bin/env make + +export COMPOSE_HTTP_TIMEOUT=120 +export DOCKER_CLIENT_TIMEOUT=120 default: @echo "make needs target:" @@ -31,4 +35,74 @@ docker-up: docker compose up --build -d docker-down: - docker compose down --remove-orphans \ No newline at end of file + docker compose down --remove-orphans + +#====================================== +restart: down up + +init: + @echo "remove all containers" + docker-compose down --remove-orphans + @echo "build containers" + docker-compose build + @echo "install dependencies" + docker-compose run --rm php-cli composer install +# @echo "run database migrations…" +# docker-compose run --rm php-cli php bin/doctrine doctrine:migrations:migrate --no-interaction + @echo "change owner of var folder for access from container" + docker-compose run --rm php-cli chown -R www-data:www-data /var/www/html/var/ + @echo "run application…" + docker-compose up -d + + +up: + @echo "run application…" + docker-compose up -d + +down: + @echo "stop application and remove containers" + docker-compose down --remove-orphans + +down-clear: + @echo "stop application and remove containers with volumes" + docker-compose down -v --remove-orphans + + +composer-install: + @echo "install dependencies…" + docker-compose run --rm php-cli composer install + +composer-update: + @echo "update dependencies…" + docker-compose run --rm php-cli composer update + +# вызов composer с любыми параметрами +# Примеры: +# make composer install +# make composer "install --no-dev" +composer: + docker-compose run --rm php-cli composer $(filter-out $@,$(MAKECMDGOALS)) + +%: + @: # silence + +dev-dump-cache: + composer dumpautoload + +#====================================== +cli-bash: + docker-compose run --rm php-cli sh $(filter-out $@,$(MAKECMDGOALS)) + +# static code analysis +test-run-phpstan: + docker-compose run --rm php-cli php vendor/bin/phpstan analyse --memory-limit 2G + +# unit-tests +test-run-unit-tests: + docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=unit --testdox + +# functional-tests, work with test database +test-run-functional-tests: + docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force + docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create + docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional --testdox \ No newline at end of file diff --git a/composer.json b/composer.json index e5e973d..f912eaf 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ "SaaS" ], "type": "library", - "homepage": "https://github.com/mesilov/bitrix24-app-core", + "homepage": "https://github.com/mesilov/bitrix24-php-lib", "license": "MIT", "authors": [ { @@ -18,6 +18,11 @@ "homepage": "https://github.com/mesilov/" } ], + "support": { + "issues": "https://github.com/mesilov/bitrix24-php-lib/issues?state=open", + "source": "https://github.com/mesilov/bitrix24-php-lib" + }, + "minimum-stability": "stable", "config": { "sort-packages": true, "allow-plugins": { @@ -28,6 +33,7 @@ "php": "8.3.*", "ext-json": "*", "ext-curl": "*", + "ext-bcmath": "*", "ext-intl": "*", "psr/log": "^3", "fig/http-message-util": "^1", @@ -36,14 +42,21 @@ "nesbot/carbon": "^3", "moneyphp/money": "^4", "mesilov/bitrix24-php-sdk": "^2", - "doctrine/orm": "^2", - "doctrine/doctrine-bundle": "^2", - "doctrine/doctrine-migrations-bundle": "^3", + "doctrine/orm": "^3", + "doctrine/doctrine-bundle": "*", + "doctrine/doctrine-migrations-bundle": "*", + "knplabs/knp-paginator-bundle": "^6", "symfony/event-dispatcher": "^7", + "symfony/serializer": "^7", "symfony/uid": "^7", - "knplabs/knp-paginator-bundle": "^6" + "symfony/yaml": "^7", + "symfony/cache": "^7", + "symfony/console": "^7", + "symfony/dotenv": "^7", + "symfony/framework-bundle": "^7" }, "require-dev": { + "friendsofphp/php-cs-fixer": "^3.59", "monolog/monolog": "^3", "fakerphp/faker": "^1", "phpstan/phpstan": "^1", @@ -62,7 +75,7 @@ "autoload-dev": { "psr-4": { "Bitrix24\\SDK\\Lib\\Tests\\": "tests", - "Bitrix24\\SDK\\Tests\\":"vendor/mesilov/bitrix24-php-sdk/tests" + "Bitrix24\\SDK\\Tests\\": "vendor/mesilov/bitrix24-php-sdk/tests" } } } diff --git a/docker-compose.yaml b/docker-compose.yaml index ada4115..0e7a7d1 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -22,4 +22,28 @@ services: volumes: - ./docker/postgres/data:/var/lib/postgresql/data restart: always - + php-cli: + build: + context: ./docker/php-cli + links: + - b24-account-test-database + volumes: + - .:/var/www/html + working_dir: /var/www/html + b24-account-test-database: + image: postgres:${POSTGRES_VERSION:-15}-alpine + restart: unless-stopped + environment: + POSTGRES_DB: ${POSTGRES_DB:-b24AccountTest} + # You should definitely change the password in production + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-b24AccountTest} + POSTGRES_USER: ${POSTGRES_USER:-b24AccountTest} + PGDATA: "/var/lib/postgresql/data/pgdata" + container_name: b24-account-test-database + ports: + - '5432:5432' + expose: + - 5432 + volumes: + - ./Init Database:/docker-entrypoint-initdb.d + - ./docker/db:/var/lib/postgresql/data diff --git a/docker/php-cli/Dockerfile b/docker/php-cli/Dockerfile new file mode 100644 index 0000000..256b9c8 --- /dev/null +++ b/docker/php-cli/Dockerfile @@ -0,0 +1,9 @@ +FROM php:8.3-cli-alpine + +RUN apk add unzip libpq-dev git icu-dev \ + && docker-php-ext-install bcmath pdo pdo_pgsql intl \ + && docker-php-ext-enable bcmath pdo pdo_pgsql intl + +RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/bin --filename=composer --quiet + +ENV COMPOSER_ALLOW_SUPERUSER 1 From 5cff2eadace008510e2c5d70090d738385a3e0a6 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 6 Oct 2024 18:51:03 +0300 Subject: [PATCH 005/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B3=D0=BB=D0=BE=D0=B1=D0=B0=D0=BB=D1=8C=D0=BD?= =?UTF-8?q?=D1=8B=D0=B5=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD?= =?UTF-8?q?=D1=8B=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docker/postgres/Dockerfile | 17 +++++++++++++---- index.php | 5 ++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/docker/postgres/Dockerfile b/docker/postgres/Dockerfile index 8d7a370..3c4041e 100644 --- a/docker/postgres/Dockerfile +++ b/docker/postgres/Dockerfile @@ -1,12 +1,21 @@ FROM postgres:16.4-alpine +# Определяем ARG переменные, которые будут переданы при сборке +ARG POSTGRES_USER +ARG POSTGRES_PASSWORD +ARG POSTGRES_DB + # Устанавливаем переменные окружения для настройки базы данных -ENV POSTGRES_USER=kirill -ENV POSTGRES_PASSWORD=bitrix24lib -ENV POSTGRES_DB=bitrixAppDb +ENV POSTGRES_USER=${POSTGRES_USER} +ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD} +ENV POSTGRES_DB=${POSTGRES_DB} # Копируем SQL-скрипты для инициализации базы данных (если есть) # COPY init.sql /docker-entrypoint-initdb.d/ # Открываем порт PostgreSQL -EXPOSE 5432 \ No newline at end of file +EXPOSE 5432 + + + + diff --git a/index.php b/index.php index b70805a..c69b486 100644 --- a/index.php +++ b/index.php @@ -1,7 +1,10 @@ "; -$conn_string = "pgsql:host=localhost;port=5432;dbname=bitrixAppDb;user=kirill;password=bitrix24lib"; +$dbName = getenv('POSTGRES_DB'); +$dbPassword = getenv('POSTGRES_PASSWORD'); +$dbUser = getenv('POSTGRES_USER'); +$conn_string = "pgsql:host=localhost;port=5432;dbname=$dbUser;user=$dbUser;password=$dbPassword"; try { $db = new PDO($conn_string); From 6d8d5bd7340be6ca12f0ffe17dcd00fe63be7255 Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 6 Oct 2024 22:46:37 +0600 Subject: [PATCH 006/130] Add UUID and member ID properties to Bitrix24Account Updated the Bitrix24Account class with UUID and member ID properties, leveraging Symfony and Doctrine annotations. Additionally, replaced the deprecated SDK package and adjusted the PHPUnit testsuite configuration. Signed-off-by: mesilov --- Makefile | 2 +- composer.json | 7 ++-- .../Entity/Bitrix24Account.php | 36 ++++++++++++++----- 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/Makefile b/Makefile index 46f7bba..3a45450 100644 --- a/Makefile +++ b/Makefile @@ -99,7 +99,7 @@ test-run-phpstan: # unit-tests test-run-unit-tests: - docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=unit --testdox + docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=unit_tests --testdox # functional-tests, work with test database test-run-functional-tests: diff --git a/composer.json b/composer.json index f912eaf..68aa091 100644 --- a/composer.json +++ b/composer.json @@ -41,7 +41,7 @@ "darsyn/ip": "^5", "nesbot/carbon": "^3", "moneyphp/money": "^4", - "mesilov/bitrix24-php-sdk": "^2", + "bitrix24/b24phpsdk": "^1", "doctrine/orm": "^3", "doctrine/doctrine-bundle": "*", "doctrine/doctrine-migrations-bundle": "*", @@ -52,8 +52,7 @@ "symfony/yaml": "^7", "symfony/cache": "^7", "symfony/console": "^7", - "symfony/dotenv": "^7", - "symfony/framework-bundle": "^7" + "symfony/dotenv": "^7" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.59", @@ -75,7 +74,7 @@ "autoload-dev": { "psr-4": { "Bitrix24\\SDK\\Lib\\Tests\\": "tests", - "Bitrix24\\SDK\\Tests\\": "vendor/mesilov/bitrix24-php-sdk/tests" + "Bitrix24\\SDK\\Tests\\": "vendor/bitrix24/b24phpsdk/tests" } } } diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 527f5b1..23bf099 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -21,10 +21,24 @@ use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; use Carbon\CarbonImmutable; use Override; +use Symfony\Bridge\Doctrine\Types\UuidType; +use Symfony\Component\Serializer\Annotation\SerializedName; use Symfony\Component\Uid\Uuid; +use Doctrine\ORM\Mapping as ORM; class Bitrix24Account implements Bitrix24AccountInterface { + #[ORM\Id] + #[ORM\Column(type: UuidType::NAME, unique: true)] + private readonly Uuid $id; + #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] + #[SerializedName('b24_user_id')] + private readonly int $bitrix24UserId; + /** bitrix24 portal unique id */ + #[ORM\Column(name: 'member_id', type: 'string', nullable: false)] + #[SerializedName('member_id')] + private readonly string $memberId; + private string $accessToken; private string $refreshToken; @@ -38,10 +52,10 @@ class Bitrix24Account implements Bitrix24AccountInterface private ?string $comment = null; public function __construct( - private readonly Uuid $id, - private readonly int $bitrix24UserId, + Uuid $id, + int $bitrix24UserId, private readonly bool $isBitrix24UserAdmin, - private readonly string $memberId, + string $memberId, private string $domainUrl, private Bitrix24AccountStatus $accountStatus, AuthToken $authToken, @@ -51,9 +65,13 @@ public function __construct( Scope $applicationScope, ) { - $this->accessToken = $authToken->getAccessToken(); - $this->refreshToken = $authToken->getRefreshToken(); - $this->expires = $authToken->getExpires(); + $this->id = $id; + $this->bitrix24UserId = $bitrix24UserId; + $this->memberId = $memberId; + + $this->accessToken = $authToken->accessToken; + $this->refreshToken = $authToken->refreshToken; + $this->expires = $authToken->expires; $this->applicationScope = $applicationScope->getScopeCodes(); } @@ -117,9 +135,9 @@ public function renewAuthToken(RenewedAuthToken $renewedAuthToken): void ); } - $this->accessToken = $renewedAuthToken->authToken->getAccessToken(); - $this->refreshToken = $renewedAuthToken->authToken->getRefreshToken(); - $this->expires = $renewedAuthToken->authToken->getExpires(); + $this->accessToken = $renewedAuthToken->authToken->accessToken; + $this->refreshToken = $renewedAuthToken->authToken->refreshToken; + $this->expires = $renewedAuthToken->authToken->expires; $this->updatedAt = new CarbonImmutable(); } From 85dafa172507426ae7263bb1e7f786e176632a5b Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 7 Oct 2024 00:49:01 +0600 Subject: [PATCH 007/130] Refactor Docker setup and Bitrix24Account entity Removed custom Docker configurations for nginx, PHP-FPM, and PostgreSQL to streamline the Docker environment. Introduced a centralized environment configuration using .env and Symfony Dotenv. Additionally, refactored the Bitrix24Account entity and its repository to enhance code maintainability and align with best practices. Signed-off-by: mesilov --- .env | 18 +++ Makefile | 67 +++------ bin/doctrine | 13 ++ composer.json | 1 + config/cli-config.php | 19 +++ docker-compose.yaml | 31 +--- docker/nginx/Dockerfile | 5 - docker/nginx/conf.d/nginx.conf | 20 --- docker/php-fpm/Dockerfile | 13 -- docker/postgres/Dockerfile | 12 -- index.php | 17 --- migrations.php | 20 +++ phpunit.xml.dist | 4 +- .../Entity/Bitrix24Account.php | 31 ++-- .../Doctrine/Bitrix24AccountRepository.php | 134 ++++++++++++++++++ src/Bitrix24Accounts/ReadModel/Fetcher.php | 45 ++++++ tests/EntityManagerFactory.php | 70 +++++++++ tests/bootstrap.php | 21 ++- 18 files changed, 379 insertions(+), 162 deletions(-) create mode 100644 .env create mode 100644 bin/doctrine create mode 100644 config/cli-config.php delete mode 100644 docker/nginx/Dockerfile delete mode 100644 docker/nginx/conf.d/nginx.conf delete mode 100644 docker/php-fpm/Dockerfile delete mode 100644 docker/postgres/Dockerfile delete mode 100644 index.php create mode 100644 migrations.php create mode 100644 src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php create mode 100644 src/Bitrix24Accounts/ReadModel/Fetcher.php create mode 100644 tests/EntityManagerFactory.php diff --git a/.env b/.env new file mode 100644 index 0000000..4fda991 --- /dev/null +++ b/.env @@ -0,0 +1,18 @@ +# In all environments, the following files are loaded if they exist, +# the latter taking precedence over the former: +# +# * .env contains default values for the environment variables needed by the app +# * .env.local uncommitted file with local overrides +# * .env.$APP_ENV committed environment-specific defaults +# * .env.$APP_ENV.local uncommitted environment-specific overrides +# +# Real environment variables win over .env files. +# +# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES. +# +# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2). +# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration +DATABASE_HOST=bitrix24-php-lib-test-database +DATABASE_USER= +DATABASE_PASSWORD= +DATABASE_NAME= \ No newline at end of file diff --git a/Makefile b/Makefile index 3a45450..edf0678 100644 --- a/Makefile +++ b/Makefile @@ -13,32 +13,8 @@ default: @echo "make needs target:" @egrep -e '^\S+' ./Makefile | grep -v default | sed -r 's/://' | sed -r 's/^/ - /' -# linters -lint-phpstan: - vendor/bin/phpstan --memory-limit=1G analyse -lint-rector: - vendor/bin/rector process --dry-run -lint-rector-fix: - vendor/bin/rector process - -# unit tests -test-unit: - vendor/bin/phpunit --testsuite unit_tests --display-warnings - -test-integration: - vendor/bin/phpunit --testsuite integration_tests --display-warnings - - -# docker file - -docker-up: - docker compose up --build -d - -docker-down: - docker compose down --remove-orphans - -#====================================== -restart: down up +%: + @: # silence init: @echo "remove all containers" @@ -47,17 +23,14 @@ init: docker-compose build @echo "install dependencies" docker-compose run --rm php-cli composer install -# @echo "run database migrations…" -# docker-compose run --rm php-cli php bin/doctrine doctrine:migrations:migrate --no-interaction @echo "change owner of var folder for access from container" docker-compose run --rm php-cli chown -R www-data:www-data /var/www/html/var/ @echo "run application…" docker-compose up -d - up: @echo "run application…" - docker-compose up -d + docker-compose up --build -d down: @echo "stop application and remove containers" @@ -67,15 +40,21 @@ down-clear: @echo "stop application and remove containers with volumes" docker-compose down -v --remove-orphans +restart: down up + +# работа с контейнерами +php-cli-bash: + docker-compose run --rm php-cli sh $(filter-out $@,$(MAKECMDGOALS)) +# работа с composer composer-install: @echo "install dependencies…" docker-compose run --rm php-cli composer install - composer-update: @echo "update dependencies…" docker-compose run --rm php-cli composer update - +composer-dumpautoload: + docker-compose run --rm php-cli composer dumpautoload # вызов composer с любыми параметрами # Примеры: # make composer install @@ -83,26 +62,20 @@ composer-update: composer: docker-compose run --rm php-cli composer $(filter-out $@,$(MAKECMDGOALS)) -%: - @: # silence - -dev-dump-cache: - composer dumpautoload - -#====================================== -cli-bash: - docker-compose run --rm php-cli sh $(filter-out $@,$(MAKECMDGOALS)) - -# static code analysis -test-run-phpstan: +# linters +lint-phpstan: docker-compose run --rm php-cli php vendor/bin/phpstan analyse --memory-limit 2G +lint-rector: + docker-compose run --rm php-cli php vendor/bin/rector process --dry-run +lint-rector-fix: + docker-compose run --rm php-cli php vendor/bin/rector process # unit-tests -test-run-unit-tests: - docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=unit_tests --testdox +test-run-unit: + docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox # functional-tests, work with test database -test-run-functional-tests: +test-run-functional: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional --testdox \ No newline at end of file diff --git a/bin/doctrine b/bin/doctrine new file mode 100644 index 0000000..9f213bc --- /dev/null +++ b/bin/doctrine @@ -0,0 +1,13 @@ +#!/usr/bin/env php + 'pdo_pgsql', + 'memory' => true, + 'dbname' => 'b24AccountTest', + ]); + +return DependencyFactory::fromConnection($config, new ExistingConnection($conn)); \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml index 0e7a7d1..0105355 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,37 +1,14 @@ services: - php-fpm: - build: - context: ./docker/php-fpm - volumes: - - ./:/var/www/bitrix24-php-lib - nginx: - build: - context: ./docker/nginx - volumes: - - ./:/var/www/bitrix24-php-lib - ports: - - "8081:80" - depends_on: - - php-fpm - postgres-container: - image: postgres - build: - context: ./docker/postgres - ports: - - "5432:5432" - volumes: - - ./docker/postgres/data:/var/lib/postgresql/data - restart: always php-cli: build: context: ./docker/php-cli links: - - b24-account-test-database + - database volumes: - .:/var/www/html working_dir: /var/www/html - b24-account-test-database: - image: postgres:${POSTGRES_VERSION:-15}-alpine + database: + image: postgres:${POSTGRES_VERSION:-16}-alpine restart: unless-stopped environment: POSTGRES_DB: ${POSTGRES_DB:-b24AccountTest} @@ -39,7 +16,7 @@ services: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-b24AccountTest} POSTGRES_USER: ${POSTGRES_USER:-b24AccountTest} PGDATA: "/var/lib/postgresql/data/pgdata" - container_name: b24-account-test-database + container_name: bitrix24-php-lib-test-database ports: - '5432:5432' expose: diff --git a/docker/nginx/Dockerfile b/docker/nginx/Dockerfile deleted file mode 100644 index 922b636..0000000 --- a/docker/nginx/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM nginx:1.27-alpine - -RUN rm /etc/nginx/conf.d/default.conf - -COPY ./conf.d/nginx.conf /etc/nginx/conf.d/ \ No newline at end of file diff --git a/docker/nginx/conf.d/nginx.conf b/docker/nginx/conf.d/nginx.conf deleted file mode 100644 index 7ef599a..0000000 --- a/docker/nginx/conf.d/nginx.conf +++ /dev/null @@ -1,20 +0,0 @@ -server { - listen 80; - server_name localhost; - - root /var/www/bitrix24-php-lib; - index index.html index.htm index.php; - - # Redirects requests to index.php if the file is not found - location / { - try_files $uri $uri/ /index.php?$query_string; - } - - # Passes PHP requests to PHP-FPM container - location ~ \.php$ { - include fastcgi_params; - fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; - fastcgi_pass php-fpm:9000; # Replace with your PHP-FPM container name - fastcgi_index index.php; - } -} \ No newline at end of file diff --git a/docker/php-fpm/Dockerfile b/docker/php-fpm/Dockerfile deleted file mode 100644 index 67daccf..0000000 --- a/docker/php-fpm/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -FROM php:8.2-fpm-alpine - -RUN set -ex \ - && apk --no-cache add \ - postgresql-dev \ - oniguruma-dev \ - libzip-dev \ - curl-dev \ - && docker-php-ext-install pdo pdo_pgsql mbstring zip curl bcmath - -WORKDIR /bitrix24-php-lib - -COPY ./ ./ \ No newline at end of file diff --git a/docker/postgres/Dockerfile b/docker/postgres/Dockerfile deleted file mode 100644 index 8d7a370..0000000 --- a/docker/postgres/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM postgres:16.4-alpine - -# Устанавливаем переменные окружения для настройки базы данных -ENV POSTGRES_USER=kirill -ENV POSTGRES_PASSWORD=bitrix24lib -ENV POSTGRES_DB=bitrixAppDb - -# Копируем SQL-скрипты для инициализации базы данных (если есть) -# COPY init.sql /docker-entrypoint-initdb.d/ - -# Открываем порт PostgreSQL -EXPOSE 5432 \ No newline at end of file diff --git a/index.php b/index.php deleted file mode 100644 index b70805a..0000000 --- a/index.php +++ /dev/null @@ -1,17 +0,0 @@ -"; -$conn_string = "pgsql:host=localhost;port=5432;dbname=bitrixAppDb;user=kirill;password=bitrix24lib"; -try { - $db = new PDO($conn_string); - - // Установка режима обработки ошибок - $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - echo "Подключение к базе данных успешно установлено."; -}catch (PDOException $error) -{ - echo "Ошибка :". $error->getMessage(); -} - -?> diff --git a/migrations.php b/migrations.php new file mode 100644 index 0000000..73e85a8 --- /dev/null +++ b/migrations.php @@ -0,0 +1,20 @@ + [ + 'table_name' => 'b24AccountsDoctrineMigrationVersions', + 'version_column_name' => 'version', + 'version_column_length' => 1024, + 'executed_at_column_name' => 'executed_at', + 'execution_time_column_name' => 'execution_time', + ], + 'migrations_paths' => [ + 'B24io\Core\Bitrix24\Account\Migrations' => '/migrations/', + ], + 'all_or_nothing' => true, + 'transactional' => true, + 'check_database_platform' => true, + 'organize_migrations' => 'none', + 'connection' => null, + 'em' => null, +]; \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 0f572c3..fee6376 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -10,8 +10,8 @@ ./tests/Unit - - ./tests/Integration + + ./tests/Functional diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 23bf099..c4eb3ed 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -22,23 +22,13 @@ use Carbon\CarbonImmutable; use Override; use Symfony\Bridge\Doctrine\Types\UuidType; +use Symfony\Component\Serializer\Annotation\Ignore; use Symfony\Component\Serializer\Annotation\SerializedName; use Symfony\Component\Uid\Uuid; use Doctrine\ORM\Mapping as ORM; class Bitrix24Account implements Bitrix24AccountInterface { - #[ORM\Id] - #[ORM\Column(type: UuidType::NAME, unique: true)] - private readonly Uuid $id; - #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] - #[SerializedName('b24_user_id')] - private readonly int $bitrix24UserId; - /** bitrix24 portal unique id */ - #[ORM\Column(name: 'member_id', type: 'string', nullable: false)] - #[SerializedName('member_id')] - private readonly string $memberId; - private string $accessToken; private string $refreshToken; @@ -52,23 +42,28 @@ class Bitrix24Account implements Bitrix24AccountInterface private ?string $comment = null; public function __construct( - Uuid $id, - int $bitrix24UserId, + #[ORM\Id] + #[ORM\Column(type: UuidType::NAME, unique: true)] + private readonly Uuid $id, + #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] + #[SerializedName('b24_user_id')] + private readonly int $bitrix24UserId, private readonly bool $isBitrix24UserAdmin, - string $memberId, + /** bitrix24 portal unique id */ + #[ORM\Column(name: 'member_id', type: 'string', nullable: false)] + #[SerializedName('member_id')] + private readonly string $memberId, private string $domainUrl, private Bitrix24AccountStatus $accountStatus, AuthToken $authToken, + #[ORM\Column(name: 'created_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] + #[Ignore] private readonly CarbonImmutable $createdAt, private CarbonImmutable $updatedAt, private int $applicationVersion, Scope $applicationScope, ) { - $this->id = $id; - $this->bitrix24UserId = $bitrix24UserId; - $this->memberId = $memberId; - $this->accessToken = $authToken->accessToken; $this->refreshToken = $authToken->refreshToken; $this->expires = $authToken->expires; diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php new file mode 100644 index 0000000..5f9f481 --- /dev/null +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -0,0 +1,134 @@ +getClassMetadata(Bitrix24Account::class)); + } + + /** + * @inheritdoc + */ + #[Override] + public function getById(Uuid $uuid): Bitrix24AccountInterface + { + $res = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); + if ($res === null) { + throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); + } + + return $res; + } + + /** + * @inheritdoc + */ + #[Override] + public function save(Bitrix24AccountInterface $bitrix24Account, bool $flush = false): void + { + $this->getEntityManager()->persist($bitrix24Account); + + if ($flush) { + $this->getEntityManager()->flush(); + } + } + + + #[Override] + public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?bool $isAdmin = null): array + { + return $this->findBy( + [ + 'memberId' => $memberId, + 'status' => [ + Bitrix24AccountStatus::new->name, + Bitrix24AccountStatus::active->name, + ] + ] + ); + } + + + /** + * @inheritdoc + */ + #[Override] + public function delete(Uuid $uuid, bool $flush = false): void + { + $bitrix24Account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); + if ($bitrix24Account === null) { + throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); + } + $this->getEntityManager()->remove($bitrix24Account); + + if ($flush) { + $this->getEntityManager()->flush(); + } + } + + public function findAllActive(): array + { + return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findBy( + [ + 'status' => Bitrix24AccountStatus::active, + ] + ); + } + + /** + * @throws InvalidArgumentException + */ + #[Override] + public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterface + { + if (trim($memberId) === '') { + throw new InvalidArgumentException('memberId cannot be an empty string'); + } + return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findOneBy( + [ + 'memberId' => $memberId, + 'isBitrix24UserAdmin' => true, + 'status' => Bitrix24AccountStatus::active, + ] + ); + } + + /** + * @throws InvalidArgumentException + */ + #[Override] + public function findByDomain(string $domainUrl, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?bool $isAdmin = null): array + { + if (trim($domainUrl) === '') { + throw new InvalidArgumentException('domainUrl cannot be an empty string'); + } + + $criteria = [ + 'domainUrl' => $domainUrl, + ]; + if ($bitrix24AccountStatus !== null) { + $criteria['status'] = $bitrix24AccountStatus->name; + } + if ($isAdmin !== null) { + $criteria['isBitrix24UserAdmin'] = $isAdmin; + } + + return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findBy($criteria); + } +} \ No newline at end of file diff --git a/src/Bitrix24Accounts/ReadModel/Fetcher.php b/src/Bitrix24Accounts/ReadModel/Fetcher.php new file mode 100644 index 0000000..2ce310d --- /dev/null +++ b/src/Bitrix24Accounts/ReadModel/Fetcher.php @@ -0,0 +1,45 @@ +em = $em; + $this->paginator = $paginator; + } + + public function list( + int $page, + int $size + ): PaginationInterface + { + $qb = $this->em->getConnection()->createQueryBuilder() + ->select( + 'b24account.id as id', + 'b24account.status as status', + 'b24account.member_id as member_id', + 'b24account.domain_url as domain_url', + 'b24account.app_version as application_version', + 'b24account.created_at_utc as created_at', + 'b24account.updated_at_utc as updated_at', + ) + ->from('bitrix24account', 'b24account') + ->orderBy('b24account.created_at_utc', 'DESC'); + + return $this->paginator->paginate($qb, $page, $size); + } +} \ No newline at end of file diff --git a/tests/EntityManagerFactory.php b/tests/EntityManagerFactory.php new file mode 100644 index 0000000..63c38ff --- /dev/null +++ b/tests/EntityManagerFactory.php @@ -0,0 +1,70 @@ + 'pdo_pgsql', + 'host' => $_ENV['DATABASE_HOST'], + 'user' => $_ENV['DATABASE_USER'], + 'password' => $_ENV['DATABASE_PASSWORD'], + 'dbname' => $_ENV['DATABASE_NAME'], + ]; + if (!Type::hasType(UuidType::NAME)) { + Type::addType(UuidType::NAME, UuidType::class); + } + if (!Type::hasType('carbon_immutable')) { + Type::addType('carbon_immutable', CarbonImmutableType::class); + } + + $config = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode); + $connection = DriverManager::getConnection($connectionParams, $config); + $entityManager = new EntityManager($connection, $config); + // todo разобраться, почему так, без этого объекты оставались в кеше и при find мы получали старые значения + $entityManager->clear(); + $entityManager->flush(); + return $entityManager; + } +} \ No newline at end of file diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 94def9c..9003ecd 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -11,4 +11,23 @@ declare(strict_types=1); -require_once dirname(__DIR__) . '/vendor/autoload.php'; \ No newline at end of file +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Dotenv\Dotenv; + +require_once dirname(__DIR__) . '/vendor/autoload.php'; +require_once dirname(__DIR__) . '/tests/EntityManagerFactory.php'; + +if (!class_exists(Dotenv::class)) { + throw new LogicException('You need to add "symfony/dotenv" as Composer dependencies.'); +} + +$input = new ArgvInput(); +if (null !== $env = $input->getParameterOption(['--env', '-e'], null, true)) { + putenv('APP_ENV=' . $_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = $env); +} + +if ($input->hasParameterOption('--no-debug', true)) { + putenv('APP_DEBUG=' . $_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0'); +} + +(new Dotenv())->loadEnv(dirname(__DIR__) . '/.env'); \ No newline at end of file From 1eed7853b30340f6613618b483f8e34b4612b947 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 7 Oct 2024 00:52:04 +0600 Subject: [PATCH 008/130] Update .gitignore to exclude /docker/postgres directory. Added /docker/postgres directory to the .gitignore file to prevent it from being tracked by Git. This ensures that local PostgreSQL database files are not included in the repository. Signed-off-by: mesilov --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index eb0a19d..6d31c13 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ /vendor /.cache /docker/db +/docker/postgres composer.phar composer.lock .phpunit.result.cache From 1ecbe1c7c9acce5dc9acd5716372034dd71a1120 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 7 Oct 2024 01:13:14 +0600 Subject: [PATCH 009/130] Add custom repository to Bitrix24Account This change integrates the Bitrix24AccountRepository with the Bitrix24Account entity. The repository will handle database interactions specific to Bitrix24Account instances. This update enhances the modularity and maintainability of the codebase. Signed-off-by: mesilov --- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index c4eb3ed..bae10ba 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -19,6 +19,7 @@ use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Bitrix24\SDK\Core\Exceptions\UnknownScopeCodeException; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; +use Bitrix24\SDK\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Carbon\CarbonImmutable; use Override; use Symfony\Bridge\Doctrine\Types\UuidType; @@ -27,6 +28,7 @@ use Symfony\Component\Uid\Uuid; use Doctrine\ORM\Mapping as ORM; +#[ORM\Entity(repositoryClass: Bitrix24AccountRepository::class)] class Bitrix24Account implements Bitrix24AccountInterface { private string $accessToken; From ace91891ebf57f2d1a3846efeb4a0daf98614012 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 7 Oct 2024 01:21:09 +0600 Subject: [PATCH 010/130] Add functional test for Bitrix24AccountRepository Introduced `Bitrix24AccountRepositoryTest` to ensure the repository's correct functionality. Modified the Makefile to run the functional tests suite with more detailed output including warnings. Signed-off-by: mesilov --- Makefile | 2 +- .../Bitrix24AccountRepositoryTest.php | 67 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php diff --git a/Makefile b/Makefile index edf0678..b794559 100644 --- a/Makefile +++ b/Makefile @@ -78,4 +78,4 @@ test-run-unit: test-run-functional: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create - docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional --testdox \ No newline at end of file + docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php new file mode 100644 index 0000000..9dede5d --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the MIT-LICENSE.txt + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Bitrix24\SDK\Lib\Tests\Functional\Bitrix24Accounts\Infrastructure\Doctrine; + +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; +use Bitrix24\SDK\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\SDK\Lib\Tests\EntityManagerFactory; +use Bitrix24\SDK\Tests\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterfaceTest; +use Carbon\CarbonImmutable; +use Override; +use PHPUnit\Framework\Attributes\CoversClass; +use Symfony\Component\Uid\Uuid; + +#[CoversClass(Bitrix24AccountRepository::class)] +class Bitrix24AccountRepositoryTest extends Bitrix24AccountRepositoryInterfaceTest +{ + #[Override] + protected function createBitrix24AccountImplementation( + Uuid $uuid, + int $bitrix24UserId, + bool $isBitrix24UserAdmin, + string $memberId, + string $domainUrl, + Bitrix24AccountStatus $bitrix24AccountStatus, + AuthToken $authToken, + CarbonImmutable $createdAt, + CarbonImmutable $updatedAt, + int $applicationVersion, + Scope $applicationScope + ): Bitrix24AccountInterface + { + return new Bitrix24Account( + $uuid, + $bitrix24UserId, + $isBitrix24UserAdmin, + $memberId, + $domainUrl, + $bitrix24AccountStatus, + $authToken, + $createdAt, + $updatedAt, + $applicationVersion, + $applicationScope + ); + } + + protected function createBitrix24AccountRepositoryImplementation(): Bitrix24AccountRepositoryInterface + { + return new Bitrix24AccountRepository(EntityManagerFactory::get()); + } +} \ No newline at end of file From 85ceeb4ed90f122464dff0a00c08a51b6360e9d1 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 7 Oct 2024 01:22:05 +0600 Subject: [PATCH 011/130] Remove /docker/postgres from .gitignore The /docker/postgres directory is no longer required to be ignored by Git. This change ensures that any important files in this directory can now be tracked and versioned. Signed-off-by: mesilov --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6d31c13..eb0a19d 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ /vendor /.cache /docker/db -/docker/postgres composer.phar composer.lock .phpunit.result.cache From e6c002b507850d10cf4f57589ac9dbb58034ec11 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 7 Oct 2024 01:33:04 +0600 Subject: [PATCH 012/130] Refactor repository and entity manager usage. Standardize usage of EntityManagerInterface and improve type inconsistencies. Apply `#[Override]` attribute in tests, and add null checks and validation for better robustness. Signed-off-by: mesilov --- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 6 +++--- .../Doctrine/Bitrix24AccountRepository.php | 9 ++++++--- src/Bitrix24Accounts/ReadModel/Fetcher.php | 14 ++++---------- tests/EntityManagerFactory.php | 10 +++++++--- .../Doctrine/Bitrix24AccountRepositoryTest.php | 1 + 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index bae10ba..f7d5e54 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -46,15 +46,15 @@ class Bitrix24Account implements Bitrix24AccountInterface public function __construct( #[ORM\Id] #[ORM\Column(type: UuidType::NAME, unique: true)] - private readonly Uuid $id, + private readonly Uuid $id, #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] #[SerializedName('b24_user_id')] - private readonly int $bitrix24UserId, + private readonly int $bitrix24UserId, private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ #[ORM\Column(name: 'member_id', type: 'string', nullable: false)] #[SerializedName('member_id')] - private readonly string $memberId, + private readonly string $memberId, private string $domainUrl, private Bitrix24AccountStatus $accountStatus, AuthToken $authToken, diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 5f9f481..e1c92e6 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -10,14 +10,14 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Bitrix24\SDK\Lib\Bitrix24Accounts\Entity\Bitrix24Account; -use Doctrine\ORM\EntityManager; +use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; use Override; use Symfony\Component\Uid\Uuid; class Bitrix24AccountRepository extends EntityRepository implements Bitrix24AccountRepositoryInterface { - public function __construct(EntityManager $entityManager) + public function __construct(EntityManagerInterface $entityManager) { parent::__construct($entityManager, $entityManager->getClassMetadata(Bitrix24Account::class)); } @@ -75,6 +75,7 @@ public function delete(Uuid $uuid, bool $flush = false): void if ($bitrix24Account === null) { throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); } + $this->getEntityManager()->remove($bitrix24Account); if ($flush) { @@ -100,6 +101,7 @@ public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterf if (trim($memberId) === '') { throw new InvalidArgumentException('memberId cannot be an empty string'); } + return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findOneBy( [ 'memberId' => $memberId, @@ -122,9 +124,10 @@ public function findByDomain(string $domainUrl, ?Bitrix24AccountStatus $bitrix24 $criteria = [ 'domainUrl' => $domainUrl, ]; - if ($bitrix24AccountStatus !== null) { + if ($bitrix24AccountStatus instanceof \Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus) { $criteria['status'] = $bitrix24AccountStatus->name; } + if ($isAdmin !== null) { $criteria['isBitrix24UserAdmin'] = $isAdmin; } diff --git a/src/Bitrix24Accounts/ReadModel/Fetcher.php b/src/Bitrix24Accounts/ReadModel/Fetcher.php index 2ce310d..45b2e6b 100644 --- a/src/Bitrix24Accounts/ReadModel/Fetcher.php +++ b/src/Bitrix24Accounts/ReadModel/Fetcher.php @@ -10,16 +10,10 @@ class Fetcher { - private EntityManagerInterface $em; - private PaginatorInterface $paginator; - public function __construct( - EntityManagerInterface $em, - PaginatorInterface $paginator - ) + private readonly EntityManagerInterface $em, + private readonly PaginatorInterface $paginator) { - $this->em = $em; - $this->paginator = $paginator; } public function list( @@ -27,7 +21,7 @@ public function list( int $size ): PaginationInterface { - $qb = $this->em->getConnection()->createQueryBuilder() + $queryBuilder = $this->em->getConnection()->createQueryBuilder() ->select( 'b24account.id as id', 'b24account.status as status', @@ -40,6 +34,6 @@ public function list( ->from('bitrix24account', 'b24account') ->orderBy('b24account.created_at_utc', 'DESC'); - return $this->paginator->paginate($qb, $page, $size); + return $this->paginator->paginate($queryBuilder, $page, $size); } } \ No newline at end of file diff --git a/tests/EntityManagerFactory.php b/tests/EntityManagerFactory.php index 63c38ff..a04e483 100644 --- a/tests/EntityManagerFactory.php +++ b/tests/EntityManagerFactory.php @@ -35,12 +35,15 @@ public static function get(): EntityManagerInterface if (!array_key_exists('DATABASE_HOST', $_ENV)) { throw new WrongConfigurationException('DATABASE_HOST not defined in $_ENV'); } + if (!array_key_exists('DATABASE_USER', $_ENV)) { throw new WrongConfigurationException('DATABASE_USER not defined in $_ENV'); } + if (!array_key_exists('DATABASE_PASSWORD', $_ENV)) { throw new WrongConfigurationException('DATABASE_PASSWORD not defined in $_ENV'); } + if (!array_key_exists('DATABASE_NAME', $_ENV)) { throw new WrongConfigurationException('DATABASE_NAME not defined in $_ENV'); } @@ -55,13 +58,14 @@ public static function get(): EntityManagerInterface if (!Type::hasType(UuidType::NAME)) { Type::addType(UuidType::NAME, UuidType::class); } + if (!Type::hasType('carbon_immutable')) { Type::addType('carbon_immutable', CarbonImmutableType::class); } - $config = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode); - $connection = DriverManager::getConnection($connectionParams, $config); - $entityManager = new EntityManager($connection, $config); + $configuration = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode); + $connection = DriverManager::getConnection($connectionParams, $configuration); + $entityManager = new EntityManager($connection, $configuration); // todo разобраться, почему так, без этого объекты оставались в кеше и при find мы получали старые значения $entityManager->clear(); $entityManager->flush(); diff --git a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php index 9dede5d..a4ff8d8 100644 --- a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php +++ b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php @@ -60,6 +60,7 @@ protected function createBitrix24AccountImplementation( ); } + #[Override] protected function createBitrix24AccountRepositoryImplementation(): Bitrix24AccountRepositoryInterface { return new Bitrix24AccountRepository(EntityManagerFactory::get()); From f442badd68ece2e425505570a443eb4f262d39d5 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 7 Oct 2024 01:40:18 +0600 Subject: [PATCH 013/130] Update PHPStan command in GitHub Actions workflow Replaced the 'make lint-phpstan' command with a direct call to 'vendor/bin/phpstan --memory-limit=2G analyse.' This change ensures better control over memory usage and eliminates the dependency on the Makefile. Signed-off-by: mesilov --- .github/workflows/phpstan.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index 03760bc..9cf8ab2 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -38,7 +38,7 @@ jobs: run: "composer update --no-interaction --no-progress --no-suggest" - name: "PHPStan" - run: "make lint-phpstan" + run: "vendor/bin/phpstan --memory-limit=2G analyse" - name: "is PHPStan check succeeded" if: ${{ success() }} From 5817e70c6c4cf26e3ac7c230dd4c52accb2c8e4a Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 7 Oct 2024 01:42:04 +0600 Subject: [PATCH 014/130] Update Rector command in GitHub workflow Replaced `make lint-rector` with `vendor/bin/rector process --dry-run` for better control and customization of the Rector tool in CI pipeline. This change ensures a direct invocation of Rector with specified options without intermediary make tasks. Signed-off-by: mesilov --- .github/workflows/rector.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/rector.yml b/.github/workflows/rector.yml index 4a0bf8a..ec35b52 100644 --- a/.github/workflows/rector.yml +++ b/.github/workflows/rector.yml @@ -38,7 +38,7 @@ jobs: run: "composer update --no-interaction --no-progress --no-suggest" - name: "Rector" - run: "make lint-rector" + run: "vendor/bin/rector process --dry-run" - name: "is Rector check succeeded" if: ${{ success() }} From 93ad32a141358c1e21ee6186468bfadf544d5494 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 10 Oct 2024 21:15:13 +0600 Subject: [PATCH 015/130] Create functional test workflow and update configurations Add a new GitHub workflow for functional tests with specified environments and steps. Update `docker-compose.yaml` to reflect the new PostgreSQL database settings. Rename existing workflows for clarity and consistency. Signed-off-by: mesilov --- .../{phpstan.yml => lint-phpstan.yml} | 0 .../workflows/{rector.yml => lint-rector.yml} | 0 .github/workflows/tests-functional.yml | 71 +++++++++++++++++++ .../workflows/{phpunit.yml => tests-unit.yml} | 2 +- docker-compose.yaml | 6 +- 5 files changed, 75 insertions(+), 4 deletions(-) rename .github/workflows/{phpstan.yml => lint-phpstan.yml} (100%) rename .github/workflows/{rector.yml => lint-rector.yml} (100%) create mode 100644 .github/workflows/tests-functional.yml rename .github/workflows/{phpunit.yml => tests-unit.yml} (98%) diff --git a/.github/workflows/phpstan.yml b/.github/workflows/lint-phpstan.yml similarity index 100% rename from .github/workflows/phpstan.yml rename to .github/workflows/lint-phpstan.yml diff --git a/.github/workflows/rector.yml b/.github/workflows/lint-rector.yml similarity index 100% rename from .github/workflows/rector.yml rename to .github/workflows/lint-rector.yml diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml new file mode 100644 index 0000000..2c3419e --- /dev/null +++ b/.github/workflows/tests-functional.yml @@ -0,0 +1,71 @@ +name: "Functional tests" + +on: + push: + pull_request: + +env: + COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist" + +jobs: + tests: + name: "Functional tests" + + runs-on: ${{ matrix.operating-system }} + + strategy: + fail-fast: false + matrix: + php-version: + - "8.3" + dependencies: [ highest ] + operating-system: [ ubuntu-latest] + services: + bitrix24-php-lib-test-database: + image: postgres:16 + ports: + - 5432:5432 + options: >- + --health-cmd="pg_isready -U postgres" + --health-interval=10s + --health-timeout=5s + --health-retries=5 + env: + POSTGRES_USER: b24phpLibTest + POSTGRES_PASSWORD: b24phpLibTest + POSTGRES_DB: b24phpLibTest + + steps: + - name: "Checkout code" + uses: "actions/checkout@v2" + + - name: "Setup PHP" + uses: "shivammathur/setup-php@v2" + with: + coverage: "none" + php-version: "${{ matrix.php-version }}" + extensions: json, bcmath, curl, intl, mbstring, pdo_pgsql, pdo + + - name: "Install dependencies with Composer" + run: | + composer update ${{ env.COMPOSER_FLAGS }} + + - name: "Wait for PostgreSQL to be ready" + run: | + until pg_isready -h localhost -p 5432 -U user; do + echo "Waiting for PostgreSQL to start..." + sleep 2 + done + + - name: "Run functional tests" + run: "make test-functional" + + - name: "is functional tests succeeded" + if: ${{ success() }} + run: | + echo '✅ functional tests pass, congratulations!' + + - name: "is functional tests failed" + if: ${{ failure() }} + run: | + echo '::error:: ❗️ functional tests failed (╯°益°)╯彡┻━┻' \ No newline at end of file diff --git a/.github/workflows/phpunit.yml b/.github/workflows/tests-unit.yml similarity index 98% rename from .github/workflows/phpunit.yml rename to .github/workflows/tests-unit.yml index 32152d5..d4b410c 100644 --- a/.github/workflows/phpunit.yml +++ b/.github/workflows/tests-unit.yml @@ -1,4 +1,4 @@ -name: "PHPUnit tests" +name: "Unit tests" on: push: diff --git a/docker-compose.yaml b/docker-compose.yaml index 0105355..4923ef9 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -11,10 +11,10 @@ services: image: postgres:${POSTGRES_VERSION:-16}-alpine restart: unless-stopped environment: - POSTGRES_DB: ${POSTGRES_DB:-b24AccountTest} + POSTGRES_DB: ${POSTGRES_DB:-b24phpLibTest} # You should definitely change the password in production - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-b24AccountTest} - POSTGRES_USER: ${POSTGRES_USER:-b24AccountTest} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-b24phpLibTest} + POSTGRES_USER: ${POSTGRES_USER:-b24phpLibTest} PGDATA: "/var/lib/postgresql/data/pgdata" container_name: bitrix24-php-lib-test-database ports: From 1a9bb104af86cf76f2191dbc249973c53261df3d Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 10 Oct 2024 21:19:16 +0600 Subject: [PATCH 016/130] Switch to direct phpunit command for unit tests Replaced the "make test-unit" command with a direct call to phpunit in the GitHub Actions workflow for better clarity and control over the test execution. This change uses the phpunit command with options for test suite, warnings, and formatted output. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index d4b410c..91ada7d 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -37,7 +37,7 @@ jobs: composer update ${{ env.COMPOSER_FLAGS }} - name: "run unit tests" - run: "make test-unit" + run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" - name: "is unit tests tests succeeded" if: ${{ success() }} From 5aaedd75451e05f9895fc91812cdbf195da62a05 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 10 Oct 2024 21:21:59 +0600 Subject: [PATCH 017/130] Update functional test workflow to include DB setup Modified the functional test workflow to drop and recreate the database schema before running tests. This ensures a consistent test environment and improves test reliability. Signed-off-by: mesilov --- .github/workflows/tests-functional.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 2c3419e..87133ea 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -58,7 +58,10 @@ jobs: done - name: "Run functional tests" - run: "make test-functional" + run: | + php bin/doctrine orm:schema-tool:drop --force + php bin/doctrine orm:schema-tool:create + php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox - name: "is functional tests succeeded" if: ${{ success() }} From 6fce03d609401393b1df9b540997fffff17119fb Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 10 Oct 2024 21:27:43 +0600 Subject: [PATCH 018/130] Update DB env variables in workflow configuration Changed the environment variable names from POSTGRES_* to DATABASE_* in the tests-functional.yml file. This ensures consistency with other parts of the project and provides more descriptive variable names. Signed-off-by: mesilov --- .github/workflows/tests-functional.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 87133ea..a414889 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -31,9 +31,10 @@ jobs: --health-timeout=5s --health-retries=5 env: - POSTGRES_USER: b24phpLibTest - POSTGRES_PASSWORD: b24phpLibTest - POSTGRES_DB: b24phpLibTest + DATABASE_HOST: localhost + DATABASE_USER: b24phpLibTest + DATABASE_PASSWORD: b24phpLibTest + DATABASE_NAME: b24phpLibTest steps: - name: "Checkout code" From 9030702c9a83ff808cd8368161097f39fe85084c Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 10 Oct 2024 21:30:10 +0600 Subject: [PATCH 019/130] Add database configuration to functional test workflow Include essential environment variables for the PostgreSQL database setup within the functional test GitHub Actions workflow. This ensures the tests have access to the correct database credentials. Signed-off-by: mesilov --- .github/workflows/tests-functional.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index a414889..d34fb9d 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -6,6 +6,10 @@ on: env: COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist" + DATABASE_HOST: localhost + DATABASE_USER: b24phpLibTest + DATABASE_PASSWORD: b24phpLibTest + DATABASE_NAME: b24phpLibTest jobs: tests: @@ -31,6 +35,9 @@ jobs: --health-timeout=5s --health-retries=5 env: + POSTGRES_USER: b24phpLibTest + POSTGRES_PASSWORD: b24phpLibTest + POSTGRES_DB: b24phpLibTest DATABASE_HOST: localhost DATABASE_USER: b24phpLibTest DATABASE_PASSWORD: b24phpLibTest From 00d16ba14289357d8f9c105e9ad7af9783de2da5 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 10 Oct 2024 21:34:14 +0600 Subject: [PATCH 020/130] Add new use cases for Bitrix24 account management Implemented commands and handlers for InstallStart, InstallFinish, Uninstall, ChangeDomainUrl, and RenewAuthToken use cases. Added testing and improved event handling in Bitrix24Account class. Signed-off-by: mesilov --- .../Entity/Bitrix24Account.php | 43 ++++++++- ...MultipleBitrix24AccountsFoundException.php | 11 +++ .../Doctrine/Bitrix24AccountRepository.php | 44 ++++++---- .../UseCase/ChangeDomainUrl/Command.php | 21 +++++ .../UseCase/ChangeDomainUrl/Handler.php | 44 ++++++++++ .../UseCase/InstallFinish/Command.php | 21 +++++ .../UseCase/InstallFinish/Handler.php | 69 +++++++++++++++ .../UseCase/InstallStart/Command.php | 25 ++++++ .../UseCase/InstallStart/Handler.php | 57 ++++++++++++ .../UseCase/RenewAuthToken/Command.php | 17 ++++ .../UseCase/RenewAuthToken/Handler.php | 87 +++++++++++++++++++ .../UseCase/Uninstall/Command.php | 18 ++++ .../UseCase/Uninstall/Handler.php | 53 +++++++++++ .../UseCase/RenewAuthToken/HandlerTest.php | 87 +++++++++++++++++++ 14 files changed, 581 insertions(+), 16 deletions(-) create mode 100644 src/Bitrix24Accounts/Exceptions/MultipleBitrix24AccountsFoundException.php create mode 100644 src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php create mode 100644 src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php create mode 100644 src/Bitrix24Accounts/UseCase/InstallFinish/Command.php create mode 100644 src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php create mode 100644 src/Bitrix24Accounts/UseCase/InstallStart/Command.php create mode 100644 src/Bitrix24Accounts/UseCase/InstallStart/Handler.php create mode 100644 src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php create mode 100644 src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php create mode 100644 src/Bitrix24Accounts/UseCase/Uninstall/Command.php create mode 100644 src/Bitrix24Accounts/UseCase/Uninstall/Handler.php create mode 100644 tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index f7d5e54..0af53d7 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -14,6 +14,12 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationInstalledEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationUninstalledEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationVersionUpdatedEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountBlockedEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; +use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; @@ -27,9 +33,10 @@ use Symfony\Component\Serializer\Annotation\SerializedName; use Symfony\Component\Uid\Uuid; use Doctrine\ORM\Mapping as ORM; +use Symfony\Contracts\EventDispatcher\Event; #[ORM\Entity(repositoryClass: Bitrix24AccountRepository::class)] -class Bitrix24Account implements Bitrix24AccountInterface +class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEmitterInterface { private string $accessToken; @@ -42,6 +49,10 @@ class Bitrix24Account implements Bitrix24AccountInterface private ?string $applicationToken = null; private ?string $comment = null; + /** + * @var Event[] + */ + private array $events = []; public function __construct( #[ORM\Id] @@ -176,6 +187,10 @@ public function changeDomainUrl(string $newDomainUrl): void $this->domainUrl = $newDomainUrl; $this->updatedAt = new CarbonImmutable(); + $this->events[] = new Bitrix24AccountDomainUrlChangedEvent( + $this->id, + new CarbonImmutable() + ); } /** @@ -197,6 +212,10 @@ public function applicationInstalled(string $applicationToken): void $this->accountStatus = Bitrix24AccountStatus::active; $this->applicationToken = $applicationToken; $this->updatedAt = new CarbonImmutable(); + $this->events[] = new Bitrix24AccountApplicationInstalledEvent( + $this->id, + new CarbonImmutable() + ); } /** @@ -229,6 +248,10 @@ public function applicationUninstalled(string $applicationToken): void $this->accountStatus = Bitrix24AccountStatus::deleted; $this->updatedAt = new CarbonImmutable(); + $this->events[] = new Bitrix24AccountApplicationUninstalledEvent( + $this->id, + new CarbonImmutable() + ); } #[Override] @@ -272,6 +295,10 @@ public function updateApplicationVersion(int $version, ?Scope $newScope): void } $this->updatedAt = new CarbonImmutable(); + $this->events[] = new Bitrix24AccountApplicationVersionUpdatedEvent( + $this->id, + new CarbonImmutable() + ); } /** @@ -304,6 +331,10 @@ public function markAsBlocked(?string $comment): void $this->accountStatus = Bitrix24AccountStatus::blocked; $this->comment = $comment; $this->updatedAt = new CarbonImmutable(); + $this->events[] = new Bitrix24AccountBlockedEvent( + $this->id, + new CarbonImmutable() + ); } #[Override] @@ -311,4 +342,14 @@ public function getComment(): ?string { return $this->comment; } + + /** + * @return Event[] + */ + public function emitEvents(): array + { + $events = $this->events; + $this->events = []; + return $events; + } } \ No newline at end of file diff --git a/src/Bitrix24Accounts/Exceptions/MultipleBitrix24AccountsFoundException.php b/src/Bitrix24Accounts/Exceptions/MultipleBitrix24AccountsFoundException.php new file mode 100644 index 0000000..e545dc2 --- /dev/null +++ b/src/Bitrix24Accounts/Exceptions/MultipleBitrix24AccountsFoundException.php @@ -0,0 +1,11 @@ +getClassMetadata(Bitrix24Account::class)); } - /** - * @inheritdoc - */ #[Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { @@ -53,17 +52,18 @@ public function save(Bitrix24AccountInterface $bitrix24Account, bool $flush = fa #[Override] public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?bool $isAdmin = null): array { - return $this->findBy( - [ - 'memberId' => $memberId, - 'status' => [ - Bitrix24AccountStatus::new->name, - Bitrix24AccountStatus::active->name, - ] - ] - ); - } + $criteria = [ + 'memberId' => $memberId + ]; + if ($bitrix24AccountStatus instanceof Bitrix24AccountStatus) { + $criteria['status'] = $bitrix24AccountStatus->name; + } + if ($isAdmin !== null) { + $criteria['isBitrix24UserAdmin'] = $isAdmin; + } + return $this->findBy($criteria); + } /** * @inheritdoc @@ -92,6 +92,20 @@ public function findAllActive(): array ); } + /** + * @param non-empty-string $applicationToken + * @return array + * @todo discuss are we need add this method in contract in b24phpsdk? + */ + public function findByApplicationToken(string $applicationToken): array + { + return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findBy( + [ + 'applicationToken' => $applicationToken, + ] + ); + } + /** * @throws InvalidArgumentException */ @@ -124,7 +138,7 @@ public function findByDomain(string $domainUrl, ?Bitrix24AccountStatus $bitrix24 $criteria = [ 'domainUrl' => $domainUrl, ]; - if ($bitrix24AccountStatus instanceof \Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus) { + if ($bitrix24AccountStatus instanceof Bitrix24AccountStatus) { $criteria['status'] = $bitrix24AccountStatus->name; } diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php new file mode 100644 index 0000000..a753b89 --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -0,0 +1,21 @@ +logger->debug('Bitrix24Accounts.ChangeDomainUrl.start', [ + 'b24_domain_url_old' => $command->oldDomainUrlHost, + 'b24_domain_url_new' => $command->newDomainUrlHost, + ]); + + $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomainUrlHost); + foreach ($accounts as $targetAccount) { + /** + * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount + */ + $targetAccount->changeDomainUrl($command->newDomainUrlHost); + $this->bitrix24AccountRepository->save($targetAccount, true); + foreach ($targetAccount->emitEvents() as $event) { + $this->eventDispatcher->dispatch($event); + } + } + + $this->logger->debug('Bitrix24Accounts.ChangeDomainUrl.Finish'); + } +} \ No newline at end of file diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php new file mode 100644 index 0000000..fb9d84f --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -0,0 +1,21 @@ +logger->debug('Bitrix24Accounts.InstallFinish.start', [ + 'b24_domain_url' => $command->domainUrl, + 'b24_member_id' => $command->memberId, + 'b24_application_id' => $command->applicationToken, + 'b24_user_id' => $command->bitrix24UserId + ]); + + //todo discuss are we need add bitrix24UserId in contract? + $accounts = $this->bitrix24AccountRepository->findByMemberId( + $command->memberId, + Bitrix24AccountStatus::new + ); + if (count($accounts) === 0) { + throw new Bitrix24AccountNotFoundException(sprintf( + 'bitrix24 account for domain %s with member id %s in status «new» not found', + $command->domainUrl, + $command->memberId + )); + } + if (count($accounts) > 1) { + throw new MultipleBitrix24AccountsFoundException(sprintf( + 'multiple bitrix24 accounts for domain %s with member id %s in status «new» found', + $command->domainUrl, + $command->memberId + )); + } + $targetAccount = $accounts[0]; + /** + * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount + */ + $targetAccount->applicationInstalled($command->applicationToken); + $this->bitrix24AccountRepository->save($targetAccount, true); + foreach ($targetAccount->emitEvents() as $event) { + $this->eventDispatcher->dispatch($event); + } + + $this->logger->debug('Bitrix24Accounts.InstallFinish.Finish'); + } +} \ No newline at end of file diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php new file mode 100644 index 0000000..604b8e6 --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -0,0 +1,25 @@ +logger->debug('Bitrix24Accounts.InstallStart.start', [ + 'id' => $command->uuid->toRfc4122(), + 'domain_url' => $command->domainUrl, + 'member_id' => $command->memberId + ]); + + $this->bitrix24AccountRepository->save( + new Bitrix24Account( + $command->uuid, + $command->bitrix24UserId, + $command->isBitrix24UserAdmin, + $command->memberId, + $command->domainUrl, + Bitrix24AccountStatus::new, + $command->authToken, + new CarbonImmutable(), + new CarbonImmutable(), + $command->applicationVersion, + $command->applicationScope + ), + true + ); + $this->eventDispatcher->dispatch( + new Bitrix24AccountCreatedEvent( + $command->uuid, + new CarbonImmutable() + ) + ); + $this->logger->debug('Bitrix24Accounts.InstallStart.Finish'); + } +} \ No newline at end of file diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php new file mode 100644 index 0000000..defa0f4 --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php @@ -0,0 +1,17 @@ +logger->debug('Bitrix24Accounts.RenewAuthToken.start', [ + 'domain_url' => $command->renewedAuthToken->domain, + 'member_id' => $command->renewedAuthToken->memberId, + 'bitrix24_user_id' => $command->bitrix24UserId + ]); + + // get all active bitrix24 accounts + //todo discuss add bitrix24_user_id in contract? + $accounts = $this->bitrix24AccountRepository->findByMemberId( + $command->renewedAuthToken->memberId, + Bitrix24AccountStatus::active + ); + + if ($command->bitrix24UserId === null && count($accounts) > 1) { + //todo discuss move to b24phpsdk contracts? + throw new MultipleBitrix24AccountsFoundException( + sprintf('updating auth token failure - for domain %s with member id %s found multiple active accounts, try pass bitrix24_user_id in command', + $command->renewedAuthToken->domain, + $command->renewedAuthToken->memberId + ) + ); + } + + // filter by member_id and bitrix24_user_id + if ($command->bitrix24UserId !== null && count($accounts) > 1) { + // try to find target bitrix24 account + $targetAccount = array_map(static function ($account, int $bitrix24UserId) { + { + if ($account->getBitrix24UserId() === $bitrix24UserId) { + return $account; + } + + return null; + } + }, $accounts); + if ($targetAccount === []) { + throw new Bitrix24AccountNotFoundException(sprintf('account with %s domain %s memberId and %s bitrix24UserId not found', + $command->renewedAuthToken->domain, + $command->renewedAuthToken->memberId, + $command->bitrix24UserId, + )); + } + } + $targetAccount = $accounts[0]; + /** + * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount + */ + $targetAccount->renewAuthToken($command->renewedAuthToken); + $this->bitrix24AccountRepository->save($targetAccount, true); + $this->bitrix24AccountRepository->save($targetAccount, true); + foreach ($targetAccount->emitEvents() as $event) { + $this->eventDispatcher->dispatch($event); + } + + $this->logger->debug('Bitrix24Accounts.InstallFinish'); + } +} \ No newline at end of file diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php new file mode 100644 index 0000000..37c7813 --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php @@ -0,0 +1,18 @@ +logger->debug('Bitrix24Accounts.Uninstall.start', [ + 'b24_application_token' => $command->applicationToken, + ]); + + $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); + + foreach ($accounts as $targetAccount) { + /** + * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount + */ + $targetAccount->applicationUninstalled($command->applicationToken); + $this->bitrix24AccountRepository->save($targetAccount, true); + foreach ($targetAccount->emitEvents() as $event) { + $this->eventDispatcher->dispatch($event); + } + } + + $this->logger->debug('Bitrix24Accounts.Uninstall.Finish'); + } +} \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php new file mode 100644 index 0000000..5023f03 --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -0,0 +1,87 @@ + + * + * For the full copyright and license information, please view the MIT-LICENSE.txt + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Bitrix24\SDK\Lib\Tests\Functional\Bitrix24Accounts\UseCase\RenewAuthToken; + +use Bitrix24\SDK\Application\ApplicationStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; +use Bitrix24\SDK\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; +use Bitrix24\SDK\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\SDK\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Command; +use Bitrix24\SDK\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Handler; +use Bitrix24\SDK\Lib\Tests\EntityManagerFactory; +use Carbon\CarbonImmutable; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Uid\Uuid; + +#[CoversClass(Handler::class)] +class HandlerTest extends TestCase +{ + private Handler $handler; + private Bitrix24AccountRepositoryInterface $repository; + + #[Test] + public function testRenewAuthTokenWithoutBitrix24UserId(): void + { + $b24Account = new Bitrix24Account( + Uuid::v4(), + 1, + true, + Uuid::v7()->toRfc4122(), + Uuid::v7()->toRfc4122() . '-test.bitrix24.com', + Bitrix24AccountStatus::active, + new AuthToken('old_1', 'old_2', 3600), + new CarbonImmutable(), + new CarbonImmutable(), + 1, + new Scope() + ); + $this->repository->save($b24Account); + + $newAuthToken = new AuthToken('new_1', 'new_2', 3600); + $this->handler->handle( + new Command( + new RenewedAuthToken( + $newAuthToken, + $b24Account->getMemberId(), + 'https://client-endpoint.com', + 'https://server-endpoint.com', + ApplicationStatus::subscription(), + $b24Account->getDomainUrl() + ) + ) + ); + + $updated = $this->repository->getById($b24Account->getId()); + $this->assertEquals($newAuthToken->accessToken, $updated->getAuthToken()->accessToken); + $this->assertEquals($newAuthToken->refreshToken, $updated->getAuthToken()->refreshToken); + } + + public function setUp(): void + { + $this->repository = new Bitrix24AccountRepository(EntityManagerFactory::get()); + $this->handler = new Handler( + new EventDispatcher(), + $this->repository, + new NullLogger() + ); + } +} \ No newline at end of file From 32803bd5328b4dd4fcbba2d921069e98c16f614d Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 10 Oct 2024 21:43:55 +0600 Subject: [PATCH 021/130] Remove redundant flush argument from save method Eliminated the unnecessary flush argument in the save method across multiple handlers and the Bitrix24AccountRepository. This refactor ensures the flush operation is consistently handled within the repository, simplifying the contract and usage. Signed-off-by: mesilov --- .../Infrastructure/Doctrine/Bitrix24AccountRepository.php | 8 +++----- src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php | 4 ++-- src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php | 2 +- src/Bitrix24Accounts/UseCase/InstallStart/Handler.php | 3 +-- src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php | 3 +-- src/Bitrix24Accounts/UseCase/Uninstall/Handler.php | 2 +- 6 files changed, 9 insertions(+), 13 deletions(-) diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index ea329c7..adf8e02 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -39,13 +39,11 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface * @inheritdoc */ #[Override] - public function save(Bitrix24AccountInterface $bitrix24Account, bool $flush = false): void + public function save(Bitrix24AccountInterface $bitrix24Account): void { $this->getEntityManager()->persist($bitrix24Account); - - if ($flush) { - $this->getEntityManager()->flush(); - } + //todo discuss add flush arg to contract or add flusher in usecases? + $this->getEntityManager()->flush(); } diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index e3469ec..62642d5 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -29,11 +29,11 @@ public function handle(Command $command): void $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomainUrlHost); foreach ($accounts as $targetAccount) { + $targetAccount->changeDomainUrl($command->newDomainUrlHost); + $this->bitrix24AccountRepository->save($targetAccount); /** * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ - $targetAccount->changeDomainUrl($command->newDomainUrlHost); - $this->bitrix24AccountRepository->save($targetAccount, true); foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index d16442c..6a69023 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -59,7 +59,7 @@ public function handle(Command $command): void * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ $targetAccount->applicationInstalled($command->applicationToken); - $this->bitrix24AccountRepository->save($targetAccount, true); + $this->bitrix24AccountRepository->save($targetAccount); foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index c80abab..0d3b811 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -43,8 +43,7 @@ public function handle(Command $command): void new CarbonImmutable(), $command->applicationVersion, $command->applicationScope - ), - true + ) ); $this->eventDispatcher->dispatch( new Bitrix24AccountCreatedEvent( diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index b0445c5..da869f7 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -76,8 +76,7 @@ public function handle(Command $command): void * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ $targetAccount->renewAuthToken($command->renewedAuthToken); - $this->bitrix24AccountRepository->save($targetAccount, true); - $this->bitrix24AccountRepository->save($targetAccount, true); + $this->bitrix24AccountRepository->save($targetAccount); foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index c4171fc..98ef849 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -42,7 +42,7 @@ public function handle(Command $command): void * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ $targetAccount->applicationUninstalled($command->applicationToken); - $this->bitrix24AccountRepository->save($targetAccount, true); + $this->bitrix24AccountRepository->save($targetAccount); foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } From 57be1b94e2756bbd928d096e083d2e1c3e305b18 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 10 Oct 2024 22:07:08 +0600 Subject: [PATCH 022/130] Refactor repository methods to include PHPStan type hints Added detailed PHPStan type hints with @phpstan-return annotations to various repository methods to improve static analysis and type safety. Refactored array filtering logic in the RenewAuthToken handler for clarity and efficiency Signed-off-by: mesilov --- .../Doctrine/Bitrix24AccountRepository.php | 16 +++++++++++++--- .../UseCase/ChangeDomainUrl/Handler.php | 5 ++--- .../UseCase/RenewAuthToken/Handler.php | 17 ++++++++--------- .../UseCase/Uninstall/Handler.php | 3 ++- 4 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index adf8e02..5393c55 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -8,6 +8,7 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Bitrix24\SDK\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Doctrine\ORM\EntityManagerInterface; @@ -18,12 +19,16 @@ class Bitrix24AccountRepository extends EntityRepository implements Bitrix24AccountRepositoryInterface { public function __construct( - EntityManagerInterface $entityManager + EntityManagerInterface $entityManager ) { parent::__construct($entityManager, $entityManager->getClassMetadata(Bitrix24Account::class)); } + /** + * @phpstan-return Bitrix24AccountInterface&AggregateRootEventsEmitterInterface + * @throws Bitrix24AccountNotFoundException + */ #[Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { @@ -46,7 +51,9 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void $this->getEntityManager()->flush(); } - + /** + * @phpstan-return array + */ #[Override] public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?bool $isAdmin = null): array { @@ -92,7 +99,7 @@ public function findAllActive(): array /** * @param non-empty-string $applicationToken - * @return array + * @phpstan-return array * @todo discuss are we need add this method in contract in b24phpsdk? */ public function findByApplicationToken(string $applicationToken): array @@ -106,6 +113,7 @@ public function findByApplicationToken(string $applicationToken): array /** * @throws InvalidArgumentException + * @phpstan-return Bitrix24AccountInterface&AggregateRootEventsEmitterInterface */ #[Override] public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterface @@ -124,6 +132,8 @@ public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterf } /** + * @phpstan-return array + * @return array * @throws InvalidArgumentException */ #[Override] diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index 62642d5..01a55af 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -31,9 +31,8 @@ public function handle(Command $command): void foreach ($accounts as $targetAccount) { $targetAccount->changeDomainUrl($command->newDomainUrlHost); $this->bitrix24AccountRepository->save($targetAccount); - /** - * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount - */ + // todo выяснить почему он не видит объединение типов + /** @phpstan-ignore-next-line */ foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index da869f7..390513d 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -53,17 +53,16 @@ public function handle(Command $command): void // filter by member_id and bitrix24_user_id if ($command->bitrix24UserId !== null && count($accounts) > 1) { + // try to find target bitrix24 account - $targetAccount = array_map(static function ($account, int $bitrix24UserId) { - { - if ($account->getBitrix24UserId() === $bitrix24UserId) { - return $account; - } + $bitrix24UserId = $command->bitrix24UserId; + $targetAccount = array_filter($accounts, static function ($account) use ($bitrix24UserId) { + return $account->getBitrix24UserId() === $bitrix24UserId; + }); + // Reset array keys and get the first matched account (if any) + $targetAccount = reset($targetAccount) ?: null; - return null; - } - }, $accounts); - if ($targetAccount === []) { + if ($targetAccount===null) { throw new Bitrix24AccountNotFoundException(sprintf('account with %s domain %s memberId and %s bitrix24UserId not found', $command->renewedAuthToken->domain, $command->renewedAuthToken->memberId, diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 98ef849..62c503c 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -34,7 +34,8 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.Uninstall.start', [ 'b24_application_token' => $command->applicationToken, ]); - + //todo remove after update contract in b24phpsdk + /** @phpstan-ignore-next-line */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); foreach ($accounts as $targetAccount) { From c0961933eb30cf87eeab8c44ed8ce3148c097bf8 Mon Sep 17 00:00:00 2001 From: mesilov Date: Fri, 11 Oct 2024 01:09:10 +0600 Subject: [PATCH 023/130] Refactor account handling logic in multiple use cases Updated the condition checks and variable names for clarity and consistency across various use cases such as Install, Uninstall, ChangeDomainUrl, and RenewAuthToken. Minor changes include replacing array length checks with empty array comparisons and standardizing the event dispatching process. Also, added missing #[Override] annotations in certain methods where applicable. Signed-off-by: mesilov --- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 2 ++ .../Doctrine/Bitrix24AccountRepository.php | 1 + .../UseCase/ChangeDomainUrl/Handler.php | 8 ++++---- .../UseCase/InstallFinish/Handler.php | 5 ++++- .../UseCase/RenewAuthToken/Handler.php | 8 ++++---- .../UseCase/Uninstall/Handler.php | 11 ++++------- .../UseCase/RenewAuthToken/HandlerTest.php | 15 +++++++++------ 7 files changed, 28 insertions(+), 22 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 0af53d7..247e9fd 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -49,6 +49,7 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEm private ?string $applicationToken = null; private ?string $comment = null; + /** * @var Event[] */ @@ -346,6 +347,7 @@ public function getComment(): ?string /** * @return Event[] */ + #[Override] public function emitEvents(): array { $events = $this->events; diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 5393c55..fe5f33e 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -63,6 +63,7 @@ public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix2 if ($bitrix24AccountStatus instanceof Bitrix24AccountStatus) { $criteria['status'] = $bitrix24AccountStatus->name; } + if ($isAdmin !== null) { $criteria['isBitrix24UserAdmin'] = $isAdmin; } diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index 01a55af..c9ad2e7 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -28,12 +28,12 @@ public function handle(Command $command): void ]); $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomainUrlHost); - foreach ($accounts as $targetAccount) { - $targetAccount->changeDomainUrl($command->newDomainUrlHost); - $this->bitrix24AccountRepository->save($targetAccount); + foreach ($accounts as $account) { + $account->changeDomainUrl($command->newDomainUrlHost); + $this->bitrix24AccountRepository->save($account); // todo выяснить почему он не видит объединение типов /** @phpstan-ignore-next-line */ - foreach ($targetAccount->emitEvents() as $event) { + foreach ($account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 6a69023..5c50e18 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -40,13 +40,14 @@ public function handle(Command $command): void $command->memberId, Bitrix24AccountStatus::new ); - if (count($accounts) === 0) { + if ($accounts === []) { throw new Bitrix24AccountNotFoundException(sprintf( 'bitrix24 account for domain %s with member id %s in status «new» not found', $command->domainUrl, $command->memberId )); } + if (count($accounts) > 1) { throw new MultipleBitrix24AccountsFoundException(sprintf( 'multiple bitrix24 accounts for domain %s with member id %s in status «new» found', @@ -54,11 +55,13 @@ public function handle(Command $command): void $command->memberId )); } + $targetAccount = $accounts[0]; /** * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ $targetAccount->applicationInstalled($command->applicationToken); + $this->bitrix24AccountRepository->save($targetAccount); foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index 390513d..1d38849 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -56,11 +56,9 @@ public function handle(Command $command): void // try to find target bitrix24 account $bitrix24UserId = $command->bitrix24UserId; - $targetAccount = array_filter($accounts, static function ($account) use ($bitrix24UserId) { - return $account->getBitrix24UserId() === $bitrix24UserId; - }); + $targetAccount = array_filter($accounts, static fn($account): bool => $account->getBitrix24UserId() === $bitrix24UserId); // Reset array keys and get the first matched account (if any) - $targetAccount = reset($targetAccount) ?: null; + $targetAccount = $targetAccount !== [] ? reset($targetAccount) : null; if ($targetAccount===null) { throw new Bitrix24AccountNotFoundException(sprintf('account with %s domain %s memberId and %s bitrix24UserId not found', @@ -70,11 +68,13 @@ public function handle(Command $command): void )); } } + $targetAccount = $accounts[0]; /** * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ $targetAccount->renewAuthToken($command->renewedAuthToken); + $this->bitrix24AccountRepository->save($targetAccount); foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 62c503c..6218f19 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -38,13 +38,10 @@ public function handle(Command $command): void /** @phpstan-ignore-next-line */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); - foreach ($accounts as $targetAccount) { - /** - * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount - */ - $targetAccount->applicationUninstalled($command->applicationToken); - $this->bitrix24AccountRepository->save($targetAccount); - foreach ($targetAccount->emitEvents() as $event) { + foreach ($accounts as $account) { + $account->applicationUninstalled($command->applicationToken); + $this->bitrix24AccountRepository->save($account); + foreach ($account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 5023f03..d40a581 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -25,6 +25,7 @@ use Bitrix24\SDK\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Handler; use Bitrix24\SDK\Lib\Tests\EntityManagerFactory; use Carbon\CarbonImmutable; +use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -36,12 +37,13 @@ class HandlerTest extends TestCase { private Handler $handler; + private Bitrix24AccountRepositoryInterface $repository; #[Test] public function testRenewAuthTokenWithoutBitrix24UserId(): void { - $b24Account = new Bitrix24Account( + $bitrix24Account = new Bitrix24Account( Uuid::v4(), 1, true, @@ -54,28 +56,29 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void 1, new Scope() ); - $this->repository->save($b24Account); + $this->repository->save($bitrix24Account); $newAuthToken = new AuthToken('new_1', 'new_2', 3600); $this->handler->handle( new Command( new RenewedAuthToken( $newAuthToken, - $b24Account->getMemberId(), + $bitrix24Account->getMemberId(), 'https://client-endpoint.com', 'https://server-endpoint.com', ApplicationStatus::subscription(), - $b24Account->getDomainUrl() + $bitrix24Account->getDomainUrl() ) ) ); - $updated = $this->repository->getById($b24Account->getId()); + $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertEquals($newAuthToken->accessToken, $updated->getAuthToken()->accessToken); $this->assertEquals($newAuthToken->refreshToken, $updated->getAuthToken()->refreshToken); } - public function setUp(): void + #[Override] + protected function setUp(): void { $this->repository = new Bitrix24AccountRepository(EntityManagerFactory::get()); $this->handler = new Handler( From cd2d4600c0c272b1637a8dd95a94495d55bbed7c Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 12 Oct 2024 10:41:49 +0300 Subject: [PATCH 024/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BC=D0=B0=D0=BF=D0=B8=D0=BD=D0=B3=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D1=81=D1=82=D0=BE=D0=BB=D0=B1=D1=86=D1=8B:=20isBitrix?= =?UTF-8?q?24UserAdmin,domain=5Furl,updatedAt,applicationVersion.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 247e9fd..df96221 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -62,18 +62,26 @@ public function __construct( #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] #[SerializedName('b24_user_id')] private readonly int $bitrix24UserId, + #[ORM\Column(name: 'is_b24_user_admin', type: 'boolean', nullable: false)] + #[SerializedName('is_b24_user_admin')] private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ #[ORM\Column(name: 'member_id', type: 'string', nullable: false)] #[SerializedName('member_id')] private readonly string $memberId, + #[ORM\Column(name: 'domain_url', type: 'string', nullable: false)] + #[SerializedName('domain_url')] private string $domainUrl, private Bitrix24AccountStatus $accountStatus, AuthToken $authToken, #[ORM\Column(name: 'created_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] #[Ignore] private readonly CarbonImmutable $createdAt, + #[ORM\Column(name: 'update_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] + #[Ignore] private CarbonImmutable $updatedAt, + #[ORM\Column(name: 'application_version', type: 'integer', nullable: false)] + #[Ignore] private int $applicationVersion, Scope $applicationScope, ) From 01ad5089fe41e80118d72ff56e47f10aabeefdcf Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 13 Oct 2024 17:55:19 +0300 Subject: [PATCH 025/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BC=D0=B0=D0=BF=D0=B8=D0=BD=D0=B3=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D1=81=D1=82=D0=BE=D0=BB=D0=B1=D0=B5=D1=86:=20accountS?= =?UTF-8?q?tatus.=20-=20=D0=9F=D1=8B=D1=82=D0=B0=D0=BB=D1=81=D1=8F=20?= =?UTF-8?q?=D0=B5=D1=89=D0=B5=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BD=D0=B0=20authToken.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index df96221..772955c 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -72,8 +72,10 @@ public function __construct( #[ORM\Column(name: 'domain_url', type: 'string', nullable: false)] #[SerializedName('domain_url')] private string $domainUrl, + #[ORM\Column(name: 'account_status', type: 'string', nullable: false, enumType: Bitrix24AccountStatus::class)] private Bitrix24AccountStatus $accountStatus, - AuthToken $authToken, + #[ORM\Embedded(class: AuthToken::class)] + AuthToken $authToken, #[ORM\Column(name: 'created_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] #[Ignore] private readonly CarbonImmutable $createdAt, From 1e565046bf301e1416c6b695488e112386bea75c Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Wed, 16 Oct 2024 01:03:57 +0300 Subject: [PATCH 026/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20Flusher.php=20-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B2=D1=8B=D0=B7=D0=BE=D0=B2=20flusher=20?= =?UTF-8?q?=D0=B2=20Bitrix24AccountRepository.php=20,=20=D0=BD=D0=BE=20?= =?UTF-8?q?=D1=87=D1=82=D0=BE=20=D1=82=D0=BE=20=D0=BF=D0=BE=D0=BB=D1=83?= =?UTF-8?q?=D1=87=D0=B0=D0=B5=D1=82=D1=81=D1=8F=20=D0=BD=D0=B5=20=D1=82?= =?UTF-8?q?=D0=B0=D0=BA.=20-=20=D0=92=20=D1=84=D1=83=D0=BD=D0=BA=D1=86?= =?UTF-8?q?=D0=B8=D0=BE=D0=BD=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D1=82?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=B0=D1=85=20=D0=BF=D0=BE=D0=BB=D1=83=D1=87?= =?UTF-8?q?=D0=B0=D0=B5=D1=82=D1=81=D1=8F=20=D0=B1=D0=BE=D0=BB=D1=8C=D1=88?= =?UTF-8?q?=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA=20=D0=B8=D0=B7=20?= =?UTF-8?q?=D0=B7=D0=B0=20=D0=B2=D1=8B=D0=B7=D0=BE=D0=B2=D0=B0=20flusher.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Doctrine/Bitrix24AccountRepository.php | 9 +++++++-- .../UseCase/Command/Flusher.php | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 src/Bitrix24Accounts/UseCase/Command/Flusher.php diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index fe5f33e..f11398e 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -11,6 +11,7 @@ use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Bitrix24\SDK\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\SDK\Lib\Bitrix24Accounts\UseCase\Command\Flusher; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; use Override; @@ -19,10 +20,12 @@ class Bitrix24AccountRepository extends EntityRepository implements Bitrix24AccountRepositoryInterface { public function __construct( - EntityManagerInterface $entityManager + EntityManagerInterface $entityManager, + Flusher $flusher ) { parent::__construct($entityManager, $entityManager->getClassMetadata(Bitrix24Account::class)); + $this->flusher = $flusher; } /** @@ -48,7 +51,9 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void { $this->getEntityManager()->persist($bitrix24Account); //todo discuss add flush arg to contract or add flusher in usecases? - $this->getEntityManager()->flush(); + + // $this->getEntityManager()->flush(); + $this->flusher->flush(); } /** diff --git a/src/Bitrix24Accounts/UseCase/Command/Flusher.php b/src/Bitrix24Accounts/UseCase/Command/Flusher.php new file mode 100644 index 0000000..c832cb6 --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/Command/Flusher.php @@ -0,0 +1,17 @@ +em->flush(); + } +} \ No newline at end of file From 04c6547d38be0c4bb3470c25572c2d42ef62e14b Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Thu, 17 Oct 2024 00:01:45 +0300 Subject: [PATCH 027/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B2=20=D1=82=D0=B5=D1=81=D1=82=D0=B0=D1=85=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=20=D1=81=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B8=20=D1=8D=D0=BA=D0=B7=D0=B5=D0=BC=D0=BF=D0=BB=D1=8F=D1=80?= =?UTF-8?q?=D0=B0=20Bitrix24AccountRepository=20=D0=B2=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D0=BE=D0=B9=20=D0=BF=D0=B0=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80?= =?UTF-8?q?=20Flusher.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Doctrine/Bitrix24AccountRepository.php | 2 +- .../Doctrine/Bitrix24AccountRepositoryTest.php | 5 ++++- .../UseCase/RenewAuthToken/HandlerTest.php | 10 +++++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index f11398e..08f7978 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -19,6 +19,7 @@ class Bitrix24AccountRepository extends EntityRepository implements Bitrix24AccountRepositoryInterface { + private Flusher $flusher; public function __construct( EntityManagerInterface $entityManager, Flusher $flusher @@ -51,7 +52,6 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void { $this->getEntityManager()->persist($bitrix24Account); //todo discuss add flush arg to contract or add flusher in usecases? - // $this->getEntityManager()->flush(); $this->flusher->flush(); } diff --git a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php index a4ff8d8..c80fdca 100644 --- a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php +++ b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php @@ -20,6 +20,7 @@ use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\SDK\Lib\Bitrix24Accounts\UseCase\Command\Flusher; use Bitrix24\SDK\Lib\Tests\EntityManagerFactory; use Bitrix24\SDK\Tests\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterfaceTest; use Carbon\CarbonImmutable; @@ -63,6 +64,8 @@ protected function createBitrix24AccountImplementation( #[Override] protected function createBitrix24AccountRepositoryImplementation(): Bitrix24AccountRepositoryInterface { - return new Bitrix24AccountRepository(EntityManagerFactory::get()); + $entityManager = EntityManagerFactory::get(); + $flusher = new Flusher($entityManager); + return new Bitrix24AccountRepository($entityManager,$flusher); } } \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index d40a581..898e953 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -16,15 +16,20 @@ use Bitrix24\SDK\Application\ApplicationStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Core\Exceptions\WrongConfigurationException; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; use Bitrix24\SDK\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\SDK\Lib\Bitrix24Accounts\UseCase\Command\Flusher; use Bitrix24\SDK\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Command; use Bitrix24\SDK\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Handler; use Bitrix24\SDK\Lib\Tests\EntityManagerFactory; use Carbon\CarbonImmutable; +use Doctrine\DBAL\Exception; +use Doctrine\ORM\Exception\ORMException; +use Doctrine\ORM\OptimisticLockException; use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; @@ -77,10 +82,13 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void $this->assertEquals($newAuthToken->refreshToken, $updated->getAuthToken()->refreshToken); } + #[Override] protected function setUp(): void { - $this->repository = new Bitrix24AccountRepository(EntityManagerFactory::get()); + $entityManager = EntityManagerFactory::get(); + $flusher = new Flusher($entityManager); + $this->repository = new Bitrix24AccountRepository($entityManager,$flusher); $this->handler = new Handler( new EventDispatcher(), $this->repository, From 22baa6e646996f6a0c94aca9bf7356d43f5efad2 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Thu, 17 Oct 2024 00:36:21 +0300 Subject: [PATCH 028/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BE=D1=82=D0=BE=D0=B1=D1=80=D0=B0=D0=B6=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D1=81=D1=82=D1=80=D1=83=D0=BA=D1=82=D1=83?= =?UTF-8?q?=D1=80=D1=8B=20=D0=B1=D0=B4=20(=D0=B3=D0=B4=D0=B5=20=D1=8D?= =?UTF-8?q?=D1=82=D0=BE=20=D0=BE=D1=82=D0=BE=D0=B1=D1=80=D0=B0=D0=B6=D0=B0?= =?UTF-8?q?=D0=B5=D1=82=D1=81=D1=8F=3F)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index d34fb9d..47e1a0d 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -69,6 +69,7 @@ jobs: run: | php bin/doctrine orm:schema-tool:drop --force php bin/doctrine orm:schema-tool:create + php bin/doctrine orm:schema-tool:update --dump-sql php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox - name: "is functional tests succeeded" From a29c2e6a660b65cf4edae06a7652fe1c497282d1 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 20 Oct 2024 13:20:06 +0300 Subject: [PATCH 029/130] =?UTF-8?q?-=20=D0=A1=D0=BE=D0=B7=D0=B4=D0=B0?= =?UTF-8?q?=D0=BB=20xml=20=D1=84=D0=B0=D0=B9=D0=BB=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D0=BC=D0=B0=D0=BF=D0=BF=D0=B8=D0=BD=D0=B3=D0=B0.=20-=20=D0=92?= =?UTF-8?q?=20EntityManagerFactory.php=20=D0=BF=D0=BE=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=8F=D0=BB=20=D0=BD=D0=B0=20=D1=81=D0=BE=D0=B7=D0=B4=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20xml=20-?= =?UTF-8?q?=20=D0=92=20Makefile=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BE=D1=82=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D0=BE=D0=B5?= =?UTF-8?q?=20=D1=81=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=B8=20?= =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B1=D0=B4?= =?UTF-8?q?.=20-=20=D0=94=D0=BB=D1=8F=20=D1=82=D0=B5=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=B4=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2?= =?UTF-8?q?=D1=83=D1=8E=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 8 +++- config/doctrine/xml/Bitrix24Account.dcm.xml | 42 ++++++++++++++++++ config/doctrine/xml/TestUser.dcm.xml | 13 ++++++ .../Entity/Bitrix24Account.php | 1 - src/Bitrix24Accounts/Entity/TestUser.php | 43 +++++++++++++++++++ tests/EntityManagerFactory.php | 8 +++- 6 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 config/doctrine/xml/Bitrix24Account.dcm.xml create mode 100644 config/doctrine/xml/TestUser.dcm.xml create mode 100644 src/Bitrix24Accounts/Entity/TestUser.php diff --git a/Makefile b/Makefile index b794559..057164e 100644 --- a/Makefile +++ b/Makefile @@ -78,4 +78,10 @@ test-run-unit: test-run-functional: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create - docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox \ No newline at end of file + docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox + +schema-drop: + docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force + +schema-create: + docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create \ No newline at end of file diff --git a/config/doctrine/xml/Bitrix24Account.dcm.xml b/config/doctrine/xml/Bitrix24Account.dcm.xml new file mode 100644 index 0000000..41028c2 --- /dev/null +++ b/config/doctrine/xml/Bitrix24Account.dcm.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/doctrine/xml/TestUser.dcm.xml b/config/doctrine/xml/TestUser.dcm.xml new file mode 100644 index 0000000..6e330dc --- /dev/null +++ b/config/doctrine/xml/TestUser.dcm.xml @@ -0,0 +1,13 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 772955c..31b9d24 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -74,7 +74,6 @@ public function __construct( private string $domainUrl, #[ORM\Column(name: 'account_status', type: 'string', nullable: false, enumType: Bitrix24AccountStatus::class)] private Bitrix24AccountStatus $accountStatus, - #[ORM\Embedded(class: AuthToken::class)] AuthToken $authToken, #[ORM\Column(name: 'created_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] #[Ignore] diff --git a/src/Bitrix24Accounts/Entity/TestUser.php b/src/Bitrix24Accounts/Entity/TestUser.php new file mode 100644 index 0000000..51a1543 --- /dev/null +++ b/src/Bitrix24Accounts/Entity/TestUser.php @@ -0,0 +1,43 @@ +login; + } + + public function setLogin(string $login): void + { + $this->login = $login; + } + + public function getPassword(): string + { + return $this->password; + } + + public function setPassword(string $password): void + { + $this->password = $password; + } + public function getId(): int + { + return $this->id; + } + + public function setId(int $id): void + { + $this->id = $id; + } + +} \ No newline at end of file diff --git a/tests/EntityManagerFactory.php b/tests/EntityManagerFactory.php index a04e483..e0de768 100644 --- a/tests/EntityManagerFactory.php +++ b/tests/EntityManagerFactory.php @@ -27,8 +27,11 @@ class EntityManagerFactory */ public static function get(): EntityManagerInterface { - $paths = [ + /*$paths = [ dirname(__DIR__) . '/src/Bitrix24Accounts/Entity' + ];*/ + $paths = [ + dirname(__DIR__) . '/config/doctrine/xml' ]; $isDevMode = true; @@ -63,7 +66,8 @@ public static function get(): EntityManagerInterface Type::addType('carbon_immutable', CarbonImmutableType::class); } - $configuration = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode); + // $configuration = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode); + $configuration = ORMSetup::createXMLMetadataConfiguration($paths, $isDevMode); $connection = DriverManager::getConnection($connectionParams, $configuration); $entityManager = new EntityManager($connection, $configuration); // todo разобраться, почему так, без этого объекты оставались в кеше и при find мы получали старые значения From 6a7b8a94e80318b10bdf02d575b0857538311f18 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Mon, 21 Oct 2024 23:40:27 +0300 Subject: [PATCH 030/130] =?UTF-8?q?-=20=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20?= =?UTF-8?q?=D0=B8=D0=B7=20namespace=20sdk?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/doctrine | 3 +-- composer.json | 4 ++-- config/{doctrine => }/xml/Bitrix24Account.dcm.xml | 2 +- config/{doctrine => }/xml/TestUser.dcm.xml | 2 +- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 4 ++-- src/Bitrix24Accounts/Entity/TestUser.php | 2 +- .../MultipleBitrix24AccountsFoundException.php | 2 +- .../Doctrine/Bitrix24AccountRepository.php | 6 +++--- src/Bitrix24Accounts/ReadModel/Fetcher.php | 2 +- .../UseCase/ChangeDomainUrl/Command.php | 2 +- .../UseCase/ChangeDomainUrl/Handler.php | 2 +- src/Bitrix24Accounts/UseCase/Command/Flusher.php | 2 +- .../UseCase/InstallFinish/Command.php | 2 +- .../UseCase/InstallFinish/Handler.php | 4 ++-- .../UseCase/InstallStart/Command.php | 2 +- .../UseCase/InstallStart/Handler.php | 4 ++-- .../UseCase/RenewAuthToken/Command.php | 2 +- .../UseCase/RenewAuthToken/Handler.php | 4 ++-- src/Bitrix24Accounts/UseCase/Uninstall/Command.php | 2 +- src/Bitrix24Accounts/UseCase/Uninstall/Handler.php | 6 +++--- tests/EntityManagerFactory.php | 5 +++-- .../Doctrine/Bitrix24AccountRepositoryTest.php | 10 +++++----- .../UseCase/RenewAuthToken/HandlerTest.php | 14 +++++++------- .../Entity/Bitrix24AccountTest.php | 4 ++-- 24 files changed, 46 insertions(+), 46 deletions(-) rename config/{doctrine => }/xml/Bitrix24Account.dcm.xml (95%) rename config/{doctrine => }/xml/TestUser.dcm.xml (87%) diff --git a/bin/doctrine b/bin/doctrine index 9f213bc..cf20dbe 100644 --- a/bin/doctrine +++ b/bin/doctrine @@ -1,12 +1,11 @@ #!/usr/bin/env php - + diff --git a/config/doctrine/xml/TestUser.dcm.xml b/config/xml/TestUser.dcm.xml similarity index 87% rename from config/doctrine/xml/TestUser.dcm.xml rename to config/xml/TestUser.dcm.xml index 6e330dc..5bc14bf 100644 --- a/config/doctrine/xml/TestUser.dcm.xml +++ b/config/xml/TestUser.dcm.xml @@ -2,7 +2,7 @@ xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> - + diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 31b9d24..3a3b15c 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -10,7 +10,7 @@ declare(strict_types=1); -namespace Bitrix24\SDK\Lib\Bitrix24Accounts\Entity; +namespace Bitrix24\Lib\Bitrix24Accounts\Entity; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; @@ -25,7 +25,7 @@ use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Bitrix24\SDK\Core\Exceptions\UnknownScopeCodeException; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; -use Bitrix24\SDK\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Carbon\CarbonImmutable; use Override; use Symfony\Bridge\Doctrine\Types\UuidType; diff --git a/src/Bitrix24Accounts/Entity/TestUser.php b/src/Bitrix24Accounts/Entity/TestUser.php index 51a1543..4627681 100644 --- a/src/Bitrix24Accounts/Entity/TestUser.php +++ b/src/Bitrix24Accounts/Entity/TestUser.php @@ -1,7 +1,7 @@ Date: Tue, 22 Oct 2024 01:03:48 +0300 Subject: [PATCH 031/130] =?UTF-8?q?-=20=D0=9F=D0=B5=D1=80=D0=B5=D0=B8?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=D0=BB=20xml=20=D1=84=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB=D1=8B=20=D0=B4=D0=BB=D1=8F=20=D0=BC=D0=B0=D0=BF?= =?UTF-8?q?=D0=BF=D0=B8=D0=BD=D0=B3=D0=B0=20-=20=D0=9F=D0=BE=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=8F=D0=BB=20=D0=BF=D0=BE=D0=B4=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=81=D1=85=D0=B5=D0=BC=20=D0=B2=20?= =?UTF-8?q?xml=20-=20=D0=9D=D0=B0=D1=87=D0=B0=D0=BB=20=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=8F=D1=82=D1=8C=20=D0=BF=D0=BE=D0=BB=D1=8F=20=D0=B2=20xml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ....Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml} | 12 ++++++------ ...x24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml} | 7 +++---- src/Bitrix24Accounts/Entity/TestUser.php | 1 + .../Doctrine/Bitrix24AccountRepository.php | 4 +--- 4 files changed, 11 insertions(+), 13 deletions(-) rename config/xml/{Bitrix24Account.dcm.xml => Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml} (74%) rename config/xml/{TestUser.dcm.xml => Bitrix24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml} (55%) diff --git a/config/xml/Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml similarity index 74% rename from config/xml/Bitrix24Account.dcm.xml rename to config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index 93e83ff..c113aa4 100644 --- a/config/xml/Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -1,10 +1,10 @@ - + xmlns:xs="https://www.w3.org/2001/XMLSchema" + xmlns:orm="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + - + + @@ -14,7 +14,7 @@ - + diff --git a/config/xml/TestUser.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml similarity index 55% rename from config/xml/TestUser.dcm.xml rename to config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml index 5bc14bf..2d30540 100644 --- a/config/xml/TestUser.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml @@ -1,9 +1,8 @@ + xmlns:xs="https://www.w3.org/2001/XMLSchema" + xmlns:orm="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> - + diff --git a/src/Bitrix24Accounts/Entity/TestUser.php b/src/Bitrix24Accounts/Entity/TestUser.php index 4627681..216d1f2 100644 --- a/src/Bitrix24Accounts/Entity/TestUser.php +++ b/src/Bitrix24Accounts/Entity/TestUser.php @@ -30,6 +30,7 @@ public function setPassword(string $password): void { $this->password = $password; } + public function getId(): int { return $this->id; diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index ecd1f0f..413787d 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -19,14 +19,12 @@ class Bitrix24AccountRepository extends EntityRepository implements Bitrix24AccountRepositoryInterface { - private Flusher $flusher; public function __construct( EntityManagerInterface $entityManager, - Flusher $flusher + private readonly Flusher $flusher ) { parent::__construct($entityManager, $entityManager->getClassMetadata(Bitrix24Account::class)); - $this->flusher = $flusher; } /** From ba737ec8a0c1525cea58714d1d6b023d34f16166 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Fri, 25 Oct 2024 00:52:55 +0300 Subject: [PATCH 032/130] =?UTF-8?q?-=20=D0=9F=D0=B5=D1=80=D0=B5=D0=BD?= =?UTF-8?q?=D0=B5=D1=81=20Flusher=20-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20useCase=20=D0=BD=D0=B0=20=D1=81=D0=BE=D1=85?= =?UTF-8?q?=D1=80=D0=B0=D0=BD=D0=B5=D0=BD=D0=B8=D0=B5=20-=20=D0=94=D0=BE?= =?UTF-8?q?=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20xml=20=D1=81=20authtoken?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...x24Accounts.Entity.Bitrix24Account.dcm.xml | 4 +- ...x24.SDK.Core.Credentials.AuthToken.dcm.xml | 14 +++++++ .../Doctrine/Bitrix24AccountRepository.php | 9 ++-- .../UseCase/SaveAccount/Command.php | 14 +++++++ .../UseCase/SaveAccount/Handler.php | 24 +++++++++++ .../UseCase/Command => Services}/Flusher.php | 2 +- .../Bitrix24AccountRepositoryTest.php | 11 +++-- .../UseCase/RenewAuthToken/HandlerTest.php | 21 ++++------ .../UseCase/SaveAccount/HandlerTest.php | 41 +++++++++++++++++++ 9 files changed, 113 insertions(+), 27 deletions(-) create mode 100644 config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml create mode 100644 src/Bitrix24Accounts/UseCase/SaveAccount/Command.php create mode 100644 src/Bitrix24Accounts/UseCase/SaveAccount/Handler.php rename src/{Bitrix24Accounts/UseCase/Command => Services}/Flusher.php (81%) create mode 100644 tests/Functional/Bitrix24Accounts/UseCase/SaveAccount/HandlerTest.php diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index c113aa4..16d4273 100644 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -4,7 +4,7 @@ - + @@ -28,7 +28,7 @@ - + diff --git a/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml b/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml new file mode 100644 index 0000000..9b557fd --- /dev/null +++ b/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 413787d..b512f42 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -4,14 +4,14 @@ namespace Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine; +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\Lib\Bitrix24Accounts\UseCase\SaveAccount\Handler; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; -use Bitrix24\Lib\Bitrix24Accounts\UseCase\Command\Flusher; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; use Override; @@ -20,8 +20,7 @@ class Bitrix24AccountRepository extends EntityRepository implements Bitrix24AccountRepositoryInterface { public function __construct( - EntityManagerInterface $entityManager, - private readonly Flusher $flusher + EntityManagerInterface $entityManager ) { parent::__construct($entityManager, $entityManager->getClassMetadata(Bitrix24Account::class)); @@ -49,9 +48,9 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface public function save(Bitrix24AccountInterface $bitrix24Account): void { $this->getEntityManager()->persist($bitrix24Account); + //todo discuss add flush arg to contract or add flusher in usecases? // $this->getEntityManager()->flush(); - $this->flusher->flush(); } /** diff --git a/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php b/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php new file mode 100644 index 0000000..04742a6 --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php @@ -0,0 +1,14 @@ +bitrix24AccountRepository->save($command->bitrix24AccountRepository); + + $this->flusher->flush(); + } +} \ No newline at end of file diff --git a/src/Bitrix24Accounts/UseCase/Command/Flusher.php b/src/Services/Flusher.php similarity index 81% rename from src/Bitrix24Accounts/UseCase/Command/Flusher.php rename to src/Services/Flusher.php index f1f52ed..292e7d4 100644 --- a/src/Bitrix24Accounts/UseCase/Command/Flusher.php +++ b/src/Services/Flusher.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\Command; +namespace Bitrix24\Lib\Services; use Doctrine\ORM\EntityManagerInterface; diff --git a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php index ce3e0c7..24fbfd4 100644 --- a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php +++ b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php @@ -13,15 +13,15 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Infrastructure\Doctrine; +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\Lib\Services\Flusher; +use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; -use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; -use Bitrix24\Lib\Bitrix24Accounts\UseCase\Command\Flusher; -use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\SDK\Tests\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterfaceTest; use Carbon\CarbonImmutable; use Override; @@ -65,7 +65,6 @@ protected function createBitrix24AccountImplementation( protected function createBitrix24AccountRepositoryImplementation(): Bitrix24AccountRepositoryInterface { $entityManager = EntityManagerFactory::get(); - $flusher = new Flusher($entityManager); - return new Bitrix24AccountRepository($entityManager,$flusher); + return new Bitrix24AccountRepository($entityManager); } } \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 0c8214c..3ea83a4 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -13,23 +13,19 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\RenewAuthToken; -use Bitrix24\SDK\Application\ApplicationStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\SDK\Core\Exceptions\WrongConfigurationException; -use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; -use Bitrix24\SDK\Core\Credentials\AuthToken; -use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; -use Bitrix24\Lib\Bitrix24Accounts\UseCase\Command\Flusher; use Bitrix24\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Command; use Bitrix24\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Handler; +use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\SDK\Application\ApplicationStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; +use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; use Carbon\CarbonImmutable; -use Doctrine\DBAL\Exception; -use Doctrine\ORM\Exception\ORMException; -use Doctrine\ORM\OptimisticLockException; use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; @@ -87,8 +83,7 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void protected function setUp(): void { $entityManager = EntityManagerFactory::get(); - $flusher = new Flusher($entityManager); - $this->repository = new Bitrix24AccountRepository($entityManager,$flusher); + $this->repository = new Bitrix24AccountRepository($entityManager); $this->handler = new Handler( new EventDispatcher(), $this->repository, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/SaveAccount/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/SaveAccount/HandlerTest.php new file mode 100644 index 0000000..9bc80fe --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/UseCase/SaveAccount/HandlerTest.php @@ -0,0 +1,41 @@ + Date: Sat, 26 Oct 2024 10:31:47 +0300 Subject: [PATCH 033/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BC=D0=B0=D0=BF=D0=BF=D0=B8=D0=BD=D0=B3=20Aut?= =?UTF-8?q?hToken=20=D0=B4=D0=BB=D1=8F=20=D1=81=D1=83=D1=89=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B8=20Bitrix24Account?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...trix24Accounts.Entity.Bitrix24Account.dcm.xml | 16 ++-------------- ...trix24.SDK.Core.Credentials.AuthToken.dcm.xml | 16 ++++++---------- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 6 +++++- tests/EntityManagerFactory.php | 2 +- 4 files changed, 14 insertions(+), 26 deletions(-) diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index 16d4273..671cb2d 100644 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -14,7 +14,7 @@ - + @@ -25,18 +25,6 @@ - - - - - - - - - - - - - + \ No newline at end of file diff --git a/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml b/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml index 9b557fd..b2498a7 100644 --- a/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml +++ b/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml @@ -1,14 +1,10 @@ - - - - - - - - - - + + + + + + \ No newline at end of file diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 3a3b15c..b0f066e 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -27,6 +27,7 @@ use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Carbon\CarbonImmutable; +use Doctrine\ORM\Mapping\Embedded; use Override; use Symfony\Bridge\Doctrine\Types\UuidType; use Symfony\Component\Serializer\Annotation\Ignore; @@ -50,6 +51,8 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEm private ?string $comment = null; + private AuthToken $authToken; + /** * @var Event[] */ @@ -74,7 +77,7 @@ public function __construct( private string $domainUrl, #[ORM\Column(name: 'account_status', type: 'string', nullable: false, enumType: Bitrix24AccountStatus::class)] private Bitrix24AccountStatus $accountStatus, - AuthToken $authToken, + AuthToken $authToken, #[ORM\Column(name: 'created_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] #[Ignore] private readonly CarbonImmutable $createdAt, @@ -87,6 +90,7 @@ public function __construct( Scope $applicationScope, ) { + $this->authToken = $authToken; $this->accessToken = $authToken->accessToken; $this->refreshToken = $authToken->refreshToken; $this->expires = $authToken->expires; diff --git a/tests/EntityManagerFactory.php b/tests/EntityManagerFactory.php index ca198ec..2475265 100644 --- a/tests/EntityManagerFactory.php +++ b/tests/EntityManagerFactory.php @@ -28,7 +28,7 @@ class EntityManagerFactory */ public static function get(): EntityManagerInterface { - /*$paths = [ + /* $paths = [ dirname(__DIR__) . '/src/Bitrix24Accounts/Entity' ];*/ $paths = [ From 22e2931d9736e46cbbd6ea0048e27712be9b151d Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 27 Oct 2024 20:29:53 +0600 Subject: [PATCH 034/130] Update bitrix24/b24phpsdk dependency version Changed the bitrix24/b24phpsdk dependency from version ^1 to dev-dev in composer.json. This ensures compatibility with the latest development version of the package, possibly addressing some bugs or adding new features. Signed-off-by: mesilov --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 95cdfa6..393cd1b 100644 --- a/composer.json +++ b/composer.json @@ -41,7 +41,7 @@ "darsyn/ip": "^5", "nesbot/carbon": "^3", "moneyphp/money": "^4", - "bitrix24/b24phpsdk": "^1", + "bitrix24/b24phpsdk": "dev-dev", "doctrine/orm": "^3", "doctrine/doctrine-bundle": "*", "doctrine/doctrine-migrations-bundle": "*", From a0135c2f142012376126601eef41df2b1c675c0c Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 27 Oct 2024 21:10:43 +0600 Subject: [PATCH 035/130] Add PHP-CS-Fixer configuration and update dependencies Introduce a new PHP-CS-Fixer configuration file to ensure consistent code formatting. Update "friendsofphp/php-cs-fixer" to version 3.64 in composer.json. Also, add "*.cache" to .gitignore for better cache file management. Signed-off-by: mesilov --- .gitignore | 3 ++- .php-cs-fixer.dist.php | 9 +++++++++ composer.json | 4 ++-- 3 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 .php-cs-fixer.dist.php diff --git a/.gitignore b/.gitignore index eb0a19d..b5709f1 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,5 @@ composer.phar composer.lock .phpunit.result.cache *.log -.env.local \ No newline at end of file +.env.local +*.cache \ No newline at end of file diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..4dc1da0 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,9 @@ +in(__DIR__.'/src'); + +return (new PhpCsFixer\Config()) + ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) + ->setFinder($finder); \ No newline at end of file diff --git a/composer.json b/composer.json index 393cd1b..c478d22 100644 --- a/composer.json +++ b/composer.json @@ -55,12 +55,12 @@ "symfony/dotenv": "^7" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^3.59", + "friendsofphp/php-cs-fixer": "^3.64", "monolog/monolog": "^3", "fakerphp/faker": "^1", "phpstan/phpstan": "^1", "phpunit/phpunit": "^11", - "doctrine/migrations":"^3", + "doctrine/migrations": "^3", "psalm/phar": "^5", "rector/rector": "^1", "roave/security-advisories": "dev-master", From f4992ab256ee535c760a3c890eefa2fe0a93db82 Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 27 Oct 2024 21:21:40 +0600 Subject: [PATCH 036/130] Add GitHub Actions for PHP CS-Fixer Introduce a GitHub Actions workflow to run PHP CS-Fixer for code linting on push and pull request events. Additionally, update the Makefile to include new targets for running and fixing code style issues with PHP CS-Fixer. Signed-off-by: mesilov --- .github/workflows/lint-cs-fixer.yml | 51 +++++++++++++++++++++++++++++ Makefile | 4 +++ 2 files changed, 55 insertions(+) create mode 100644 .github/workflows/lint-cs-fixer.yml diff --git a/.github/workflows/lint-cs-fixer.yml b/.github/workflows/lint-cs-fixer.yml new file mode 100644 index 0000000..6d2fd84 --- /dev/null +++ b/.github/workflows/lint-cs-fixer.yml @@ -0,0 +1,51 @@ +on: + push: + pull_request: + +name: Lint CS-Fixer + +jobs: + static-analysis: + name: "CS-Fixer" + runs-on: ${{ matrix.operating-system }} + + strategy: + fail-fast: false + matrix: + php-version: + - "8.3" + dependencies: [ highest ] + operating-system: [ ubuntu-latest] + + steps: + - name: "Checkout" + uses: "actions/checkout@v2" + + - name: "Install PHP" + uses: "shivammathur/setup-php@v2" + with: + coverage: "none" + php-version: "${{ matrix.php-version }}" + extensions: json, bcmath, curl, intl, mbstring + tools: composer:v2 + + - name: "Install lowest dependencies" + if: ${{ matrix.dependencies == 'lowest' }} + run: "composer update --prefer-lowest --no-interaction --no-progress --no-suggest" + + - name: "Install highest dependencies" + if: ${{ matrix.dependencies == 'highest' }} + run: "composer update --no-interaction --no-progress --no-suggest" + + - name: "CS-Fixer" + run: "vendor/bin/php-cs-fixer fix --dry-run --diff --verbose" + + - name: "is CS-Fixer check succeeded" + if: ${{ success() }} + run: | + echo '✅ CS-Fixer check pass, congratulations!' + + - name: "is CS-Fixer check failed" + if: ${{ failure() }} + run: | + echo '::error:: ❗️ CS-Fixer check failed (╯°益°)╯彡┻━┻' \ No newline at end of file diff --git a/Makefile b/Makefile index 057164e..5afdd9e 100644 --- a/Makefile +++ b/Makefile @@ -69,6 +69,10 @@ lint-rector: docker-compose run --rm php-cli php vendor/bin/rector process --dry-run lint-rector-fix: docker-compose run --rm php-cli php vendor/bin/rector process +lint-cs-fixer: + docker-compose run --rm php-cli php vendor/bin/php-cs-fixer fix --dry-run --diff --verbose +lint-cs-fixer-fix: + docker-compose run --rm php-cli php vendor/bin/php-cs-fixer fix --diff --verbose # unit-tests test-run-unit: From 0ec7bbc673b1323cd76b16e4653d807067638d63 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 28 Oct 2024 00:06:36 +0600 Subject: [PATCH 037/130] Enhance PHP-CS-Fixer configuration with additional rules Updated .php-cs-fixer.dist.php to include cache file and new rule sets (@Symfony, @DoctrineAnnotation, @PhpCsFixer). Also adjusted the string concatenation formatting for better readability. Signed-off-by: mesilov --- .php-cs-fixer.dist.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 4dc1da0..9e5fcfd 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -2,8 +2,14 @@ declare(strict_types=1); $finder = PhpCsFixer\Finder::create() - ->in(__DIR__.'/src'); + ->in(__DIR__ . '/src'); return (new PhpCsFixer\Config()) ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) - ->setFinder($finder); \ No newline at end of file + ->setCacheFile(__DIR__ . '/.php-cs-fixer.cache') + ->setFinder($finder) + ->setRules([ + '@Symfony' => true, + '@DoctrineAnnotation' => true, + '@PhpCsFixer' => true, + ]); \ No newline at end of file From 9c99e2a788145c12289df1b905416ce121809630 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Mon, 28 Oct 2024 23:30:47 +0300 Subject: [PATCH 038/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BC=D0=B0=D0=BF=D0=BF=D0=B8=D0=BD=D0=B3=20Sco?= =?UTF-8?q?pe=20=D0=B4=D0=BB=D1=8F=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20Bitrix24Account?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...x24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml | 3 +-- config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml | 7 +++++++ .../Infrastructure/Doctrine/Bitrix24AccountRepository.php | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) create mode 100644 config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index 671cb2d..ebe3cf3 100644 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -24,7 +24,6 @@ - - + \ No newline at end of file diff --git a/config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml b/config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml new file mode 100644 index 0000000..86ac70c --- /dev/null +++ b/config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index b512f42..7d47558 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -50,14 +50,14 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void $this->getEntityManager()->persist($bitrix24Account); //todo discuss add flush arg to contract or add flusher in usecases? - // $this->getEntityManager()->flush(); + $this->getEntityManager()->flush(); } /** * @phpstan-return array */ #[Override] - public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?bool $isAdmin = null): array + public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?int $bitrix24UserId = null, ?bool $isAdmin = null): array { $criteria = [ 'memberId' => $memberId From 0ba4a98d12a072d7e05850bbe843b4efe4b24bdd Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Wed, 30 Oct 2024 23:22:58 +0300 Subject: [PATCH 039/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=8F=D0=BB=20=D0=BD=D0=B0=D0=B7=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=20id=20=D0=BD=D0=B0=20uuid=20=D0=B2=20=D1=81=D1=83=D1=89=D0=BD?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B8=20=D0=B8=20=D0=B2=20=D0=BC=D0=B0=D0=BF?= =?UTF-8?q?=D0=BF=D0=B8=D0=BD=D0=B3=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...x24Accounts.Entity.Bitrix24Account.dcm.xml | 2 +- .../Entity/Bitrix24Account.php | 20 +++++++++---------- .../Doctrine/Bitrix24AccountRepository.php | 2 +- .../UseCase/SaveAccount/Command.php | 3 ++- .../UseCase/SaveAccount/Handler.php | 5 ++--- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index ebe3cf3..fb541b9 100644 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -2,7 +2,7 @@ xmlns:xs="https://www.w3.org/2001/XMLSchema" xmlns:orm="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> - + diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index b0f066e..faec717 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -61,7 +61,7 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEm public function __construct( #[ORM\Id] #[ORM\Column(type: UuidType::NAME, unique: true)] - private readonly Uuid $id, + private Uuid $uuid, #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] #[SerializedName('b24_user_id')] private readonly int $bitrix24UserId, @@ -100,7 +100,7 @@ public function __construct( #[Override] public function getId(): Uuid { - return $this->id; + return $this->uuid; } #[Override] @@ -150,7 +150,7 @@ public function renewAuthToken(RenewedAuthToken $renewedAuthToken): void sprintf( 'member id %s for bitrix24 account %s for domain %s mismatch with member id %s for renewed access token', $this->memberId, - $this->id->toRfc4122(), + $this->uuid->toRfc4122(), $this->domainUrl, $renewedAuthToken->memberId, ) @@ -192,7 +192,7 @@ public function changeDomainUrl(string $newDomainUrl): void throw new InvalidArgumentException( sprintf( 'bitrix24 account %s for domain %s must be in active or new state, now account in %s state. domain url cannot be changed', - $this->id->toRfc4122(), + $this->uuid->toRfc4122(), $this->domainUrl, $this->accountStatus->name ) @@ -202,7 +202,7 @@ public function changeDomainUrl(string $newDomainUrl): void $this->domainUrl = $newDomainUrl; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountDomainUrlChangedEvent( - $this->id, + $this->uuid, new CarbonImmutable() ); } @@ -227,7 +227,7 @@ public function applicationInstalled(string $applicationToken): void $this->applicationToken = $applicationToken; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountApplicationInstalledEvent( - $this->id, + $this->uuid, new CarbonImmutable() ); } @@ -254,7 +254,7 @@ public function applicationUninstalled(string $applicationToken): void 'application token «%s» mismatch with application token «%s» for bitrix24 account %s for domain %s', $applicationToken, $this->applicationToken, - $this->id->toRfc4122(), + $this->uuid->toRfc4122(), $this->domainUrl ) ); @@ -263,7 +263,7 @@ public function applicationUninstalled(string $applicationToken): void $this->accountStatus = Bitrix24AccountStatus::deleted; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountApplicationUninstalledEvent( - $this->id, + $this->uuid, new CarbonImmutable() ); } @@ -310,7 +310,7 @@ public function updateApplicationVersion(int $version, ?Scope $newScope): void $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountApplicationVersionUpdatedEvent( - $this->id, + $this->uuid, new CarbonImmutable() ); } @@ -346,7 +346,7 @@ public function markAsBlocked(?string $comment): void $this->comment = $comment; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountBlockedEvent( - $this->id, + $this->uuid, new CarbonImmutable() ); } diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 7d47558..e51a6a2 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -50,7 +50,7 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void $this->getEntityManager()->persist($bitrix24Account); //todo discuss add flush arg to contract or add flusher in usecases? - $this->getEntityManager()->flush(); + // $this->getEntityManager()->flush(); } /** diff --git a/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php b/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php index 04742a6..e294d7c 100644 --- a/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php +++ b/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php @@ -4,11 +4,12 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\SaveAccount; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; readonly class Command { public function __construct( - public Bitrix24AccountRepositoryInterface $bitrix24AccountRepository + public Bitrix24AccountInterface $bitrix24Account ){} } \ No newline at end of file diff --git a/src/Bitrix24Accounts/UseCase/SaveAccount/Handler.php b/src/Bitrix24Accounts/UseCase/SaveAccount/Handler.php index 8fa4030..ed4c234 100644 --- a/src/Bitrix24Accounts/UseCase/SaveAccount/Handler.php +++ b/src/Bitrix24Accounts/UseCase/SaveAccount/Handler.php @@ -6,18 +6,17 @@ use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\Lib\Bitrix24Accounts\UseCase\SaveAccount\Command; final readonly class Handler { public function __construct( private Flusher $flusher, - private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, + private Bitrix24AccountRepositoryInterface $repository, ) {} public function handle(Command $command):void { - $this->bitrix24AccountRepository->save($command->bitrix24AccountRepository); + $this->repository->save($command->bitrix24Account); $this->flusher->flush(); } From 984c7a147e93a0c84d2b4e5e7d57df56c5b7a367 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Thu, 31 Oct 2024 00:58:06 +0300 Subject: [PATCH 040/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BB=D1=83=D1=87?= =?UTF-8?q?=D0=B0=D0=B5=D1=82=D1=81=D1=8F=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D1=8F=D1=82=D1=8C=20=D0=B2=20=D1=82=D0=B0=D0=B1=D0=BB?= =?UTF-8?q?=D0=B8=D1=86=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...4.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml | 2 +- .../xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml | 2 +- config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml | 2 +- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 9 +++++---- .../Doctrine/Bitrix24AccountRepository.php | 6 +++++- .../UseCase/RenewAuthToken/HandlerTest.php | 3 ++- 6 files changed, 15 insertions(+), 9 deletions(-) diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index fb541b9..7204f98 100644 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -14,7 +14,7 @@ - + diff --git a/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml b/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml index b2498a7..b229a88 100644 --- a/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml +++ b/config/xml/Bitrix24.SDK.Core.Credentials.AuthToken.dcm.xml @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml b/config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml index 86ac70c..0df218b 100644 --- a/config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml +++ b/config/xml/Bitrix24.SDK.Core.Credentials.Scope.dcm.xml @@ -2,6 +2,6 @@ xmlns:xs="https://www.w3.org/2001/XMLSchema" xmlns:orm="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> - + \ No newline at end of file diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index faec717..1de7dc3 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -58,20 +58,21 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEm */ private array $events = []; + public function __construct( #[ORM\Id] #[ORM\Column(type: UuidType::NAME, unique: true)] - private Uuid $uuid, + private Uuid $uuid, #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] #[SerializedName('b24_user_id')] - private readonly int $bitrix24UserId, + private readonly int $bitrix24UserId, #[ORM\Column(name: 'is_b24_user_admin', type: 'boolean', nullable: false)] #[SerializedName('is_b24_user_admin')] - private readonly bool $isBitrix24UserAdmin, + private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ #[ORM\Column(name: 'member_id', type: 'string', nullable: false)] #[SerializedName('member_id')] - private readonly string $memberId, + private readonly string $memberId, #[ORM\Column(name: 'domain_url', type: 'string', nullable: false)] #[SerializedName('domain_url')] private string $domainUrl, diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index e51a6a2..4598636 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -33,6 +33,8 @@ public function __construct( #[Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { + // print_r($uuid); + // exit(); $res = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); if ($res === null) { throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); @@ -47,10 +49,12 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface #[Override] public function save(Bitrix24AccountInterface $bitrix24Account): void { + $this->getEntityManager()->persist($bitrix24Account); //todo discuss add flush arg to contract or add flusher in usecases? - // $this->getEntityManager()->flush(); + $this->getEntityManager()->flush(); + } /** diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 3ea83a4..e843460 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -45,7 +45,7 @@ class HandlerTest extends TestCase public function testRenewAuthTokenWithoutBitrix24UserId(): void { $bitrix24Account = new Bitrix24Account( - Uuid::v4(), + Uuid::v7(), 1, true, Uuid::v7()->toRfc4122(), @@ -57,6 +57,7 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void 1, new Scope() ); + $this->repository->save($bitrix24Account); $newAuthToken = new AuthToken('new_1', 'new_2', 3600); From 620a43711c61584315795c96516505d19774fa3f Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 3 Nov 2024 22:33:58 +0600 Subject: [PATCH 041/130] Add environment variable loading and debugging support This commit updates the Makefile to include default and personal environment variable files. It introduces a new debug-print-env target to print essential environment variables for debugging purposes. Docker compose file adjustments and minor code formatting tweaks are also included. Signed-off-by: mesilov --- .env | 2 +- Makefile | 15 ++++++++- config/cli-config.php | 2 +- docker-compose.yaml | 6 ++-- .../Entity/Bitrix24AccountTest.php | 33 ++++++++++--------- 5 files changed, 35 insertions(+), 23 deletions(-) diff --git a/.env b/.env index 4fda991..f9de590 100644 --- a/.env +++ b/.env @@ -12,7 +12,7 @@ # # Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2). # https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration -DATABASE_HOST=bitrix24-php-lib-test-database +DATABASE_HOST= DATABASE_USER= DATABASE_PASSWORD= DATABASE_NAME= \ No newline at end of file diff --git a/Makefile b/Makefile index 5afdd9e..ac38090 100644 --- a/Makefile +++ b/Makefile @@ -9,6 +9,12 @@ export COMPOSE_HTTP_TIMEOUT=120 export DOCKER_CLIENT_TIMEOUT=120 +# load default and personal env-variables +ENV := $(PWD)/.env +ENV_LOCAL := $(PWD)/.env.local +include $(ENV) +-include $(ENV_LOCAL) + default: @echo "make needs target:" @egrep -e '^\S+' ./Makefile | grep -v default | sed -r 's/://' | sed -r 's/^/ - /' @@ -16,6 +22,13 @@ default: %: @: # silence +# Rule to print all environment variables for debugging +debug-print-env: + @echo "DATABASE_HOST=$(DATABASE_HOST)" + @echo "DATABASE_NAME=$(DATABASE_NAME)" + @echo "DATABASE_USER=$(DATABASE_USER)" + @echo "DATABASE_PASSWORD=$(DATABASE_PASSWORD)" + init: @echo "remove all containers" docker-compose down --remove-orphans @@ -79,7 +92,7 @@ test-run-unit: docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox # functional-tests, work with test database -test-run-functional: +test-run-functional: debug-print-env docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox diff --git a/config/cli-config.php b/config/cli-config.php index 0eb1e75..18e2c02 100644 --- a/config/cli-config.php +++ b/config/cli-config.php @@ -13,7 +13,7 @@ [ 'driver' => 'pdo_pgsql', 'memory' => true, - 'dbname' => 'b24AccountTest', + 'dbname' => 'b24phpLibTest', ]); return DependencyFactory::fromConnection($config, new ExistingConnection($conn)); \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml index 4923ef9..beb38fc 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -2,7 +2,7 @@ services: php-cli: build: context: ./docker/php-cli - links: + depends_on: - database volumes: - .:/var/www/html @@ -19,8 +19,6 @@ services: container_name: bitrix24-php-lib-test-database ports: - '5432:5432' - expose: - - 5432 volumes: - - ./Init Database:/docker-entrypoint-initdb.d + - ./docker/init_database/:/docker-entrypoint-initdb.d - ./docker/db:/var/lib/postgresql/data diff --git a/tests/Unit/Bitrix24Accounts/Entity/Bitrix24AccountTest.php b/tests/Unit/Bitrix24Accounts/Entity/Bitrix24AccountTest.php index 25fa358..3671674 100644 --- a/tests/Unit/Bitrix24Accounts/Entity/Bitrix24AccountTest.php +++ b/tests/Unit/Bitrix24Accounts/Entity/Bitrix24AccountTest.php @@ -13,35 +13,36 @@ namespace Bitrix24\Lib\Tests\Unit\Bitrix24Accounts\Entity; +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Tests\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterfaceTest; use Carbon\CarbonImmutable; -use Override; use PHPUnit\Framework\Attributes\CoversClass; use Symfony\Component\Uid\Uuid; +/** + * @internal + */ #[CoversClass(Bitrix24Account::class)] class Bitrix24AccountTest extends Bitrix24AccountInterfaceTest { - #[Override] + #[\Override] protected function createBitrix24AccountImplementation( - Uuid $uuid, - int $bitrix24UserId, - bool $isBitrix24UserAdmin, - string $memberId, - string $domainUrl, + Uuid $uuid, + int $bitrix24UserId, + bool $isBitrix24UserAdmin, + string $memberId, + string $domainUrl, Bitrix24AccountStatus $bitrix24AccountStatus, - AuthToken $authToken, - CarbonImmutable $createdAt, - CarbonImmutable $updatedAt, - int $applicationVersion, - Scope $applicationScope - ): Bitrix24AccountInterface - { + AuthToken $authToken, + CarbonImmutable $createdAt, + CarbonImmutable $updatedAt, + int $applicationVersion, + Scope $applicationScope + ): Bitrix24AccountInterface { return new Bitrix24Account( $uuid, $bitrix24UserId, @@ -56,4 +57,4 @@ protected function createBitrix24AccountImplementation( $applicationScope ); } -} \ No newline at end of file +} From 4ce759c832e40c92e7ae9229e78df126255c10c9 Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 3 Nov 2024 23:32:24 +0600 Subject: [PATCH 042/130] Add functional test for ChangeDomainUrl handler Introduce functional testing for the ChangeDomainUrl handler to ensure the domain URL is updated correctly. Included flush operation in the handler to persist changes. Signed-off-by: mesilov --- .../UseCase/ChangeDomainUrl/Handler.php | 3 + .../UseCase/ChangeDomainUrl/HandlerTest.php | 92 +++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index a762104..072f616 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl; +use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; @@ -15,6 +16,7 @@ public function __construct( private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, + private Flusher $flusher, private LoggerInterface $logger ) { @@ -31,6 +33,7 @@ public function handle(Command $command): void foreach ($accounts as $account) { $account->changeDomainUrl($command->newDomainUrlHost); $this->bitrix24AccountRepository->save($account); + $this->flusher->flush(); // todo выяснить почему он не видит объединение типов /** @phpstan-ignore-next-line */ foreach ($account->emitEvents() as $event) { diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php new file mode 100644 index 0000000..e1d637f --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -0,0 +1,92 @@ + + * + * For the full copyright and license information, please view the MIT-LICENSE.txt + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\ChangeDomainUrl; + +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\Lib\Services\Flusher; +use Bitrix24\Lib\Bitrix24Accounts; +use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\SDK\Application\ApplicationStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; +use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; +use Carbon\CarbonImmutable; +use Override; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Uid\Uuid; + +#[CoversClass(Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler::class)] +class HandlerTest extends TestCase +{ + private Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler $handler; + private Flusher $flusher; + + private Bitrix24AccountRepositoryInterface $repository; + + #[Test] + public function testRenewAuthTokenWithoutBitrix24UserId(): void + { + $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $bitrix24Account = new Bitrix24Account( + Uuid::v7(), + 1, + true, + Uuid::v7()->toRfc4122(), + $oldDomainUrl, + Bitrix24AccountStatus::active, + new AuthToken('old_1', 'old_2', 3600), + new CarbonImmutable(), + new CarbonImmutable(), + 1, + new Scope() + ); + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $newDomainUrl = 'new' . $oldDomainUrl; + $this->handler->handle( + new Bitrix24Accounts\UseCase\ChangeDomainUrl\Command( + $oldDomainUrl, + $newDomainUrl + ) + ); + + $updated = $this->repository->getById($bitrix24Account->getId()); + $this->assertEquals( + $newDomainUrl, + $updated->getDomainUrl() + ); + } + + #[Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager); + $this->handler = new Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler( + new EventDispatcher(), + $this->repository, + $this->flusher, + new NullLogger() + ); + } +} \ No newline at end of file From dc596ea9dba289e9c00776f26130c1e30b7f54c2 Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 3 Nov 2024 23:43:36 +0600 Subject: [PATCH 043/130] Add flusher support to InstallFinish handler Introduced a Flusher service to the InstallFinish handler to ensure database changes are persisted immediately. Updated the HandlerTest to include a functional test for the new behavior, ensuring that application tokens are validated correctly after persistence. Signed-off-by: mesilov --- .../UseCase/InstallFinish/Handler.php | 7 +- .../UseCase/InstallFinish/HandlerTest.php | 90 +++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 60b62ab..a1d90ef 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; +use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; @@ -18,6 +19,7 @@ public function __construct( private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, + private Flusher $flusher, private LoggerInterface $logger ) { @@ -35,10 +37,10 @@ public function handle(Command $command): void 'b24_user_id' => $command->bitrix24UserId ]); - //todo discuss are we need add bitrix24UserId in contract? $accounts = $this->bitrix24AccountRepository->findByMemberId( $command->memberId, - Bitrix24AccountStatus::new + Bitrix24AccountStatus::new, + $command->bitrix24UserId ); if ($accounts === []) { throw new Bitrix24AccountNotFoundException(sprintf( @@ -63,6 +65,7 @@ public function handle(Command $command): void $targetAccount->applicationInstalled($command->applicationToken); $this->bitrix24AccountRepository->save($targetAccount); + $this->flusher->flush(); foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php new file mode 100644 index 0000000..4ddc51d --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -0,0 +1,90 @@ + + * + * For the full copyright and license information, please view the MIT-LICENSE.txt + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\InstallFinish; + +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\Lib\Services\Flusher; +use Bitrix24\Lib\Bitrix24Accounts; +use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\SDK\Application\ApplicationStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; +use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; +use Carbon\CarbonImmutable; +use Override; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Uid\Uuid; + +#[CoversClass(Bitrix24Accounts\UseCase\InstallFinish\Handler::class)] +class HandlerTest extends TestCase +{ + private Bitrix24Accounts\UseCase\InstallFinish\Handler $handler; + private Flusher $flusher; + + private Bitrix24AccountRepositoryInterface $repository; + + #[Test] + public function testRenewAuthTokenWithoutBitrix24UserId(): void + { + $bitrix24Account = new Bitrix24Account( + Uuid::v7(), + 1, + true, + Uuid::v7()->toRfc4122(), + Uuid::v7()->toRfc4122() . '-test.bitrix24.com', + Bitrix24AccountStatus::new, + new AuthToken('old_1', 'old_2', 3600), + new CarbonImmutable(), + new CarbonImmutable(), + 1, + new Scope() + ); + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $applicationToken = Uuid::v7()->toRfc4122(); + $this->handler->handle( + new Bitrix24Accounts\UseCase\InstallFinish\Command( + $applicationToken, + $bitrix24Account->getMemberId(), + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getBitrix24UserId() + ) + ); + + $updated = $this->repository->getById($bitrix24Account->getId()); + $this->assertTrue($updated->isApplicationTokenValid($applicationToken)); + } + + #[Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager); + $this->handler = new Bitrix24Accounts\UseCase\InstallFinish\Handler( + new EventDispatcher(), + $this->repository, + $this->flusher, + new NullLogger() + ); + } +} \ No newline at end of file From 04297f73393e4ec7cc21896d14219268e01e241e Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 4 Nov 2024 00:08:13 +0600 Subject: [PATCH 044/130] Add functional test for InstallStart handler Introduced a new PHPUnit test to ensure the correctness of the `InstallStart` handler's functionality. Also, integrated the `Flusher` service within the handler to persist changes. Signed-off-by: mesilov --- .../UseCase/InstallStart/Handler.php | 3 + .../UseCase/InstallStart/HandlerTest.php | 100 ++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index 739fcd1..50c5262 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallStart; +use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountCreatedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; @@ -17,6 +18,7 @@ public function __construct( private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, + private Flusher $flusher, private LoggerInterface $logger ) { @@ -45,6 +47,7 @@ public function handle(Command $command): void $command->applicationScope ) ); + $this->flusher->flush(); $this->eventDispatcher->dispatch( new Bitrix24AccountCreatedEvent( $command->uuid, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php new file mode 100644 index 0000000..d93b74a --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -0,0 +1,100 @@ + + * + * For the full copyright and license information, please view the MIT-LICENSE.txt + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\InstallStart; + +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\Lib\Services\Flusher; +use Bitrix24\Lib\Bitrix24Accounts; +use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\SDK\Application\ApplicationStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; +use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; +use Bitrix24\SDK\Core\Exceptions\UnknownScopeCodeException; +use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; +use Carbon\CarbonImmutable; +use Override; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Log\NullLogger; +use Random\RandomException; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Uid\Uuid; + +#[CoversClass(Bitrix24Accounts\UseCase\InstallStart\Handler::class)] +class HandlerTest extends TestCase +{ + private Bitrix24Accounts\UseCase\InstallStart\Handler $handler; + private Flusher $flusher; + private Bitrix24AccountRepositoryInterface $repository; + + /** + * @throws InvalidArgumentException + * @throws Bitrix24AccountNotFoundException + * @throws RandomException + * @throws UnknownScopeCodeException + */ + #[Test] + public function testInstallStartHappyPath(): void + { + $accountId = Uuid::v7(); + $b24UserId = random_int(1, 100_000); + $isB24UserAdmin = true; + $b24MemberId = Uuid::v7()->toRfc4122(); + $b24DomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $authToken = new AuthToken('old_1', 'old_2', 3600); + $appVersion = 1; + $scope = new Scope(['crm']); + $this->handler->handle( + new Bitrix24Accounts\UseCase\InstallStart\Command( + $accountId, + $b24UserId, + $isB24UserAdmin, + $b24MemberId, + $b24DomainUrl, + $authToken, + $appVersion, + $scope + ) + ); + + $account = $this->repository->getById($accountId); + $this->assertEquals($b24UserId, $account->getBitrix24UserId()); + $this->assertEquals($isB24UserAdmin, $account->isBitrix24UserAdmin()); + $this->assertEquals($b24MemberId, $account->getMemberId()); + $this->assertEquals($b24DomainUrl, $account->getDomainUrl()); + $this->assertEquals($authToken, $account->getAuthToken()); + $this->assertEquals($appVersion, $account->getApplicationVersion()); + $this->assertEquals($scope, $account->getApplicationScope()); + } + + #[Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager); + $this->handler = new Bitrix24Accounts\UseCase\InstallStart\Handler( + new EventDispatcher(), + $this->repository, + $this->flusher, + new NullLogger() + ); + } +} \ No newline at end of file From c365b9fc0184abf4f076dce4e4a1abb075fee554 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 4 Nov 2024 00:19:17 +0600 Subject: [PATCH 045/130] Remove custom exception and update handler logic Removed `MultipleBitrix24AccountsFoundException` and adjusted handler logic to use the existing exception from the SDK. This ensures consistency in exception handling across the application and adds the `Flusher` service to the token renewal handler for persisting changes. Signed-off-by: mesilov --- ...MultipleBitrix24AccountsFoundException.php | 11 ------ .../UseCase/InstallFinish/Handler.php | 2 +- .../UseCase/RenewAuthToken/Handler.php | 34 +++++++------------ .../UseCase/Uninstall/Handler.php | 1 - .../UseCase/RenewAuthToken/HandlerTest.php | 2 ++ 5 files changed, 16 insertions(+), 34 deletions(-) delete mode 100644 src/Bitrix24Accounts/Exceptions/MultipleBitrix24AccountsFoundException.php diff --git a/src/Bitrix24Accounts/Exceptions/MultipleBitrix24AccountsFoundException.php b/src/Bitrix24Accounts/Exceptions/MultipleBitrix24AccountsFoundException.php deleted file mode 100644 index 8ec97fb..0000000 --- a/src/Bitrix24Accounts/Exceptions/MultipleBitrix24AccountsFoundException.php +++ /dev/null @@ -1,11 +0,0 @@ -bitrix24AccountRepository->findByMemberId( $command->renewedAuthToken->memberId, - Bitrix24AccountStatus::active + Bitrix24AccountStatus::active, + $command->bitrix24UserId ); if ($command->bitrix24UserId === null && count($accounts) > 1) { - //todo discuss move to b24phpsdk contracts? throw new MultipleBitrix24AccountsFoundException( sprintf('updating auth token failure - for domain %s with member id %s found multiple active accounts, try pass bitrix24_user_id in command', $command->renewedAuthToken->domain, @@ -51,22 +51,14 @@ public function handle(Command $command): void ); } - // filter by member_id and bitrix24_user_id if ($command->bitrix24UserId !== null && count($accounts) > 1) { - - // try to find target bitrix24 account - $bitrix24UserId = $command->bitrix24UserId; - $targetAccount = array_filter($accounts, static fn($account): bool => $account->getBitrix24UserId() === $bitrix24UserId); - // Reset array keys and get the first matched account (if any) - $targetAccount = $targetAccount !== [] ? reset($targetAccount) : null; - - if ($targetAccount===null) { - throw new Bitrix24AccountNotFoundException(sprintf('account with %s domain %s memberId and %s bitrix24UserId not found', + throw new MultipleBitrix24AccountsFoundException( + sprintf('updating auth token failure - for domain %s with member id %s and bitrix24 user id %s found multiple active accounts', $command->renewedAuthToken->domain, $command->renewedAuthToken->memberId, - $command->bitrix24UserId, - )); - } + $command->bitrix24UserId + ) + ); } $targetAccount = $accounts[0]; @@ -74,12 +66,12 @@ public function handle(Command $command): void * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ $targetAccount->renewAuthToken($command->renewedAuthToken); - $this->bitrix24AccountRepository->save($targetAccount); + $this->flusher->flush(); foreach ($targetAccount->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } - $this->logger->debug('Bitrix24Accounts.InstallFinish'); + $this->logger->debug('Bitrix24Accounts.RenewAuthToken.finish'); } } \ No newline at end of file diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 73b510a..fd5bded 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -10,7 +10,6 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; -use Bitrix24\Lib\Bitrix24Accounts\Exceptions\MultipleBitrix24AccountsFoundException; use Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall\Command; use Psr\Log\LoggerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index e843460..25e28fc 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -85,9 +85,11 @@ protected function setUp(): void { $entityManager = EntityManagerFactory::get(); $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager); $this->handler = new Handler( new EventDispatcher(), $this->repository, + $this->flusher, new NullLogger() ); } From db1357095aae1869fb044da5f9455306b6780aff Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 4 Nov 2024 00:33:58 +0600 Subject: [PATCH 046/130] Remove SaveAccount use case and add proper Uninstall testing Deleted the SaveAccount use case and related tests to streamline the project. Enhanced the Uninstall use case by adding a unit test for the handler and integrating the Flusher service for better transaction management. Signed-off-by: mesilov --- .../Doctrine/Bitrix24AccountRepository.php | 1 - .../UseCase/SaveAccount/Command.php | 15 ---- .../UseCase/SaveAccount/Handler.php | 23 ----- .../UseCase/Uninstall/Command.php | 13 ++- .../UseCase/Uninstall/Handler.php | 5 +- .../UseCase/SaveAccount/HandlerTest.php | 41 --------- .../UseCase/Uninstall/HandlerTest.php | 85 +++++++++++++++++++ 7 files changed, 93 insertions(+), 90 deletions(-) delete mode 100644 src/Bitrix24Accounts/UseCase/SaveAccount/Command.php delete mode 100644 src/Bitrix24Accounts/UseCase/SaveAccount/Handler.php delete mode 100644 tests/Functional/Bitrix24Accounts/UseCase/SaveAccount/HandlerTest.php create mode 100644 tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 4598636..93196ad 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -107,7 +107,6 @@ public function findAllActive(): array /** * @param non-empty-string $applicationToken * @phpstan-return array - * @todo discuss are we need add this method in contract in b24phpsdk? */ public function findByApplicationToken(string $applicationToken): array { diff --git a/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php b/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php deleted file mode 100644 index e294d7c..0000000 --- a/src/Bitrix24Accounts/UseCase/SaveAccount/Command.php +++ /dev/null @@ -1,15 +0,0 @@ -repository->save($command->bitrix24Account); - - $this->flusher->flush(); - } -} \ No newline at end of file diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php index d0bd745..16038c8 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php @@ -4,15 +4,12 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall; -use Bitrix24\SDK\Core\Credentials\AuthToken; -use Bitrix24\SDK\Core\Credentials\Scope; -use Symfony\Component\Uid\Uuid; - readonly class Command { public function __construct( + /** + * @var non-empty-string $applicationToken + */ public string $applicationToken - ) - { - } -} \ No newline at end of file + ) {} +} diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index fd5bded..60b4282 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall; +use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; @@ -19,6 +20,7 @@ public function __construct( private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, + private Flusher $flusher, private LoggerInterface $logger ) { @@ -33,13 +35,12 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.Uninstall.start', [ 'b24_application_token' => $command->applicationToken, ]); - //todo remove after update contract in b24phpsdk - /** @phpstan-ignore-next-line */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); foreach ($accounts as $account) { $account->applicationUninstalled($command->applicationToken); $this->bitrix24AccountRepository->save($account); + $this->flusher->flush(); foreach ($account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/SaveAccount/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/SaveAccount/HandlerTest.php deleted file mode 100644 index 9bc80fe..0000000 --- a/tests/Functional/Bitrix24Accounts/UseCase/SaveAccount/HandlerTest.php +++ /dev/null @@ -1,41 +0,0 @@ - + * + * For the full copyright and license information, please view the MIT-LICENSE.txt + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\Uninstall; + +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\Lib\Services\Flusher; +use Bitrix24\Lib\Bitrix24Accounts; +use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; +use Carbon\CarbonImmutable; +use Override; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Uid\Uuid; + +#[CoversClass(Bitrix24Accounts\UseCase\Uninstall\Handler::class)] +class HandlerTest extends TestCase +{ + private Bitrix24Accounts\UseCase\Uninstall\Handler $handler; + private Flusher $flusher; + + private Bitrix24AccountRepositoryInterface $repository; + + #[Test] + public function testUninstallWithHappyPath(): void + { + $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $bitrix24Account = new Bitrix24Account( + Uuid::v7(), + 1, + true, + Uuid::v7()->toRfc4122(), + $oldDomainUrl, + Bitrix24AccountStatus::new, + new AuthToken('old_1', 'old_2', 3600), + new CarbonImmutable(), + new CarbonImmutable(), + 1, + new Scope() + ); + + $applicationToken = Uuid::v7()->toRfc4122(); + $bitrix24Account->applicationInstalled($applicationToken); + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + + $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); + + $updated = $this->repository->getById($bitrix24Account->getId()); + $this->assertEquals(Bitrix24AccountStatus::deleted, $updated->getStatus()); + } + + #[Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager); + $this->handler = new Bitrix24Accounts\UseCase\Uninstall\Handler( + new EventDispatcher(), + $this->repository, + $this->flusher, + new NullLogger() + ); + } +} \ No newline at end of file From 87639e763bfa55aedfc6cda9baed98be73ce7834 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 4 Nov 2024 00:55:26 +0600 Subject: [PATCH 047/130] Add TraceableEventDispatcher to HandlerTests Refactor HandlerTests to use TraceableEventDispatcher, enabling better tracking of events. This change improves the readability and maintainability of test cases by using a consistent event dispatching mechanism. Signed-off-by: mesilov --- .../UseCase/ChangeDomainUrl/HandlerTest.php | 18 +++++++++++------- .../UseCase/InstallFinish/HandlerTest.php | 15 ++++++++++----- .../UseCase/InstallStart/HandlerTest.php | 13 ++++++++++++- .../UseCase/RenewAuthToken/HandlerTest.php | 10 ++++++++-- .../UseCase/Uninstall/HandlerTest.php | 12 ++++++++++-- 5 files changed, 51 insertions(+), 17 deletions(-) diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index e1d637f..065c1b9 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -18,19 +18,20 @@ use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; -use Bitrix24\SDK\Application\ApplicationStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationInstalledEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; -use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; use Carbon\CarbonImmutable; use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; #[CoversClass(Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler::class)] @@ -40,6 +41,7 @@ class HandlerTest extends TestCase private Flusher $flusher; private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; #[Test] public function testRenewAuthTokenWithoutBitrix24UserId(): void @@ -70,10 +72,11 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void ); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertEquals( - $newDomainUrl, - $updated->getDomainUrl() - ); + $this->assertEquals($newDomainUrl, $updated->getDomainUrl()); + + $this->assertTrue(in_array( + Bitrix24AccountApplicationInstalledEvent::class, + $this->eventDispatcher->getOrphanedEvents())); } #[Override] @@ -82,8 +85,9 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager); + $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->handler = new Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler( - new EventDispatcher(), + $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 4ddc51d..246a080 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -18,19 +18,20 @@ use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; -use Bitrix24\SDK\Application\ApplicationStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; -use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; use Carbon\CarbonImmutable; use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; #[CoversClass(Bitrix24Accounts\UseCase\InstallFinish\Handler::class)] @@ -38,9 +39,8 @@ class HandlerTest extends TestCase { private Bitrix24Accounts\UseCase\InstallFinish\Handler $handler; private Flusher $flusher; - private Bitrix24AccountRepositoryInterface $repository; - + private TraceableEventDispatcher $eventDispatcher; #[Test] public function testRenewAuthTokenWithoutBitrix24UserId(): void { @@ -72,6 +72,10 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertTrue($updated->isApplicationTokenValid($applicationToken)); + + $this->assertTrue(in_array( + Bitrix24AccountDomainUrlChangedEvent::class, + $this->eventDispatcher->getOrphanedEvents())); } #[Override] @@ -80,8 +84,9 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager); + $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->handler = new Bitrix24Accounts\UseCase\InstallFinish\Handler( - new EventDispatcher(), + $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index d93b74a..315b4dd 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -20,6 +20,8 @@ use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\SDK\Application\ApplicationStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountCreatedEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; @@ -34,7 +36,9 @@ use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Random\RandomException; +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; #[CoversClass(Bitrix24Accounts\UseCase\InstallStart\Handler::class)] @@ -43,6 +47,7 @@ class HandlerTest extends TestCase private Bitrix24Accounts\UseCase\InstallStart\Handler $handler; private Flusher $flusher; private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; /** * @throws InvalidArgumentException @@ -82,6 +87,11 @@ public function testInstallStartHappyPath(): void $this->assertEquals($authToken, $account->getAuthToken()); $this->assertEquals($appVersion, $account->getApplicationVersion()); $this->assertEquals($scope, $account->getApplicationScope()); + + + $this->assertTrue(in_array( + Bitrix24AccountCreatedEvent::class, + $this->eventDispatcher->getOrphanedEvents())); } #[Override] @@ -90,8 +100,9 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager); + $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->handler = new Bitrix24Accounts\UseCase\InstallStart\Handler( - new EventDispatcher(), + $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 25e28fc..6d28b3e 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -31,15 +31,17 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; #[CoversClass(Handler::class)] class HandlerTest extends TestCase { private Handler $handler; - private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; #[Test] public function testRenewAuthTokenWithoutBitrix24UserId(): void @@ -77,6 +79,9 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertEquals($newAuthToken->accessToken, $updated->getAuthToken()->accessToken); $this->assertEquals($newAuthToken->refreshToken, $updated->getAuthToken()->refreshToken); + + // на продлении токенов событий не бросаем + $this->assertCount(0, $this->eventDispatcher->getOrphanedEvents()); } @@ -86,8 +91,9 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager); + $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->handler = new Handler( - new EventDispatcher(), + $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 1351bad..31cddc5 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -19,6 +19,7 @@ use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationUninstalledEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; @@ -28,7 +29,9 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; #[CoversClass(Bitrix24Accounts\UseCase\Uninstall\Handler::class)] @@ -36,8 +39,8 @@ class HandlerTest extends TestCase { private Bitrix24Accounts\UseCase\Uninstall\Handler $handler; private Flusher $flusher; - private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; #[Test] public function testUninstallWithHappyPath(): void @@ -67,6 +70,10 @@ public function testUninstallWithHappyPath(): void $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertEquals(Bitrix24AccountStatus::deleted, $updated->getStatus()); + + $this->assertTrue(in_array( + Bitrix24AccountApplicationUninstalledEvent::class, + $this->eventDispatcher->getOrphanedEvents())); } #[Override] @@ -75,8 +82,9 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager); + $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->handler = new Bitrix24Accounts\UseCase\Uninstall\Handler( - new EventDispatcher(), + $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() From 313751098980a25b6ed328432ee51a91867b1bd7 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 4 Nov 2024 01:03:22 +0600 Subject: [PATCH 048/130] Update test to check for domain URL change event Refactor HandlerTest to assert that the Bitrix24AccountDomainUrlChangedEvent is triggered instead of Bitrix24AccountApplicationInstalledEvent. This ensures the correct event is dispatched when the domain URL changes. Signed-off-by: mesilov --- .../Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index 065c1b9..1ac611b 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -20,6 +20,7 @@ use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationInstalledEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; @@ -75,7 +76,7 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void $this->assertEquals($newDomainUrl, $updated->getDomainUrl()); $this->assertTrue(in_array( - Bitrix24AccountApplicationInstalledEvent::class, + Bitrix24AccountDomainUrlChangedEvent::class, $this->eventDispatcher->getOrphanedEvents())); } From 7467889e7ec20eb41ab4a0fa83237b78d564c895 Mon Sep 17 00:00:00 2001 From: mesilov Date: Mon, 4 Nov 2024 01:05:52 +0600 Subject: [PATCH 049/130] Remove unused import in HandlerTest.php Removed the unused `Bitrix24AccountApplicationInstalledEvent` import in the `ChangeDomainUrl/HandlerTest.php` file. This cleanup helps reduce code clutter and improve readability. Signed-off-by: mesilov --- .../Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index 1ac611b..a0e1c08 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -19,7 +19,6 @@ use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationInstalledEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; From fc01b558ea0b4884f06ab5c606c73b7b1b135156 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 3 Nov 2024 22:33:22 +0300 Subject: [PATCH 050/130] =?UTF-8?q?-=20=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20?= =?UTF-8?q?=D0=B0=D0=B2=D1=82=D0=BE=D0=B3=D0=B5=D0=BD=D0=B5=D1=80=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8E=20-=20=D0=9F=D0=BE=D1=84=D0=B8=D0=BA=D1=81?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=81=D1=82=D0=B0=D1=82=D1=83=D1=81=20=D0=BF?= =?UTF-8?q?=D1=80=D0=B8=20=D1=82=D0=B5=D1=81=D1=82=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...x24Accounts.Entity.Bitrix24Account.dcm.xml | 8 +-- .../Entity/Bitrix24Account.php | 60 +++++++++---------- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index 7204f98..605d064 100644 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -2,9 +2,7 @@ xmlns:xs="https://www.w3.org/2001/XMLSchema" xmlns:orm="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> - - - + @@ -14,10 +12,12 @@ - + + + diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 1de7dc3..3d33815 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -62,23 +62,23 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEm public function __construct( #[ORM\Id] #[ORM\Column(type: UuidType::NAME, unique: true)] - private Uuid $uuid, + private Uuid $id, #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] #[SerializedName('b24_user_id')] private readonly int $bitrix24UserId, #[ORM\Column(name: 'is_b24_user_admin', type: 'boolean', nullable: false)] #[SerializedName('is_b24_user_admin')] - private readonly bool $isBitrix24UserAdmin, + private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ #[ORM\Column(name: 'member_id', type: 'string', nullable: false)] #[SerializedName('member_id')] - private readonly string $memberId, + private readonly string $memberId, #[ORM\Column(name: 'domain_url', type: 'string', nullable: false)] #[SerializedName('domain_url')] private string $domainUrl, #[ORM\Column(name: 'account_status', type: 'string', nullable: false, enumType: Bitrix24AccountStatus::class)] - private Bitrix24AccountStatus $accountStatus, - AuthToken $authToken, + private Bitrix24AccountStatus $status, + AuthToken $authToken, #[ORM\Column(name: 'created_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] #[Ignore] private readonly CarbonImmutable $createdAt, @@ -101,7 +101,7 @@ public function __construct( #[Override] public function getId(): Uuid { - return $this->uuid; + return $this->id; } #[Override] @@ -131,7 +131,7 @@ public function getDomainUrl(): string #[Override] public function getStatus(): Bitrix24AccountStatus { - return $this->accountStatus; + return $this->status; } #[Override] @@ -151,7 +151,7 @@ public function renewAuthToken(RenewedAuthToken $renewedAuthToken): void sprintf( 'member id %s for bitrix24 account %s for domain %s mismatch with member id %s for renewed access token', $this->memberId, - $this->uuid->toRfc4122(), + $this->id->toRfc4122(), $this->domainUrl, $renewedAuthToken->memberId, ) @@ -189,13 +189,13 @@ public function changeDomainUrl(string $newDomainUrl): void throw new InvalidArgumentException('new domain url cannot be empty'); } - if (Bitrix24AccountStatus::blocked === $this->accountStatus || Bitrix24AccountStatus::deleted === $this->accountStatus) { + if (Bitrix24AccountStatus::blocked === $this->status || Bitrix24AccountStatus::deleted === $this->status) { throw new InvalidArgumentException( sprintf( 'bitrix24 account %s for domain %s must be in active or new state, now account in %s state. domain url cannot be changed', - $this->uuid->toRfc4122(), + $this->id->toRfc4122(), $this->domainUrl, - $this->accountStatus->name + $this->status->name ) ); } @@ -203,7 +203,7 @@ public function changeDomainUrl(string $newDomainUrl): void $this->domainUrl = $newDomainUrl; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountDomainUrlChangedEvent( - $this->uuid, + $this->id, new CarbonImmutable() ); } @@ -214,21 +214,21 @@ public function changeDomainUrl(string $newDomainUrl): void #[Override] public function applicationInstalled(string $applicationToken): void { - if (Bitrix24AccountStatus::new !== $this->accountStatus) { + if (Bitrix24AccountStatus::new !== $this->status) { throw new InvalidArgumentException(sprintf( 'for finish installation bitrix24 account must be in status «new», current status - «%s»', - $this->accountStatus->name)); + $this->status->name)); } if ($applicationToken === '') { throw new InvalidArgumentException('application token cannot be empty'); } - $this->accountStatus = Bitrix24AccountStatus::active; + $this->status = Bitrix24AccountStatus::active; $this->applicationToken = $applicationToken; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountApplicationInstalledEvent( - $this->uuid, + $this->id, new CarbonImmutable() ); } @@ -243,10 +243,10 @@ public function applicationUninstalled(string $applicationToken): void throw new InvalidArgumentException('application token cannot be empty'); } - if (Bitrix24AccountStatus::active !== $this->accountStatus) { + if (Bitrix24AccountStatus::active !== $this->status) { throw new InvalidArgumentException(sprintf( 'for uninstall account must be in status «active», current status - «%s»', - $this->accountStatus->name)); + $this->status->name)); } if ($this->applicationToken !== $applicationToken) { @@ -255,16 +255,16 @@ public function applicationUninstalled(string $applicationToken): void 'application token «%s» mismatch with application token «%s» for bitrix24 account %s for domain %s', $applicationToken, $this->applicationToken, - $this->uuid->toRfc4122(), + $this->id->toRfc4122(), $this->domainUrl ) ); } - $this->accountStatus = Bitrix24AccountStatus::deleted; + $this->status = Bitrix24AccountStatus::deleted; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountApplicationUninstalledEvent( - $this->uuid, + $this->id, new CarbonImmutable() ); } @@ -293,8 +293,8 @@ public function getUpdatedAt(): CarbonImmutable #[Override] public function updateApplicationVersion(int $version, ?Scope $newScope): void { - if (Bitrix24AccountStatus::active !== $this->accountStatus) { - throw new InvalidArgumentException(sprintf('account must be in status «active», but now account in status «%s»', $this->accountStatus->name)); + if (Bitrix24AccountStatus::active !== $this->status) { + throw new InvalidArgumentException(sprintf('account must be in status «active», but now account in status «%s»', $this->status->name)); } if ($this->applicationVersion >= $version) { @@ -311,7 +311,7 @@ public function updateApplicationVersion(int $version, ?Scope $newScope): void $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountApplicationVersionUpdatedEvent( - $this->uuid, + $this->id, new CarbonImmutable() ); } @@ -322,13 +322,13 @@ public function updateApplicationVersion(int $version, ?Scope $newScope): void #[Override] public function markAsActive(?string $comment): void { - if (Bitrix24AccountStatus::blocked !== $this->accountStatus) { + if (Bitrix24AccountStatus::blocked !== $this->status) { throw new InvalidArgumentException( sprintf('you can activate account only in status blocked, now account in status %s', - $this->accountStatus->name)); + $this->status->name)); } - $this->accountStatus = Bitrix24AccountStatus::active; + $this->status = Bitrix24AccountStatus::active; $this->comment = $comment; $this->updatedAt = new CarbonImmutable(); } @@ -339,15 +339,15 @@ public function markAsActive(?string $comment): void #[Override] public function markAsBlocked(?string $comment): void { - if (Bitrix24AccountStatus::deleted === $this->accountStatus) { + if (Bitrix24AccountStatus::deleted === $this->status) { throw new InvalidArgumentException('you cannot block account in status «deleted»'); } - $this->accountStatus = Bitrix24AccountStatus::blocked; + $this->status = Bitrix24AccountStatus::blocked; $this->comment = $comment; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountBlockedEvent( - $this->uuid, + $this->id, new CarbonImmutable() ); } From 0d169d35c2e1b7598fd4b7d85a65673243c30bad Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Mon, 4 Nov 2024 18:00:12 +0300 Subject: [PATCH 051/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=8F=D0=BB=20=D1=82=D0=B8=D0=BF=20=D0=B2=20=D0=BC=D0=B0=D0=BF?= =?UTF-8?q?=D0=BF=D0=B8=D0=BD=D0=B3=D0=B5=20=D1=81=20datetime=5Fimmutable?= =?UTF-8?q?=20=D0=BD=D0=B0=20carbon=5Fimmutable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index 605d064..0d19a83 100644 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -3,9 +3,11 @@ xmlns:orm="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + + @@ -14,16 +16,16 @@ - - - + - + + + \ No newline at end of file From 37aea9ae9ade646c4f54d08edb1af6ec39aec847 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Thu, 7 Nov 2024 23:52:45 +0300 Subject: [PATCH 052/130] =?UTF-8?q?-=20=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20?= =?UTF-8?q?=D0=B2=20=D0=B0=D0=BA=D0=BA=D0=B0=D1=83=D0=BD=D1=82=D0=B5=20?= =?UTF-8?q?=D0=B0=D1=82=D1=80=D0=B8=D0=B1=D1=83=D1=82=D1=8B=20-=20=D0=94?= =?UTF-8?q?=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=B2=20=D1=82=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=B5=20=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D1=82=D0=BE=D0=BA=D0=B5=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=B7=D0=BE=D0=B2=20flusher=20-=20=D0=A3=D0=B1?= =?UTF-8?q?=D1=80=D0=B0=D0=BB=20=D0=B8=D0=B7=20=D1=80=D0=B5=D0=BF=D0=BE?= =?UTF-8?q?=D0=B7=D0=B8=D1=82=D0=BE=D1=80=D0=B8=D1=8F=20=D0=B2=D1=8B=D0=B7?= =?UTF-8?q?=D0=BE=D0=B2=D1=8B=20flusher?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entity/Bitrix24Account.php | 24 ------------------- .../Doctrine/Bitrix24AccountRepository.php | 12 ++-------- .../UseCase/RenewAuthToken/Handler.php | 1 + .../UseCase/RenewAuthToken/HandlerTest.php | 3 +++ 4 files changed, 6 insertions(+), 34 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 3d33815..b0cb6e4 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -25,18 +25,11 @@ use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Bitrix24\SDK\Core\Exceptions\UnknownScopeCodeException; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; -use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Carbon\CarbonImmutable; -use Doctrine\ORM\Mapping\Embedded; use Override; -use Symfony\Bridge\Doctrine\Types\UuidType; -use Symfony\Component\Serializer\Annotation\Ignore; -use Symfony\Component\Serializer\Annotation\SerializedName; use Symfony\Component\Uid\Uuid; -use Doctrine\ORM\Mapping as ORM; use Symfony\Contracts\EventDispatcher\Event; -#[ORM\Entity(repositoryClass: Bitrix24AccountRepository::class)] class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEmitterInterface { private string $accessToken; @@ -60,33 +53,16 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEm public function __construct( - #[ORM\Id] - #[ORM\Column(type: UuidType::NAME, unique: true)] private Uuid $id, - #[ORM\Column(name: 'b24_user_id', type: 'integer', nullable: false)] - #[SerializedName('b24_user_id')] private readonly int $bitrix24UserId, - #[ORM\Column(name: 'is_b24_user_admin', type: 'boolean', nullable: false)] - #[SerializedName('is_b24_user_admin')] private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ - #[ORM\Column(name: 'member_id', type: 'string', nullable: false)] - #[SerializedName('member_id')] private readonly string $memberId, - #[ORM\Column(name: 'domain_url', type: 'string', nullable: false)] - #[SerializedName('domain_url')] private string $domainUrl, - #[ORM\Column(name: 'account_status', type: 'string', nullable: false, enumType: Bitrix24AccountStatus::class)] private Bitrix24AccountStatus $status, AuthToken $authToken, - #[ORM\Column(name: 'created_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] - #[Ignore] private readonly CarbonImmutable $createdAt, - #[ORM\Column(name: 'update_at_utc', type: 'carbon_immutable', precision: 3, nullable: false)] - #[Ignore] private CarbonImmutable $updatedAt, - #[ORM\Column(name: 'application_version', type: 'integer', nullable: false)] - #[Ignore] private int $applicationVersion, Scope $applicationScope, ) diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 93196ad..122ef99 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -49,12 +49,7 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface #[Override] public function save(Bitrix24AccountInterface $bitrix24Account): void { - $this->getEntityManager()->persist($bitrix24Account); - - //todo discuss add flush arg to contract or add flusher in usecases? - $this->getEntityManager()->flush(); - } /** @@ -81,18 +76,15 @@ public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix2 * @inheritdoc */ #[Override] - public function delete(Uuid $uuid, bool $flush = false): void + public function delete(Uuid $uuid): void { $bitrix24Account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); + if ($bitrix24Account === null) { throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); } $this->getEntityManager()->remove($bitrix24Account); - - if ($flush) { - $this->getEntityManager()->flush(); - } } public function findAllActive(): array diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index e5987d3..3fe5632 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -62,6 +62,7 @@ public function handle(Command $command): void } $targetAccount = $accounts[0]; + /** * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 6d28b3e..6ea1f6e 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -40,6 +40,7 @@ class HandlerTest extends TestCase { private Handler $handler; + private Flusher $flusher; private Bitrix24AccountRepositoryInterface $repository; private TraceableEventDispatcher $eventDispatcher; @@ -62,6 +63,8 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void $this->repository->save($bitrix24Account); + $this->flusher->flush(); + $newAuthToken = new AuthToken('new_1', 'new_2', 3600); $this->handler->handle( new Command( From 5340ec885b1924ef33f717b5e2dc6a54b681bc8b Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 10 Nov 2024 13:03:57 +0600 Subject: [PATCH 053/130] Add FlusherDecorator for functional tests Introduce the `FlusherDecorator` to facilitate flushing in functional tests. Updated `Bitrix24AccountRepositoryTest` to use this new decorator. Enhanced the Makefile to include an ORM schema update command for functional test execution. Signed-off-by: mesilov --- Makefile | 1 + .../UseCase/InstallStart/Command.php | 20 +++++++++---------- .../Bitrix24AccountRepositoryTest.php | 8 ++++++++ tests/Functional/FlusherDecorator.php | 20 +++++++++++++++++++ 4 files changed, 38 insertions(+), 11 deletions(-) create mode 100644 tests/Functional/FlusherDecorator.php diff --git a/Makefile b/Makefile index ac38090..03001c5 100644 --- a/Makefile +++ b/Makefile @@ -95,6 +95,7 @@ test-run-unit: test-run-functional: debug-print-env docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create + docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:update --dump-sql docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox schema-drop: diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index 8b41877..b650275 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -11,15 +11,13 @@ readonly class Command { public function __construct( - public Uuid $uuid, - public int $bitrix24UserId, - public bool $isBitrix24UserAdmin, - public string $memberId, - public string $domainUrl, + public Uuid $uuid, + public int $bitrix24UserId, + public bool $isBitrix24UserAdmin, + public string $memberId, + public string $domainUrl, public AuthToken $authToken, - public int $applicationVersion, - public Scope $applicationScope - ) - { - } -} \ No newline at end of file + public int $applicationVersion, + public Scope $applicationScope + ) {} +} diff --git a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php index 24fbfd4..cf6e12b 100644 --- a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php +++ b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php @@ -17,12 +17,14 @@ use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\Lib\Tests\Functional\FlusherDecorator; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Tests\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterfaceTest; +use Bitrix24\SDK\Tests\Application\Contracts\TestRepositoryFlusherInterface; use Carbon\CarbonImmutable; use Override; use PHPUnit\Framework\Attributes\CoversClass; @@ -67,4 +69,10 @@ protected function createBitrix24AccountRepositoryImplementation(): Bitrix24Acco $entityManager = EntityManagerFactory::get(); return new Bitrix24AccountRepository($entityManager); } + + #[Override] + protected function createRepositoryFlusherImplementation(): TestRepositoryFlusherInterface + { + return new FlusherDecorator(new Flusher(EntityManagerFactory::get())); + } } \ No newline at end of file diff --git a/tests/Functional/FlusherDecorator.php b/tests/Functional/FlusherDecorator.php new file mode 100644 index 0000000..d2aef2c --- /dev/null +++ b/tests/Functional/FlusherDecorator.php @@ -0,0 +1,20 @@ +flusher->flush(); + } +} From 33f6356a0e9a4becbae21acc7d7cf07a797daf73 Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 10 Nov 2024 13:20:55 +0600 Subject: [PATCH 054/130] Refactor and enforce input validation in Bitrix24AccountRepository Remove unused use statement and improve code formatting for consistency. Add input validation for non-empty strings and introduce error handling for invalid account statuses in delete method. Signed-off-by: mesilov --- .../Doctrine/Bitrix24AccountRepository.php | 52 +++++++++++-------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 122ef99..daaad13 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -5,7 +5,6 @@ namespace Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine; use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; -use Bitrix24\Lib\Bitrix24Accounts\UseCase\SaveAccount\Handler; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; @@ -21,31 +20,28 @@ class Bitrix24AccountRepository extends EntityRepository implements Bitrix24Acco { public function __construct( EntityManagerInterface $entityManager - ) - { + ) { parent::__construct($entityManager, $entityManager->getClassMetadata(Bitrix24Account::class)); } /** * @phpstan-return Bitrix24AccountInterface&AggregateRootEventsEmitterInterface + * * @throws Bitrix24AccountNotFoundException */ #[Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { - // print_r($uuid); - // exit(); + // print_r($uuid); + // exit(); $res = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); - if ($res === null) { + if (null === $res) { throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); } return $res; } - /** - * @inheritdoc - */ #[Override] public function save(Bitrix24AccountInterface $bitrix24Account): void { @@ -54,35 +50,45 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void /** * @phpstan-return array + * + * @throws InvalidArgumentException */ #[Override] - public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?int $bitrix24UserId = null, ?bool $isAdmin = null): array + public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?int $bitrix24UserId = null, ?bool $isAdmin = null): array { + if ('' === trim($memberId)) { + throw new InvalidArgumentException('memberId cannot be empty'); + } + $criteria = [ - 'memberId' => $memberId + 'memberId' => $memberId, ]; if ($bitrix24AccountStatus instanceof Bitrix24AccountStatus) { $criteria['status'] = $bitrix24AccountStatus->name; } - if ($isAdmin !== null) { + if (null !== $isAdmin) { $criteria['isBitrix24UserAdmin'] = $isAdmin; } return $this->findBy($criteria); } - /** - * @inheritdoc - */ #[Override] public function delete(Uuid $uuid): void { $bitrix24Account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); - if ($bitrix24Account === null) { + if (null === $bitrix24Account) { throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); } + if (Bitrix24AccountStatus::deleted !== $bitrix24Account->getStatus()) { + throw new InvalidArgumentException(sprintf( + 'you cannot delete bitrix24account «%s», they must be in status «deleted», current status «%s»', + $bitrix24Account->getId()->toRfc4122(), + $bitrix24Account->getStatus()->name + )); + } $this->getEntityManager()->remove($bitrix24Account); } @@ -98,6 +104,7 @@ public function findAllActive(): array /** * @param non-empty-string $applicationToken + * * @phpstan-return array */ public function findByApplicationToken(string $applicationToken): array @@ -111,12 +118,13 @@ public function findByApplicationToken(string $applicationToken): array /** * @throws InvalidArgumentException + * * @phpstan-return Bitrix24AccountInterface&AggregateRootEventsEmitterInterface */ #[Override] public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterface { - if (trim($memberId) === '') { + if ('' === trim($memberId)) { throw new InvalidArgumentException('memberId cannot be an empty string'); } @@ -131,13 +139,15 @@ public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterf /** * @phpstan-return array - * @return array + * + * @return array + * * @throws InvalidArgumentException */ #[Override] public function findByDomain(string $domainUrl, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?bool $isAdmin = null): array { - if (trim($domainUrl) === '') { + if ('' === trim($domainUrl)) { throw new InvalidArgumentException('domainUrl cannot be an empty string'); } @@ -148,10 +158,10 @@ public function findByDomain(string $domainUrl, ?Bitrix24AccountStatus $bitrix24 $criteria['status'] = $bitrix24AccountStatus->name; } - if ($isAdmin !== null) { + if (null !== $isAdmin) { $criteria['isBitrix24UserAdmin'] = $isAdmin; } return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findBy($criteria); } -} \ No newline at end of file +} From e648cbaf9c886c4d80cc84896a0ab8893cedc26b Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 10 Nov 2024 14:22:25 +0600 Subject: [PATCH 055/130] Fix formatting and simplify tests Adjusted the whitespace formatting in Handler.php and Bitrix24Account.php for improved readability. Refactored HandlerTest.php to use Bitrix24AccountBuilder for cleaner test setup and added a new test case for handling domain URL changes across multiple accounts. Signed-off-by: mesilov --- .../Entity/Bitrix24Account.php | 55 +++++---- .../UseCase/InstallFinish/Handler.php | 20 ++- .../Builders/Bitrix24AccountBuilder.php | 89 ++++++++++++++ .../UseCase/ChangeDomainUrl/HandlerTest.php | 114 ++++++++++++------ .../UseCase/InstallFinish/HandlerTest.php | 47 ++++---- 5 files changed, 229 insertions(+), 96 deletions(-) create mode 100644 tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index b0cb6e4..135d1e7 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -51,22 +51,20 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEm */ private array $events = []; - public function __construct( - private Uuid $id, - private readonly int $bitrix24UserId, - private readonly bool $isBitrix24UserAdmin, + private Uuid $id, + private readonly int $bitrix24UserId, + private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ - private readonly string $memberId, - private string $domainUrl, - private Bitrix24AccountStatus $status, - AuthToken $authToken, + private readonly string $memberId, + private string $domainUrl, + private Bitrix24AccountStatus $status, + AuthToken $authToken, private readonly CarbonImmutable $createdAt, - private CarbonImmutable $updatedAt, - private int $applicationVersion, - Scope $applicationScope, - ) - { + private CarbonImmutable $updatedAt, + private int $applicationVersion, + Scope $applicationScope, + ) { $this->authToken = $authToken; $this->accessToken = $authToken->accessToken; $this->refreshToken = $authToken->refreshToken; @@ -161,7 +159,7 @@ public function getApplicationScope(): Scope #[Override] public function changeDomainUrl(string $newDomainUrl): void { - if ($newDomainUrl === '') { + if ('' === $newDomainUrl) { throw new InvalidArgumentException('new domain url cannot be empty'); } @@ -193,10 +191,11 @@ public function applicationInstalled(string $applicationToken): void if (Bitrix24AccountStatus::new !== $this->status) { throw new InvalidArgumentException(sprintf( 'for finish installation bitrix24 account must be in status «new», current status - «%s»', - $this->status->name)); + $this->status->name + )); } - if ($applicationToken === '') { + if ('' === $applicationToken) { throw new InvalidArgumentException('application token cannot be empty'); } @@ -215,14 +214,15 @@ public function applicationInstalled(string $applicationToken): void #[Override] public function applicationUninstalled(string $applicationToken): void { - if ($applicationToken === '') { + if ('' === $applicationToken) { throw new InvalidArgumentException('application token cannot be empty'); } if (Bitrix24AccountStatus::active !== $this->status) { throw new InvalidArgumentException(sprintf( 'for uninstall account must be in status «active», current status - «%s»', - $this->status->name)); + $this->status->name + )); } if ($this->applicationToken !== $applicationToken) { @@ -275,13 +275,16 @@ public function updateApplicationVersion(int $version, ?Scope $newScope): void if ($this->applicationVersion >= $version) { throw new InvalidArgumentException( - sprintf('you cannot downgrade application version or set some version, current version «%s», but you try to upgrade to «%s»', + sprintf( + 'you cannot downgrade application version or set some version, current version «%s», but you try to upgrade to «%s»', $this->applicationVersion, - $version)); + $version + ) + ); } $this->applicationVersion = $version; - if ($newScope instanceof \Bitrix24\SDK\Core\Credentials\Scope) { + if ($newScope instanceof Scope) { $this->applicationScope = $newScope->getScopeCodes(); } @@ -300,8 +303,11 @@ public function markAsActive(?string $comment): void { if (Bitrix24AccountStatus::blocked !== $this->status) { throw new InvalidArgumentException( - sprintf('you can activate account only in status blocked, now account in status %s', - $this->status->name)); + sprintf( + 'you can activate account only in status «blocked», now account in status «%s»', + $this->status->name + ) + ); } $this->status = Bitrix24AccountStatus::active; @@ -342,6 +348,7 @@ public function emitEvents(): array { $events = $this->events; $this->events = []; + return $events; } -} \ No newline at end of file +} diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 91ebc39..f53e467 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -17,13 +17,11 @@ readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, + private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) - { - } + private Flusher $flusher, + private LoggerInterface $logger + ) {} /** * @throws Bitrix24AccountNotFoundException @@ -34,7 +32,7 @@ public function handle(Command $command): void 'b24_domain_url' => $command->domainUrl, 'b24_member_id' => $command->memberId, 'b24_application_id' => $command->applicationToken, - 'b24_user_id' => $command->bitrix24UserId + 'b24_user_id' => $command->bitrix24UserId, ]); $accounts = $this->bitrix24AccountRepository->findByMemberId( @@ -42,7 +40,7 @@ public function handle(Command $command): void Bitrix24AccountStatus::new, $command->bitrix24UserId ); - if ($accounts === []) { + if ([] === $accounts) { throw new Bitrix24AccountNotFoundException(sprintf( 'bitrix24 account for domain %s with member id %s in status «new» not found', $command->domainUrl, @@ -59,9 +57,7 @@ public function handle(Command $command): void } $targetAccount = $accounts[0]; - /** - * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount - */ + // @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount $targetAccount->applicationInstalled($command->applicationToken); $this->bitrix24AccountRepository->save($targetAccount); @@ -72,4 +68,4 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.InstallFinish.Finish'); } -} \ No newline at end of file +} diff --git a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php new file mode 100644 index 0000000..25538ec --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php @@ -0,0 +1,89 @@ + + * + * For the full copyright and license information, please view the MIT-LICENSE.txt + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders; + +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; +use Carbon\CarbonImmutable; +use Symfony\Component\Uid\Uuid; + +class Bitrix24AccountBuilder +{ + private Uuid $id; + private int $bitrix24UserId; + private bool $isBitrix24UserAdmin; + /** bitrix24 portal unique id */ + private string $memberId; + private string $domainUrl; + private Bitrix24AccountStatus $status; + private AuthToken $authToken; + private CarbonImmutable $createdAt; + private CarbonImmutable $updatedAt; + private int $applicationVersion; + private Scope $applicationScope; + + public function __construct() + { + $this->id = Uuid::v7(); + $this->bitrix24UserId = random_int(1, 1_000_000); + $this->isBitrix24UserAdmin = true; + $this->memberId = Uuid::v4()->toRfc4122(); + $this->domainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $this->status = Bitrix24AccountStatus::active; + $this->authToken = new AuthToken('old_1', 'old_2', 3600); + $this->createdAt = CarbonImmutable::now(); + $this->updatedAt = CarbonImmutable::now(); + $this->applicationVersion = 1; + $this->applicationScope = new Scope(); + } + + public function withMemberId(string $memberId): self + { + $this->memberId = $memberId; + return $this; + } + + public function withDomainUrl(string $domainUrl): self + { + $this->domainUrl = $domainUrl; + return $this; + } + + public function withStatus(Bitrix24AccountStatus $status): self + { + $this->status = $status; + return $this; + } + + public function build(): AggregateRootEventsEmitterInterface&Bitrix24AccountInterface + { + return new Bitrix24Account( + $this->id, + $this->bitrix24UserId, + $this->isBitrix24UserAdmin, + $this->memberId, + $this->domainUrl, + $this->status, + $this->authToken, + $this->createdAt, + $this->updatedAt, + $this->applicationVersion, + $this->applicationScope + ); + } +} diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index a0e1c08..16e5dd2 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -13,20 +13,16 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\ChangeDomainUrl; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; -use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\SDK\Core\Credentials\AuthToken; -use Bitrix24\SDK\Core\Credentials\Scope; -use Carbon\CarbonImmutable; -use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; @@ -34,6 +30,9 @@ use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; +/** + * @internal + */ #[CoversClass(Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler::class)] class HandlerTest extends TestCase { @@ -43,27 +42,35 @@ class HandlerTest extends TestCase private Bitrix24AccountRepositoryInterface $repository; private TraceableEventDispatcher $eventDispatcher; - #[Test] - public function testRenewAuthTokenWithoutBitrix24UserId(): void + #[\Override] + protected function setUp(): void { - $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; - $bitrix24Account = new Bitrix24Account( - Uuid::v7(), - 1, - true, - Uuid::v7()->toRfc4122(), - $oldDomainUrl, - Bitrix24AccountStatus::active, - new AuthToken('old_1', 'old_2', 3600), - new CarbonImmutable(), - new CarbonImmutable(), - 1, - new Scope() + $entityManager = EntityManagerFactory::get(); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager); + $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->handler = new Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler( + $this->eventDispatcher, + $this->repository, + $this->flusher, + new NullLogger() ); + } + + #[Test] + #[TestDox('Test change domain url with happy path - one account')] + public function testChangeDomainUrlWithHappyPath(): void + { + $oldDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; + $newDomainUrl = 'new-'.$oldDomainUrl; + + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withDomainUrl($oldDomainUrl) + ->build() + ; $this->repository->save($bitrix24Account); $this->flusher->flush(); - $newDomainUrl = 'new' . $oldDomainUrl; $this->handler->handle( new Bitrix24Accounts\UseCase\ChangeDomainUrl\Command( $oldDomainUrl, @@ -76,21 +83,56 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void $this->assertTrue(in_array( Bitrix24AccountDomainUrlChangedEvent::class, - $this->eventDispatcher->getOrphanedEvents())); + $this->eventDispatcher->getOrphanedEvents() + )); } - #[Override] - protected function setUp(): void + #[Test] + #[TestDox('Test change domain url with happy path - many accounts')] + public function testChangeDomainUrlWithHappyPathForManyAccounts(): void { - $entityManager = EntityManagerFactory::get(); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager); - $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); - $this->handler = new Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler( - $this->eventDispatcher, - $this->repository, - $this->flusher, - new NullLogger() + $oldDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; + $newDomainUrl = 'new-'.$oldDomainUrl; + $b24MemberId = Uuid::v7()->toRfc4122(); + + $bitrix24AccountA = (new Bitrix24AccountBuilder()) + ->withDomainUrl($oldDomainUrl) + ->withMemberId($b24MemberId) + ->build(); + $this->repository->save($bitrix24AccountA); + + $bitrix24AccountB = (new Bitrix24AccountBuilder()) + ->withDomainUrl($oldDomainUrl) + ->withMemberId($b24MemberId) + ->build(); + $this->repository->save($bitrix24AccountB); + + $this->flusher->flush(); + + $this->handler->handle( + new Bitrix24Accounts\UseCase\ChangeDomainUrl\Command( + $oldDomainUrl, + $newDomainUrl + ) ); + + $accounts = $this->repository->findByMemberId($b24MemberId); + foreach ($accounts as $account) { + $this->assertSame( + $account->getDomainUrl(), + $newDomainUrl, + sprintf( + 'domain url «%s» mismatch with expected «%s» for account «%s»', + $account->getDomainUrl(), + $newDomainUrl, + $account->getId()->toRfc4122() + ) + ); + } + + $this->assertTrue(in_array( + Bitrix24AccountDomainUrlChangedEvent::class, + $this->eventDispatcher->getOrphanedEvents() + )); } -} \ No newline at end of file +} diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 246a080..47106c0 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -13,20 +13,18 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\InstallFinish; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationInstalledEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\SDK\Core\Credentials\AuthToken; -use Bitrix24\SDK\Core\Credentials\Scope; -use Carbon\CarbonImmutable; use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; @@ -41,22 +39,15 @@ class HandlerTest extends TestCase private Flusher $flusher; private Bitrix24AccountRepositoryInterface $repository; private TraceableEventDispatcher $eventDispatcher; + #[Test] - public function testRenewAuthTokenWithoutBitrix24UserId(): void + #[TestDox('test finish installation with happy path')] + public function testFinishInstallationWithHappyPath(): void { - $bitrix24Account = new Bitrix24Account( - Uuid::v7(), - 1, - true, - Uuid::v7()->toRfc4122(), - Uuid::v7()->toRfc4122() . '-test.bitrix24.com', - Bitrix24AccountStatus::new, - new AuthToken('old_1', 'old_2', 3600), - new CarbonImmutable(), - new CarbonImmutable(), - 1, - new Scope() - ); + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::new) + ->build(); + $this->repository->save($bitrix24Account); $this->flusher->flush(); @@ -71,11 +62,19 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void ); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertTrue($updated->isApplicationTokenValid($applicationToken)); - - $this->assertTrue(in_array( - Bitrix24AccountDomainUrlChangedEvent::class, - $this->eventDispatcher->getOrphanedEvents())); + $this->assertTrue( + $updated->isApplicationTokenValid($applicationToken), + sprintf('failed application token «%s» validation for bitrix24 account with id «%s»', + $applicationToken, + $bitrix24Account->getId()->toString() + )); + $this->assertTrue( + in_array(Bitrix24AccountApplicationInstalledEvent::class, $this->eventDispatcher->getOrphanedEvents(), true), + sprintf('emited event «%s» for bitrix24 account wiht id «%s» not found', + Bitrix24AccountApplicationInstalledEvent::class, + $bitrix24Account->getId()->toString() + ) + ); } #[Override] From 9890d0aefc07362dd1ff0bedfee03b30a294a8c8 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Thu, 14 Nov 2024 23:34:06 +0300 Subject: [PATCH 056/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20xdebug=20-=20=D0=98=D0=B7=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BF=D0=BE=D0=B4=D1=85=D0=BE=D0=B4=20=D0=BA=20?= =?UTF-8?q?EntityManager=20c=20=D1=84=D0=B0=D0=B1=D1=80=D0=B8=D0=BA=D0=B8?= =?UTF-8?q?=20=D0=BD=D0=B0=20"=D1=81=D0=B8=D0=BD=D0=B3=D0=BB=D1=82=D0=BE?= =?UTF-8?q?=D0=BD"=20-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=B2=20makefile=20=D0=B7=D0=B0=D0=BF=D1=83=D1=81=D0=BA=20?= =?UTF-8?q?=D0=BE=D0=B4=D0=B8=D0=BD=D0=BE=D1=87=D0=BD=D0=BE=D0=B3=D0=BE=20?= =?UTF-8?q?=D1=82=D0=B5=D1=81=D1=82=D0=B0=20=D1=81=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D1=83=D1=81=D0=BA=D0=BE=D0=BC=20xdebug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 10 +++- docker-compose.yaml | 4 ++ docker/php-cli/Dockerfile | 12 ++++- tests/EntityManagerFactory.php | 87 +++++++++++++++++++--------------- 4 files changed, 70 insertions(+), 43 deletions(-) diff --git a/Makefile b/Makefile index 03001c5..0e4c481 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,7 @@ ENV_LOCAL := $(PWD)/.env.local include $(ENV) -include $(ENV_LOCAL) + default: @echo "make needs target:" @egrep -e '^\S+' ./Makefile | grep -v default | sed -r 's/://' | sed -r 's/^/ - /' @@ -96,10 +97,15 @@ test-run-functional: debug-print-env docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:update --dump-sql - docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox + +# Запустить один функциональный тест с дебагером +run-one-functional-test: debug-print-env + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testFindByApplicationToken' tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force schema-create: - docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create \ No newline at end of file + docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create + diff --git a/docker-compose.yaml b/docker-compose.yaml index beb38fc..fb520fb 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -6,6 +6,10 @@ services: - database volumes: - .:/var/www/html + extra_hosts: + - "host.docker.internal:host-gateway" + environment: + PHP_IDE_CONFIG: "serverName=docker-cli" working_dir: /var/www/html database: image: postgres:${POSTGRES_VERSION:-16}-alpine diff --git a/docker/php-cli/Dockerfile b/docker/php-cli/Dockerfile index 256b9c8..a154dfd 100644 --- a/docker/php-cli/Dockerfile +++ b/docker/php-cli/Dockerfile @@ -1,9 +1,17 @@ FROM php:8.3-cli-alpine -RUN apk add unzip libpq-dev git icu-dev \ +RUN apk add unzip libpq-dev git icu-dev autoconf build-base linux-headers \ && docker-php-ext-install bcmath pdo pdo_pgsql intl \ && docker-php-ext-enable bcmath pdo pdo_pgsql intl +RUN pecl install xdebug \ + && docker-php-ext-enable xdebug \ + && echo "xdebug.mode=debug" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \ + && echo "xdebug.client_host = host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \ + && echo "xdebug.client_port = 9003" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini + +RUN git config --global --add safe.directory /var/www/html + RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/bin --filename=composer --quiet -ENV COMPOSER_ALLOW_SUPERUSER 1 +ENV COMPOSER_ALLOW_SUPERUSER=1 diff --git a/tests/EntityManagerFactory.php b/tests/EntityManagerFactory.php index 2475265..783cae0 100644 --- a/tests/EntityManagerFactory.php +++ b/tests/EntityManagerFactory.php @@ -11,13 +11,14 @@ use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Exception\ORMException; use Doctrine\ORM\OptimisticLockException; +use Monolog\Logger; use Symfony\Bridge\Doctrine\Types\UuidType; use Doctrine\DBAL\DriverManager; use Doctrine\ORM\EntityManager; use Doctrine\ORM\ORMSetup; use Doctrine\DBAL\Types\Type; - - +use Monolog\Handler\StreamHandler; +use Monolog\Level; class EntityManagerFactory { /** @@ -26,54 +27,62 @@ class EntityManagerFactory * @throws ORMException * @throws Exception */ + + private static ?EntityManager $entityManager = null; + public static function get(): EntityManagerInterface { /* $paths = [ dirname(__DIR__) . '/src/Bitrix24Accounts/Entity' ];*/ - $paths = [ - dirname(__DIR__) . '/config/xml' - ]; - $isDevMode = true; - if (!array_key_exists('DATABASE_HOST', $_ENV)) { - throw new WrongConfigurationException('DATABASE_HOST not defined in $_ENV'); - } + if (self::$entityManager === null) { + $paths = [ + dirname(__DIR__) . '/config/xml' + ]; + $isDevMode = true; - if (!array_key_exists('DATABASE_USER', $_ENV)) { - throw new WrongConfigurationException('DATABASE_USER not defined in $_ENV'); - } + if (!array_key_exists('DATABASE_HOST', $_ENV)) { + throw new WrongConfigurationException('DATABASE_HOST not defined in $_ENV'); + } - if (!array_key_exists('DATABASE_PASSWORD', $_ENV)) { - throw new WrongConfigurationException('DATABASE_PASSWORD not defined in $_ENV'); - } + if (!array_key_exists('DATABASE_USER', $_ENV)) { + throw new WrongConfigurationException('DATABASE_USER not defined in $_ENV'); + } - if (!array_key_exists('DATABASE_NAME', $_ENV)) { - throw new WrongConfigurationException('DATABASE_NAME not defined in $_ENV'); - } + if (!array_key_exists('DATABASE_PASSWORD', $_ENV)) { + throw new WrongConfigurationException('DATABASE_PASSWORD not defined in $_ENV'); + } - $connectionParams = [ - 'driver' => 'pdo_pgsql', - 'host' => $_ENV['DATABASE_HOST'], - 'user' => $_ENV['DATABASE_USER'], - 'password' => $_ENV['DATABASE_PASSWORD'], - 'dbname' => $_ENV['DATABASE_NAME'], - ]; - if (!Type::hasType(UuidType::NAME)) { - Type::addType(UuidType::NAME, UuidType::class); - } + if (!array_key_exists('DATABASE_NAME', $_ENV)) { + throw new WrongConfigurationException('DATABASE_NAME not defined in $_ENV'); + } - if (!Type::hasType('carbon_immutable')) { - Type::addType('carbon_immutable', CarbonImmutableType::class); - } + $connectionParams = [ + 'driver' => 'pdo_pgsql', + 'host' => $_ENV['DATABASE_HOST'], + 'user' => $_ENV['DATABASE_USER'], + 'password' => $_ENV['DATABASE_PASSWORD'], + 'dbname' => $_ENV['DATABASE_NAME'], + ]; + + if (!Type::hasType(UuidType::NAME)) { + Type::addType(UuidType::NAME, UuidType::class); + } - // $configuration = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode); - $configuration = ORMSetup::createXMLMetadataConfiguration($paths, $isDevMode); - $connection = DriverManager::getConnection($connectionParams, $configuration); - $entityManager = new EntityManager($connection, $configuration); - // todo разобраться, почему так, без этого объекты оставались в кеше и при find мы получали старые значения - $entityManager->clear(); - $entityManager->flush(); - return $entityManager; + if (!Type::hasType('carbon_immutable')) { + Type::addType('carbon_immutable', CarbonImmutableType::class); + } + + // $configuration = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode); + $configuration = ORMSetup::createXMLMetadataConfiguration($paths, $isDevMode); + // $log = new Logger('name'); + // $log->pushHandler(new StreamHandler('log.txt', Level::Debug)); + + // $configuration->setMiddlewares([new \Doctrine\DBAL\Logging\Middleware($log)]); + $connection = DriverManager::getConnection($connectionParams, $configuration); + self::$entityManager = new EntityManager($connection, $configuration); + } + return self::$entityManager; } } \ No newline at end of file From 969782e5438c13e67161d73f7d58905e5f8d2c7a Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 17 Nov 2024 02:09:10 +0600 Subject: [PATCH 057/130] Refactor repository methods and improve exception handling Formatted the Bitrix24AccountRepository methods for readability and added null checks for better error handling. Introduced additional validation for application tokens and domain URLs to prevent empty string errors. Signed-off-by: mesilov --- .../Doctrine/Bitrix24AccountRepository.php | 45 ++++++++++++++----- 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index daaad13..f695276 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -36,7 +36,9 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface // exit(); $res = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); if (null === $res) { - throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); + throw new Bitrix24AccountNotFoundException( + sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122()) + ); } return $res; @@ -54,8 +56,12 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void * @throws InvalidArgumentException */ #[Override] - public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?int $bitrix24UserId = null, ?bool $isAdmin = null): array - { + public function findByMemberId( + string $memberId, + ?Bitrix24AccountStatus $bitrix24AccountStatus = null, + ?int $bitrix24UserId = null, + ?bool $isAdmin = null + ): array { if ('' === trim($memberId)) { throw new InvalidArgumentException('memberId cannot be empty'); } @@ -66,6 +72,9 @@ public function findByMemberId(string $memberId, ?Bitrix24AccountStatus $bitrix2 if ($bitrix24AccountStatus instanceof Bitrix24AccountStatus) { $criteria['status'] = $bitrix24AccountStatus->name; } + if (null !== $bitrix24UserId) { + $criteria['bitrix24UserId'] = $bitrix24UserId; + } if (null !== $isAdmin) { $criteria['isBitrix24UserAdmin'] = $isAdmin; @@ -80,14 +89,18 @@ public function delete(Uuid $uuid): void $bitrix24Account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); if (null === $bitrix24Account) { - throw new Bitrix24AccountNotFoundException(sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122())); + throw new Bitrix24AccountNotFoundException( + sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122()) + ); } if (Bitrix24AccountStatus::deleted !== $bitrix24Account->getStatus()) { - throw new InvalidArgumentException(sprintf( - 'you cannot delete bitrix24account «%s», they must be in status «deleted», current status «%s»', - $bitrix24Account->getId()->toRfc4122(), - $bitrix24Account->getStatus()->name - )); + throw new InvalidArgumentException( + sprintf( + 'you cannot delete bitrix24account «%s», they must be in status «deleted», current status «%s»', + $bitrix24Account->getId()->toRfc4122(), + $bitrix24Account->getStatus()->name + ) + ); } $this->getEntityManager()->remove($bitrix24Account); @@ -106,9 +119,14 @@ public function findAllActive(): array * @param non-empty-string $applicationToken * * @phpstan-return array + * @throws InvalidArgumentException */ public function findByApplicationToken(string $applicationToken): array { + if ($applicationToken === '') { + throw new InvalidArgumentException('application token cannot be an empty string'); + } + return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findBy( [ 'applicationToken' => $applicationToken, @@ -132,7 +150,7 @@ public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterf [ 'memberId' => $memberId, 'isBitrix24UserAdmin' => true, - 'status' => Bitrix24AccountStatus::active, + 'status' => [Bitrix24AccountStatus::active, Bitrix24AccountStatus::new], ] ); } @@ -145,8 +163,11 @@ public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterf * @throws InvalidArgumentException */ #[Override] - public function findByDomain(string $domainUrl, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?bool $isAdmin = null): array - { + public function findByDomain( + string $domainUrl, + ?Bitrix24AccountStatus $bitrix24AccountStatus = null, + ?bool $isAdmin = null + ): array { if ('' === trim($domainUrl)) { throw new InvalidArgumentException('domainUrl cannot be an empty string'); } From 21d34d3ce9a476a81e0113bb4ad4a0a72e0c741c Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 17 Nov 2024 02:48:04 +0600 Subject: [PATCH 058/130] Refactor exception formatting for readability Reformat exception messages to use multi-line structure for better readability. This change affects the methods: applicationInstalled, uninstallApplication, and updateApplicationVersion. Additionally, updated Bitrix24AccountBlockedEvent instantiation to include a comment attribute. Signed-off-by: mesilov --- .../Entity/Bitrix24Account.php | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 135d1e7..bc457e0 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -189,10 +189,12 @@ public function changeDomainUrl(string $newDomainUrl): void public function applicationInstalled(string $applicationToken): void { if (Bitrix24AccountStatus::new !== $this->status) { - throw new InvalidArgumentException(sprintf( - 'for finish installation bitrix24 account must be in status «new», current status - «%s»', - $this->status->name - )); + throw new InvalidArgumentException( + sprintf( + 'for finish installation bitrix24 account must be in status «new», current status - «%s»', + $this->status->name + ) + ); } if ('' === $applicationToken) { @@ -219,10 +221,12 @@ public function applicationUninstalled(string $applicationToken): void } if (Bitrix24AccountStatus::active !== $this->status) { - throw new InvalidArgumentException(sprintf( - 'for uninstall account must be in status «active», current status - «%s»', - $this->status->name - )); + throw new InvalidArgumentException( + sprintf( + 'for uninstall account must be in status «active», current status - «%s»', + $this->status->name + ) + ); } if ($this->applicationToken !== $applicationToken) { @@ -270,7 +274,9 @@ public function getUpdatedAt(): CarbonImmutable public function updateApplicationVersion(int $version, ?Scope $newScope): void { if (Bitrix24AccountStatus::active !== $this->status) { - throw new InvalidArgumentException(sprintf('account must be in status «active», but now account in status «%s»', $this->status->name)); + throw new InvalidArgumentException( + sprintf('account must be in status «active», but now account in status «%s»', $this->status->name) + ); } if ($this->applicationVersion >= $version) { @@ -330,7 +336,8 @@ public function markAsBlocked(?string $comment): void $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountBlockedEvent( $this->id, - new CarbonImmutable() + new CarbonImmutable(), + $this->comment ); } From 469e5639505301907a662841704e5278da75a450 Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 17 Nov 2024 02:57:32 +0600 Subject: [PATCH 059/130] Refactor event dispatching mechanism Revised the event dispatching mechanism to handle emitted events directly from Bitrix24Account entity. Also streamlined constructor formatting and updated doc annotations for consistency. Signed-off-by: mesilov --- .../Entity/Bitrix24Account.php | 49 ++++++++++--------- .../UseCase/InstallStart/Handler.php | 47 +++++++++--------- 2 files changed, 49 insertions(+), 47 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index bc457e0..af1862b 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -18,6 +18,7 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationUninstalledEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationVersionUpdatedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountBlockedEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountCreatedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; @@ -26,7 +27,6 @@ use Bitrix24\SDK\Core\Exceptions\UnknownScopeCodeException; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; use Carbon\CarbonImmutable; -use Override; use Symfony\Component\Uid\Uuid; use Symfony\Contracts\EventDispatcher\Event; @@ -70,45 +70,50 @@ public function __construct( $this->refreshToken = $authToken->refreshToken; $this->expires = $authToken->expires; $this->applicationScope = $applicationScope->getScopeCodes(); + + $this->events[] = new Bitrix24AccountCreatedEvent( + $this->id, + $this->createdAt + ); } - #[Override] + #[\Override] public function getId(): Uuid { return $this->id; } - #[Override] + #[\Override] public function getBitrix24UserId(): int { return $this->bitrix24UserId; } - #[Override] + #[\Override] public function isBitrix24UserAdmin(): bool { return $this->isBitrix24UserAdmin; } - #[Override] + #[\Override] public function getMemberId(): string { return $this->memberId; } - #[Override] + #[\Override] public function getDomainUrl(): string { return $this->domainUrl; } - #[Override] + #[\Override] public function getStatus(): Bitrix24AccountStatus { return $this->status; } - #[Override] + #[\Override] public function getAuthToken(): AuthToken { return new AuthToken($this->accessToken, $this->refreshToken, $this->expires); @@ -117,7 +122,7 @@ public function getAuthToken(): AuthToken /** * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function renewAuthToken(RenewedAuthToken $renewedAuthToken): void { if ($this->memberId !== $renewedAuthToken->memberId) { @@ -138,7 +143,7 @@ public function renewAuthToken(RenewedAuthToken $renewedAuthToken): void $this->updatedAt = new CarbonImmutable(); } - #[Override] + #[\Override] public function getApplicationVersion(): int { return $this->applicationVersion; @@ -147,7 +152,7 @@ public function getApplicationVersion(): int /** * @throws UnknownScopeCodeException */ - #[Override] + #[\Override] public function getApplicationScope(): Scope { return new Scope($this->applicationScope); @@ -156,7 +161,7 @@ public function getApplicationScope(): Scope /** * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function changeDomainUrl(string $newDomainUrl): void { if ('' === $newDomainUrl) { @@ -185,7 +190,7 @@ public function changeDomainUrl(string $newDomainUrl): void /** * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function applicationInstalled(string $applicationToken): void { if (Bitrix24AccountStatus::new !== $this->status) { @@ -213,7 +218,7 @@ public function applicationInstalled(string $applicationToken): void /** * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function applicationUninstalled(string $applicationToken): void { if ('' === $applicationToken) { @@ -249,19 +254,19 @@ public function applicationUninstalled(string $applicationToken): void ); } - #[Override] + #[\Override] public function isApplicationTokenValid(string $applicationToken): bool { return $this->applicationToken === $applicationToken; } - #[Override] + #[\Override] public function getCreatedAt(): CarbonImmutable { return $this->createdAt; } - #[Override] + #[\Override] public function getUpdatedAt(): CarbonImmutable { return $this->updatedAt; @@ -270,7 +275,7 @@ public function getUpdatedAt(): CarbonImmutable /** * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function updateApplicationVersion(int $version, ?Scope $newScope): void { if (Bitrix24AccountStatus::active !== $this->status) { @@ -304,7 +309,7 @@ public function updateApplicationVersion(int $version, ?Scope $newScope): void /** * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function markAsActive(?string $comment): void { if (Bitrix24AccountStatus::blocked !== $this->status) { @@ -324,7 +329,7 @@ public function markAsActive(?string $comment): void /** * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function markAsBlocked(?string $comment): void { if (Bitrix24AccountStatus::deleted === $this->status) { @@ -341,7 +346,7 @@ public function markAsBlocked(?string $comment): void ); } - #[Override] + #[\Override] public function getComment(): ?string { return $this->comment; @@ -350,7 +355,7 @@ public function getComment(): ?string /** * @return Event[] */ - #[Override] + #[\Override] public function emitEvents(): array { $events = $this->events; diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index 50c5262..5c1270d 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -16,12 +16,11 @@ readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, + private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) - { + private Flusher $flusher, + private LoggerInterface $logger + ) { } public function handle(Command $command): void @@ -32,28 +31,26 @@ public function handle(Command $command): void 'member_id' => $command->memberId ]); - $this->bitrix24AccountRepository->save( - new Bitrix24Account( - $command->uuid, - $command->bitrix24UserId, - $command->isBitrix24UserAdmin, - $command->memberId, - $command->domainUrl, - Bitrix24AccountStatus::new, - $command->authToken, - new CarbonImmutable(), - new CarbonImmutable(), - $command->applicationVersion, - $command->applicationScope - ) + $newAccount = new Bitrix24Account( + $command->uuid, + $command->bitrix24UserId, + $command->isBitrix24UserAdmin, + $command->memberId, + $command->domainUrl, + Bitrix24AccountStatus::new, + $command->authToken, + new CarbonImmutable(), + new CarbonImmutable(), + $command->applicationVersion, + $command->applicationScope ); + $this->bitrix24AccountRepository->save($newAccount); $this->flusher->flush(); - $this->eventDispatcher->dispatch( - new Bitrix24AccountCreatedEvent( - $command->uuid, - new CarbonImmutable() - ) - ); + + foreach ($newAccount->emitEvents() as $event) { + $this->eventDispatcher->dispatch($event); + } + $this->logger->debug('Bitrix24Accounts.InstallStart.Finish'); } } \ No newline at end of file From 57153aea1aae9160af7ee391eb5f3a1815382d04 Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 17 Nov 2024 03:23:38 +0600 Subject: [PATCH 060/130] Refactor `Handler.php` files for code clarity and maintainability Adjusted import statements, formatted constructor and exception handling, and added PHPDoc comments for improved readability and maintenance. These changes enhance code consistency and readability across the `Uninstall`, `InstallStart`, and `InstallFinish` handlers. Signed-off-by: mesilov --- .../UseCase/InstallFinish/Handler.php | 31 ++++++++++++------- .../UseCase/InstallStart/Handler.php | 10 +++--- .../UseCase/Uninstall/Handler.php | 18 +++++------ 3 files changed, 33 insertions(+), 26 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index f53e467..fe22b80 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -11,6 +11,7 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\MultipleBitrix24AccountsFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; +use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Psr\Log\LoggerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -25,6 +26,8 @@ public function __construct( /** * @throws Bitrix24AccountNotFoundException + * @throws MultipleBitrix24AccountsFoundException + * @throws InvalidArgumentException */ public function handle(Command $command): void { @@ -41,23 +44,29 @@ public function handle(Command $command): void $command->bitrix24UserId ); if ([] === $accounts) { - throw new Bitrix24AccountNotFoundException(sprintf( - 'bitrix24 account for domain %s with member id %s in status «new» not found', - $command->domainUrl, - $command->memberId - )); + throw new Bitrix24AccountNotFoundException( + sprintf( + 'bitrix24 account for domain %s with member id %s in status «new» not found', + $command->domainUrl, + $command->memberId + ) + ); } if (count($accounts) > 1) { - throw new MultipleBitrix24AccountsFoundException(sprintf( - 'multiple bitrix24 accounts for domain %s with member id %s in status «new» found', - $command->domainUrl, - $command->memberId - )); + throw new MultipleBitrix24AccountsFoundException( + sprintf( + 'multiple bitrix24 accounts for domain %s with member id %s in status «new» found', + $command->domainUrl, + $command->memberId + ) + ); } + /** + * @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $targetAccount + */ $targetAccount = $accounts[0]; - // @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount $targetAccount->applicationInstalled($command->applicationToken); $this->bitrix24AccountRepository->save($targetAccount); diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index 5c1270d..f807d4c 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -4,11 +4,10 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallStart; +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountCreatedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Carbon\CarbonImmutable; use Psr\Log\LoggerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -20,15 +19,14 @@ public function __construct( private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, private Flusher $flusher, private LoggerInterface $logger - ) { - } + ) {} public function handle(Command $command): void { $this->logger->debug('Bitrix24Accounts.InstallStart.start', [ 'id' => $command->uuid->toRfc4122(), 'domain_url' => $command->domainUrl, - 'member_id' => $command->memberId + 'member_id' => $command->memberId, ]); $newAccount = new Bitrix24Account( @@ -53,4 +51,4 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.InstallStart.Finish'); } -} \ No newline at end of file +} diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 60b4282..407a7d1 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -6,25 +6,21 @@ use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; -use Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall\Command; use Psr\Log\LoggerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, + private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) - { - } + private Flusher $flusher, + private LoggerInterface $logger + ) {} /** * @throws Bitrix24AccountNotFoundException @@ -35,6 +31,10 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.Uninstall.start', [ 'b24_application_token' => $command->applicationToken, ]); + + /** + * @var AggregateRootEventsEmitterInterface[]|Bitrix24AccountInterface[] $accounts + */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); foreach ($accounts as $account) { @@ -48,4 +48,4 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.Uninstall.Finish'); } -} \ No newline at end of file +} From 9ad05814e253bbcb93a04ed18fd81e89fa8cee8a Mon Sep 17 00:00:00 2001 From: mesilov Date: Sun, 17 Nov 2024 11:17:00 +0600 Subject: [PATCH 061/130] Refactor event dispatching mechanism Revised the event dispatching mechanism to handle emitted events directly from the Bitrix24Account entity. Streamlined constructor formatting and updated doc annotations for consistency. Signed-off-by: mesilov --- .../Entity/Bitrix24Account.php | 17 +++-- .../UseCase/InstallStart/Handler.php | 3 +- .../UseCase/InstallStart/HandlerTest.php | 54 +++++++-------- .../UseCase/RenewAuthToken/HandlerTest.php | 69 ++++++++----------- 4 files changed, 71 insertions(+), 72 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index af1862b..fc9e417 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -64,6 +64,7 @@ public function __construct( private CarbonImmutable $updatedAt, private int $applicationVersion, Scope $applicationScope, + bool $isEmitBitrix24AccountCreatedEvent = false ) { $this->authToken = $authToken; $this->accessToken = $authToken->accessToken; @@ -71,10 +72,12 @@ public function __construct( $this->expires = $authToken->expires; $this->applicationScope = $applicationScope->getScopeCodes(); - $this->events[] = new Bitrix24AccountCreatedEvent( - $this->id, - $this->createdAt - ); + if ($isEmitBitrix24AccountCreatedEvent) { + $this->events[] = new Bitrix24AccountCreatedEvent( + $this->id, + $this->createdAt + ); + } } #[\Override] @@ -113,10 +116,14 @@ public function getStatus(): Bitrix24AccountStatus return $this->status; } + /** + * @throws InvalidArgumentException + */ #[\Override] public function getAuthToken(): AuthToken { - return new AuthToken($this->accessToken, $this->refreshToken, $this->expires); + $this->authToken = new AuthToken($this->accessToken, $this->refreshToken, $this->expires); + return $this->authToken; } /** diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index f807d4c..722352d 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -40,7 +40,8 @@ public function handle(Command $command): void new CarbonImmutable(), new CarbonImmutable(), $command->applicationVersion, - $command->applicationScope + $command->applicationScope, + true ); $this->bitrix24AccountRepository->save($newAccount); $this->flusher->flush(); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 315b4dd..1ca6599 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -13,24 +13,17 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\InstallStart; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; +use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; -use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; -use Bitrix24\SDK\Application\ApplicationStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountCreatedEvent; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountDomainUrlChangedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Bitrix24\SDK\Core\Exceptions\UnknownScopeCodeException; -use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; -use Carbon\CarbonImmutable; -use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -41,6 +34,9 @@ use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; +/** + * @internal + */ #[CoversClass(Bitrix24Accounts\UseCase\InstallStart\Handler::class)] class HandlerTest extends TestCase { @@ -49,6 +45,21 @@ class HandlerTest extends TestCase private Bitrix24AccountRepositoryInterface $repository; private TraceableEventDispatcher $eventDispatcher; + #[\Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager); + $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->handler = new Bitrix24Accounts\UseCase\InstallStart\Handler( + $this->eventDispatcher, + $this->repository, + $this->flusher, + new NullLogger() + ); + } + /** * @throws InvalidArgumentException * @throws Bitrix24AccountNotFoundException @@ -62,7 +73,7 @@ public function testInstallStartHappyPath(): void $b24UserId = random_int(1, 100_000); $isB24UserAdmin = true; $b24MemberId = Uuid::v7()->toRfc4122(); - $b24DomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $b24DomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; $authToken = new AuthToken('old_1', 'old_2', 3600); $appVersion = 1; $scope = new Scope(['crm']); @@ -88,24 +99,13 @@ public function testInstallStartHappyPath(): void $this->assertEquals($appVersion, $account->getApplicationVersion()); $this->assertEquals($scope, $account->getApplicationScope()); - - $this->assertTrue(in_array( + $this->assertContains( Bitrix24AccountCreatedEvent::class, - $this->eventDispatcher->getOrphanedEvents())); - } - - #[Override] - protected function setUp(): void - { - $entityManager = EntityManagerFactory::get(); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager); - $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); - $this->handler = new Bitrix24Accounts\UseCase\InstallStart\Handler( - $this->eventDispatcher, - $this->repository, - $this->flusher, - new NullLogger() + $this->eventDispatcher->getOrphanedEvents(), + sprintf( + 'not found expected domain event «%s»', + Bitrix24AccountCreatedEvent::class + ) ); } -} \ No newline at end of file +} diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 6ea1f6e..9d9854c 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -13,20 +13,16 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\RenewAuthToken; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Command; use Bitrix24\Lib\Bitrix24Accounts\UseCase\RenewAuthToken\Handler; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\ApplicationStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; -use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; -use Carbon\CarbonImmutable; -use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -34,8 +30,10 @@ use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; -use Symfony\Component\Uid\Uuid; +/** + * @internal + */ #[CoversClass(Handler::class)] class HandlerTest extends TestCase { @@ -44,25 +42,28 @@ class HandlerTest extends TestCase private Bitrix24AccountRepositoryInterface $repository; private TraceableEventDispatcher $eventDispatcher; - #[Test] - public function testRenewAuthTokenWithoutBitrix24UserId(): void + #[\Override] + protected function setUp(): void { - $bitrix24Account = new Bitrix24Account( - Uuid::v7(), - 1, - true, - Uuid::v7()->toRfc4122(), - Uuid::v7()->toRfc4122() . '-test.bitrix24.com', - Bitrix24AccountStatus::active, - new AuthToken('old_1', 'old_2', 3600), - new CarbonImmutable(), - new CarbonImmutable(), - 1, - new Scope() + $entityManager = EntityManagerFactory::get(); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager); + $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->handler = new Handler( + $this->eventDispatcher, + $this->repository, + $this->flusher, + new NullLogger() ); + } + #[Test] + public function testRenewAuthTokenWithoutBitrix24UserId(): void + { + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->build() + ; $this->repository->save($bitrix24Account); - $this->flusher->flush(); $newAuthToken = new AuthToken('new_1', 'new_2', 3600); @@ -78,28 +79,18 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void ) ) ); - $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertEquals($newAuthToken->accessToken, $updated->getAuthToken()->accessToken); $this->assertEquals($newAuthToken->refreshToken, $updated->getAuthToken()->refreshToken); // на продлении токенов событий не бросаем - $this->assertCount(0, $this->eventDispatcher->getOrphanedEvents()); - } - - - #[Override] - protected function setUp(): void - { - $entityManager = EntityManagerFactory::get(); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager); - $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); - $this->handler = new Handler( - $this->eventDispatcher, - $this->repository, - $this->flusher, - new NullLogger() + $this->assertCount( + 0, + $this->eventDispatcher->getOrphanedEvents(), + sprintf( + 'get unexpected domain events count %s', + count($this->eventDispatcher->getOrphanedEvents()), + ) ); } -} \ No newline at end of file +} From 22b58ab9ce76d57a870e22c34d068fb0e1d76b29 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Wed, 20 Nov 2024 23:11:20 +0300 Subject: [PATCH 062/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=8F=D0=BB=20=D0=BF=D0=BE=D0=B4=D1=85=D0=BE=D0=B4=20=D0=BA=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D1=83=D1=87=D0=B5=D0=BD=D0=B8=D1=8E=20authTo?= =?UTF-8?q?ken=20-=20=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=80=D0=B8=D0=B8=20-=20=D0=A3?= =?UTF-8?q?=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BE=D0=B4=D0=BD=D1=83=20=D0=B8?= =?UTF-8?q?=D0=B7=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BE=D0=BA=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=20=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B8=20=D1=82=D0=BE=D0=BA=D0=B5=D0=BD=D0=B0=20-?= =?UTF-8?q?=20=D0=A3=D0=B4=D0=B0=D0=BB=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=D1=83=D1=8E=20=D1=81=D1=83=D1=89=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D1=8C=20User=20-=20=D0=92=20cli-config.php=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=BC=D0=B5=D0=BD=D0=B8=D0=BB=20=D1=85=D0=B0=D1=80?= =?UTF-8?q?=D0=B4=D0=BA=D0=BE=D0=B4=20=D0=BD=D0=B0=20=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D1=83=D1=8E=20=D0=BE=D0=BA=D1=80?= =?UTF-8?q?=D1=83=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 3 +- Makefile | 2 +- config/cli-config.php | 2 +- ...b.Bitrix24Accounts.Entity.TestUser.dcm.xml | 12 ----- .../Entity/Bitrix24Account.php | 38 ++++++++-------- src/Bitrix24Accounts/Entity/TestUser.php | 44 ------------------- .../Doctrine/Bitrix24AccountRepository.php | 9 ++-- tests/EntityManagerFactory.php | 8 ---- .../UseCase/RenewAuthToken/HandlerTest.php | 10 ----- 9 files changed, 27 insertions(+), 101 deletions(-) delete mode 100644 config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml delete mode 100644 src/Bitrix24Accounts/Entity/TestUser.php diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 47e1a0d..244ba73 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -68,8 +68,9 @@ jobs: - name: "Run functional tests" run: | php bin/doctrine orm:schema-tool:drop --force - php bin/doctrine orm:schema-tool:create + php bin/doctrine orm:schema-tool:create --dump-sql php bin/doctrine orm:schema-tool:update --dump-sql + php bin/doctrine orm:info php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox - name: "is functional tests succeeded" diff --git a/Makefile b/Makefile index 0e4c481..c71ff1d 100644 --- a/Makefile +++ b/Makefile @@ -101,7 +101,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testFindByApplicationToken' tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testRenewAuthTokenWithoutBitrix24UserId' tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/config/cli-config.php b/config/cli-config.php index 18e2c02..28ff2dc 100644 --- a/config/cli-config.php +++ b/config/cli-config.php @@ -13,7 +13,7 @@ [ 'driver' => 'pdo_pgsql', 'memory' => true, - 'dbname' => 'b24phpLibTest', + 'dbname' => $_ENV['DATABASE_NAME'], ]); return DependencyFactory::fromConnection($config, new ExistingConnection($conn)); \ No newline at end of file diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml deleted file mode 100644 index 2d30540..0000000 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.TestUser.dcm.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index fc9e417..580d719 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -32,12 +32,6 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEmitterInterface { - private string $accessToken; - - private string $refreshToken; - - private int $expires; - private array $applicationScope; private ?string $applicationToken = null; @@ -67,17 +61,8 @@ public function __construct( bool $isEmitBitrix24AccountCreatedEvent = false ) { $this->authToken = $authToken; - $this->accessToken = $authToken->accessToken; - $this->refreshToken = $authToken->refreshToken; - $this->expires = $authToken->expires; $this->applicationScope = $applicationScope->getScopeCodes(); - - if ($isEmitBitrix24AccountCreatedEvent) { - $this->events[] = new Bitrix24AccountCreatedEvent( - $this->id, - $this->createdAt - ); - } + $this->addAccountCreatedEventIfNeeded($isEmitBitrix24AccountCreatedEvent); } #[\Override] @@ -122,7 +107,6 @@ public function getStatus(): Bitrix24AccountStatus #[\Override] public function getAuthToken(): AuthToken { - $this->authToken = new AuthToken($this->accessToken, $this->refreshToken, $this->expires); return $this->authToken; } @@ -144,9 +128,12 @@ public function renewAuthToken(RenewedAuthToken $renewedAuthToken): void ); } - $this->accessToken = $renewedAuthToken->authToken->accessToken; - $this->refreshToken = $renewedAuthToken->authToken->refreshToken; - $this->expires = $renewedAuthToken->authToken->expires; + $this->authToken = new AuthToken( + $renewedAuthToken->authToken->accessToken, + $renewedAuthToken->authToken->refreshToken, + $renewedAuthToken->authToken->expires + ); + $this->updatedAt = new CarbonImmutable(); } @@ -370,4 +357,15 @@ public function emitEvents(): array return $events; } + + public function addAccountCreatedEventIfNeeded(bool $isEmitCreatedEvent): void + { + if ($isEmitCreatedEvent) { + // Создание события и добавление его в массив событий + $this->events[] = new Bitrix24AccountCreatedEvent( + $this->id, + $this->createdAt + ); + } + } } diff --git a/src/Bitrix24Accounts/Entity/TestUser.php b/src/Bitrix24Accounts/Entity/TestUser.php deleted file mode 100644 index 216d1f2..0000000 --- a/src/Bitrix24Accounts/Entity/TestUser.php +++ /dev/null @@ -1,44 +0,0 @@ -login; - } - - public function setLogin(string $login): void - { - $this->login = $login; - } - - public function getPassword(): string - { - return $this->password; - } - - public function setPassword(string $password): void - { - $this->password = $password; - } - - public function getId(): int - { - return $this->id; - } - - public function setId(int $id): void - { - $this->id = $id; - } - -} \ No newline at end of file diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index f695276..9cb26d9 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -32,8 +32,6 @@ public function __construct( #[Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { - // print_r($uuid); - // exit(); $res = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); if (null === $res) { throw new Bitrix24AccountNotFoundException( @@ -106,12 +104,15 @@ public function delete(Uuid $uuid): void $this->getEntityManager()->remove($bitrix24Account); } - public function findAllActive(): array + public function findAllActive(int|null $limit = null, int|null $offset = null): array { return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findBy( [ 'status' => Bitrix24AccountStatus::active, - ] + ], + null, + $limit, + $offset ); } diff --git a/tests/EntityManagerFactory.php b/tests/EntityManagerFactory.php index 783cae0..2127162 100644 --- a/tests/EntityManagerFactory.php +++ b/tests/EntityManagerFactory.php @@ -32,10 +32,6 @@ class EntityManagerFactory public static function get(): EntityManagerInterface { - /* $paths = [ - dirname(__DIR__) . '/src/Bitrix24Accounts/Entity' - ];*/ - if (self::$entityManager === null) { $paths = [ dirname(__DIR__) . '/config/xml' @@ -74,12 +70,8 @@ public static function get(): EntityManagerInterface Type::addType('carbon_immutable', CarbonImmutableType::class); } - // $configuration = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode); $configuration = ORMSetup::createXMLMetadataConfiguration($paths, $isDevMode); - // $log = new Logger('name'); - // $log->pushHandler(new StreamHandler('log.txt', Level::Debug)); - // $configuration->setMiddlewares([new \Doctrine\DBAL\Logging\Middleware($log)]); $connection = DriverManager::getConnection($connectionParams, $configuration); self::$entityManager = new EntityManager($connection, $configuration); } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 9d9854c..817ceb7 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -82,15 +82,5 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertEquals($newAuthToken->accessToken, $updated->getAuthToken()->accessToken); $this->assertEquals($newAuthToken->refreshToken, $updated->getAuthToken()->refreshToken); - - // на продлении токенов событий не бросаем - $this->assertCount( - 0, - $this->eventDispatcher->getOrphanedEvents(), - sprintf( - 'get unexpected domain events count %s', - count($this->eventDispatcher->getOrphanedEvents()), - ) - ); } } From 959aaaad97d52acd6d26345d818f8bb6ee43fbd3 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Thu, 21 Nov 2024 00:09:48 +0300 Subject: [PATCH 063/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BE=D0=BA=20=D0=B2=20=D1=82=D0=B5=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/ChangeDomainUrl/HandlerTest.php | 37 +++++++--- .../UseCase/InstallStart/HandlerTest.php | 68 +++++++++++++++++-- .../UseCase/RenewAuthToken/HandlerTest.php | 21 +++++- .../UseCase/Uninstall/HandlerTest.php | 14 +++- 4 files changed, 119 insertions(+), 21 deletions(-) diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index 16e5dd2..9448734 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -61,13 +61,12 @@ protected function setUp(): void #[TestDox('Test change domain url with happy path - one account')] public function testChangeDomainUrlWithHappyPath(): void { - $oldDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; - $newDomainUrl = 'new-'.$oldDomainUrl; + $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $newDomainUrl = 'new-' . $oldDomainUrl; $bitrix24Account = (new Bitrix24AccountBuilder()) ->withDomainUrl($oldDomainUrl) - ->build() - ; + ->build(); $this->repository->save($bitrix24Account); $this->flusher->flush(); @@ -79,20 +78,33 @@ public function testChangeDomainUrlWithHappyPath(): void ); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertEquals($newDomainUrl, $updated->getDomainUrl()); + $this->assertEquals( + $newDomainUrl, + $updated->getDomainUrl(), + sprintf( + 'New domain url %s must be equals domain url %s after update', + $newDomainUrl, + $updated->getDomainUrl() + ) + ); $this->assertTrue(in_array( Bitrix24AccountDomainUrlChangedEvent::class, - $this->eventDispatcher->getOrphanedEvents() - )); + $this->eventDispatcher->getOrphanedEvents(), + ), + sprintf( + 'Event %s was expected to be in the list of orphan events, but it is missing', + Bitrix24AccountDomainUrlChangedEvent::class + ) + ); } #[Test] #[TestDox('Test change domain url with happy path - many accounts')] public function testChangeDomainUrlWithHappyPathForManyAccounts(): void { - $oldDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; - $newDomainUrl = 'new-'.$oldDomainUrl; + $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $newDomainUrl = 'new-' . $oldDomainUrl; $b24MemberId = Uuid::v7()->toRfc4122(); $bitrix24AccountA = (new Bitrix24AccountBuilder()) @@ -133,6 +145,11 @@ public function testChangeDomainUrlWithHappyPathForManyAccounts(): void $this->assertTrue(in_array( Bitrix24AccountDomainUrlChangedEvent::class, $this->eventDispatcher->getOrphanedEvents() - )); + ), + sprintf( + 'Event %s was expected to be in the list of orphan events, but it is missing', + Bitrix24AccountDomainUrlChangedEvent::class + ) + ); } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 1ca6599..5461746 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -91,13 +91,67 @@ public function testInstallStartHappyPath(): void ); $account = $this->repository->getById($accountId); - $this->assertEquals($b24UserId, $account->getBitrix24UserId()); - $this->assertEquals($isB24UserAdmin, $account->isBitrix24UserAdmin()); - $this->assertEquals($b24MemberId, $account->getMemberId()); - $this->assertEquals($b24DomainUrl, $account->getDomainUrl()); - $this->assertEquals($authToken, $account->getAuthToken()); - $this->assertEquals($appVersion, $account->getApplicationVersion()); - $this->assertEquals($scope, $account->getApplicationScope()); + + $this->assertEquals( + $b24UserId, + $account->getBitrix24UserId(), + sprintf( + 'Expected the property value to be "%s", but got "%s"', + $b24UserId, + $account->getBitrix24UserId() + ) + ); + + $this->assertEquals( + $isB24UserAdmin, + $account->isBitrix24UserAdmin(), + sprintf( + 'Expected the property value to be "%s", but got "%s"', + $isB24UserAdmin, + $account->isBitrix24UserAdmin() + ) + ); + + $this->assertEquals( + $b24MemberId, + $account->getMemberId(), + sprintf( + 'Expected the property value to be "%s", but got "%s"', + $b24MemberId, + $account->getMemberId() + ) + ); + + $this->assertEquals( + $b24DomainUrl, + $account->getDomainUrl(), + sprintf( + 'Expected the property value to be "%s", but got "%s"', + $b24DomainUrl, + $account->getDomainUrl() + ) + ); + + $this->assertEquals( + $authToken, + $account->getAuthToken(), + sprintf('Object not equals') + ); + + $this->assertEquals( + $appVersion, + $account->getApplicationVersion(), + sprintf( + 'Expected the property value to be "%s", but got "%s"', + $appVersion, + $account->getApplicationVersion() + ) + ); + $this->assertEquals( + $scope, + $account->getApplicationScope(), + sprintf('Object not equals') + ); $this->assertContains( Bitrix24AccountCreatedEvent::class, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 817ceb7..0de29b0 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -80,7 +80,24 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void ) ); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertEquals($newAuthToken->accessToken, $updated->getAuthToken()->accessToken); - $this->assertEquals($newAuthToken->refreshToken, $updated->getAuthToken()->refreshToken); + $this->assertEquals( + $newAuthToken->accessToken, + $updated->getAuthToken()->accessToken, + sprintf( + 'Expected accessToken %s but got %s', + $newAuthToken->accessToken, + $updated->getAuthToken()->accessToken + ) + ); + + $this->assertEquals( + $newAuthToken->refreshToken, + $updated->getAuthToken()->refreshToken, + sprintf( + 'Expected refreshToken %s but got %s', + $newAuthToken->refreshToken, + $updated->getAuthToken()->refreshToken + ) + ); } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 31cddc5..8b6a752 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -69,11 +69,21 @@ public function testUninstallWithHappyPath(): void $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertEquals(Bitrix24AccountStatus::deleted, $updated->getStatus()); + $this->assertEquals( + Bitrix24AccountStatus::deleted, + $updated->getStatus(), + sprintf('Expected status deleted') + ); $this->assertTrue(in_array( Bitrix24AccountApplicationUninstalledEvent::class, - $this->eventDispatcher->getOrphanedEvents())); + $this->eventDispatcher->getOrphanedEvents() + ), + sprintf( + 'Event %s was expected to be in the list of orphan events, but it is missing', + Bitrix24AccountApplicationUninstalledEvent::class + ) + ); } #[Override] From a67cb48264eab24be198f3eaffdb75441d51e7b2 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 24 Nov 2024 14:04:05 +0300 Subject: [PATCH 064/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20Fetcher=20=D1=82=D0=B5=D1=81=D1=82=20-=20=D0=92?= =?UTF-8?q?=20=D0=BA=D0=B0=D0=B6=D0=B4=D0=BE=D0=BC=20use=20case=20=D1=81?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4?= =?UTF-8?q?=20=D1=81=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=BE?= =?UTF-8?q?=D0=B9=20-=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=20=D0=B2=20xml=20=D0=BD=D0=B0=D0=B7=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D1=81=D1=82=D0=BE=D0=BB=D0=B1=D1=86=D0=B0=20=D0=BE?= =?UTF-8?q?=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...x24Accounts.Entity.Bitrix24Account.dcm.xml | 2 +- src/Bitrix24Accounts/ReadModel/Fetcher.php | 4 +- .../UseCase/InstallFinish/Handler.php | 49 +++++++------ .../UseCase/RenewAuthToken/Handler.php | 51 +++++++------- .../Bitrix24Accounts/FetcherTest.php | 68 +++++++++++++++++++ 5 files changed, 129 insertions(+), 45 deletions(-) create mode 100644 tests/Functional/Bitrix24Accounts/FetcherTest.php diff --git a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml index 0d19a83..c2e57d9 100644 --- a/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml +++ b/config/xml/Bitrix24.Lib.Bitrix24Accounts.Entity.Bitrix24Account.dcm.xml @@ -20,7 +20,7 @@ - + diff --git a/src/Bitrix24Accounts/ReadModel/Fetcher.php b/src/Bitrix24Accounts/ReadModel/Fetcher.php index 03ed4dc..91b1982 100644 --- a/src/Bitrix24Accounts/ReadModel/Fetcher.php +++ b/src/Bitrix24Accounts/ReadModel/Fetcher.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\ReadModel; +use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Doctrine\ORM\EntityManagerInterface; use Knp\Component\Pager\Pagination\PaginationInterface; use Knp\Component\Pager\PaginatorInterface; @@ -21,13 +22,14 @@ public function list( int $size ): PaginationInterface { + $queryBuilder = $this->em->getConnection()->createQueryBuilder() ->select( 'b24account.id as id', 'b24account.status as status', 'b24account.member_id as member_id', 'b24account.domain_url as domain_url', - 'b24account.app_version as application_version', + 'b24account.application_version as application_version', 'b24account.created_at_utc as created_at', 'b24account.updated_at_utc as updated_at', ) diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index fe22b80..7b31f3f 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; +use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; @@ -38,17 +39,37 @@ public function handle(Command $command): void 'b24_user_id' => $command->bitrix24UserId, ]); + + /** + * @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $targetAccount + */ + $targetAccount = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId,Bitrix24AccountStatus::new, $command->bitrix24UserId); + + $targetAccount->applicationInstalled($command->applicationToken); + + $this->bitrix24AccountRepository->save($targetAccount); + $this->flusher->flush(); + foreach ($targetAccount->emitEvents() as $event) { + $this->eventDispatcher->dispatch($event); + } + + $this->logger->debug('Bitrix24Accounts.InstallFinish.Finish'); + } + + public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $status, int|null $bitrix24UserId): Bitrix24AccountInterface + { $accounts = $this->bitrix24AccountRepository->findByMemberId( - $command->memberId, - Bitrix24AccountStatus::new, - $command->bitrix24UserId + $memberId, + $status, + $bitrix24UserId ); + if ([] === $accounts) { throw new Bitrix24AccountNotFoundException( sprintf( 'bitrix24 account for domain %s with member id %s in status «new» not found', - $command->domainUrl, - $command->memberId + $domainUrl, + $memberId ) ); } @@ -57,24 +78,12 @@ public function handle(Command $command): void throw new MultipleBitrix24AccountsFoundException( sprintf( 'multiple bitrix24 accounts for domain %s with member id %s in status «new» found', - $command->domainUrl, - $command->memberId + $domainUrl, + $memberId ) ); } - /** - * @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $targetAccount - */ - $targetAccount = $accounts[0]; - $targetAccount->applicationInstalled($command->applicationToken); - - $this->bitrix24AccountRepository->save($targetAccount); - $this->flusher->flush(); - foreach ($targetAccount->emitEvents() as $event) { - $this->eventDispatcher->dispatch($event); - } - - $this->logger->debug('Bitrix24Accounts.InstallFinish.Finish'); + return $accounts[0]; } } diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index 3fe5632..cf00ff6 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -36,43 +36,48 @@ public function handle(Command $command): void ]); // get all active bitrix24 accounts + $targetAccount = $this->getSingleAccountByMemberId($command->renewedAuthToken->domain, $command->renewedAuthToken->memberId,Bitrix24AccountStatus::active,$command->bitrix24UserId); + + /** + * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount + */ + $targetAccount->renewAuthToken($command->renewedAuthToken); + $this->bitrix24AccountRepository->save($targetAccount); + $this->flusher->flush(); + foreach ($targetAccount->emitEvents() as $event) { + $this->eventDispatcher->dispatch($event); + } + + $this->logger->debug('Bitrix24Accounts.RenewAuthToken.finish'); + } + + public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $status, int|null $bitrix24UserId): Bitrix24AccountInterface + { $accounts = $this->bitrix24AccountRepository->findByMemberId( - $command->renewedAuthToken->memberId, - Bitrix24AccountStatus::active, - $command->bitrix24UserId + $memberId, + $status, + $bitrix24UserId ); - if ($command->bitrix24UserId === null && count($accounts) > 1) { + if ($bitrix24UserId === null && count($accounts) > 1) { throw new MultipleBitrix24AccountsFoundException( sprintf('updating auth token failure - for domain %s with member id %s found multiple active accounts, try pass bitrix24_user_id in command', - $command->renewedAuthToken->domain, - $command->renewedAuthToken->memberId + $domainUrl, + $memberId ) ); } - if ($command->bitrix24UserId !== null && count($accounts) > 1) { + if ($bitrix24UserId !== null && count($accounts) > 1) { throw new MultipleBitrix24AccountsFoundException( sprintf('updating auth token failure - for domain %s with member id %s and bitrix24 user id %s found multiple active accounts', - $command->renewedAuthToken->domain, - $command->renewedAuthToken->memberId, - $command->bitrix24UserId + $domainUrl, + $memberId, + $bitrix24UserId ) ); } - $targetAccount = $accounts[0]; - - /** - * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount - */ - $targetAccount->renewAuthToken($command->renewedAuthToken); - $this->bitrix24AccountRepository->save($targetAccount); - $this->flusher->flush(); - foreach ($targetAccount->emitEvents() as $event) { - $this->eventDispatcher->dispatch($event); - } - - $this->logger->debug('Bitrix24Accounts.RenewAuthToken.finish'); + return $accounts[0]; } } \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/FetcherTest.php b/tests/Functional/Bitrix24Accounts/FetcherTest.php new file mode 100644 index 0000000..c4e5dc4 --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/FetcherTest.php @@ -0,0 +1,68 @@ +entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); + $requestStack = new RequestStack(); + $argumentAccess = new ArgumentAccess\RequestArgumentAccess($requestStack); + $this->paginator = new Paginator($eventDispatcher, $argumentAccess); + $this->fetcher = new Fetcher($this->entityManager, $this->paginator); + $this->flusher = new Flusher($this->entityManager); + $this->repository = new Bitrix24AccountRepository($this->entityManager); + } + + public function testListReturnsPaginatedResults(): void + { + + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->build() + ; + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + // Параметры для теста + $page = 1; + $size = 10; + // Вызов метода list + /** @var PaginationInterface $result */ + $result = $this->fetcher->list($page, $size); + + // Проверка, что результат является экземпляром PaginationInterface + $this->assertInstanceOf(PaginationInterface::class, $result); + + // Проверка, что данные возвращаются корректно + $this->assertGreaterThan(0, count($result)); // Проверяем, что есть хотя бы одна запись + } + +} \ No newline at end of file From f082b166112560bf4879c0d673ad8640f5bd4c87 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Tue, 26 Nov 2024 00:36:20 +0300 Subject: [PATCH 065/130] =?UTF-8?q?-=20=D0=92=D0=BE=D0=B9=D0=BD=D0=B0=20?= =?UTF-8?q?=D1=81=20AggregateRoot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- src/AggregateRoot.php | 19 +++++++++++++++ .../Entity/Bitrix24Account.php | 23 +++++++------------ .../UseCase/Uninstall/Handler.php | 6 ++++- .../UseCase/Uninstall/HandlerTest.php | 12 +++++++--- 5 files changed, 42 insertions(+), 20 deletions(-) create mode 100644 src/AggregateRoot.php diff --git a/Makefile b/Makefile index c71ff1d..823a5ae 100644 --- a/Makefile +++ b/Makefile @@ -101,7 +101,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testRenewAuthTokenWithoutBitrix24UserId' tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testUninstallWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/AggregateRoot.php b/src/AggregateRoot.php new file mode 100644 index 0000000..4fc766b --- /dev/null +++ b/src/AggregateRoot.php @@ -0,0 +1,19 @@ +events; + $this->events = []; + + return $events; + } + +} \ No newline at end of file diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 580d719..482651b 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -12,6 +12,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\Entity; +use Bitrix24\Lib\AggregateRoot; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationInstalledEvent; @@ -30,7 +31,7 @@ use Symfony\Component\Uid\Uuid; use Symfony\Contracts\EventDispatcher\Event; -class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEmitterInterface +class Bitrix24Account implements Bitrix24AccountInterface { private array $applicationScope; @@ -40,10 +41,7 @@ class Bitrix24Account implements Bitrix24AccountInterface, AggregateRootEventsEm private AuthToken $authToken; - /** - * @var Event[] - */ - private array $events = []; + private array $events; public function __construct( private Uuid $id, @@ -207,6 +205,8 @@ public function applicationInstalled(string $applicationToken): void $this->id, new CarbonImmutable() ); + var_dump('applicationInstalled'); + // dd($this->events); } /** @@ -346,19 +346,12 @@ public function getComment(): ?string return $this->comment; } - /** - * @return Event[] - */ - #[\Override] - public function emitEvents(): array + public function getEvents(): array { - $events = $this->events; - $this->events = []; - - return $events; + return $this->events; } - public function addAccountCreatedEventIfNeeded(bool $isEmitCreatedEvent): void + private function addAccountCreatedEventIfNeeded(bool $isEmitCreatedEvent): void { if ($isEmitCreatedEvent) { // Создание события и добавление его в массив событий diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 407a7d1..b85a390 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall; +use Bitrix24\Lib\AggregateRoot; use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; @@ -19,7 +20,7 @@ public function __construct( private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, private Flusher $flusher, - private LoggerInterface $logger + private LoggerInterface $logger, ) {} /** @@ -28,6 +29,8 @@ public function __construct( */ public function handle(Command $command): void { + var_dump('handle'); + $aggregateRoot = new AggregateRoot(); $this->logger->debug('Bitrix24Accounts.Uninstall.start', [ 'b24_application_token' => $command->applicationToken, ]); @@ -41,6 +44,7 @@ public function handle(Command $command): void $account->applicationUninstalled($command->applicationToken); $this->bitrix24AccountRepository->save($account); $this->flusher->flush(); + foreach ($account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 8b6a752..c712bf7 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -13,6 +13,7 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\Uninstall; +use Bitrix24\Lib\AggregateRoot; use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; @@ -45,6 +46,7 @@ class HandlerTest extends TestCase #[Test] public function testUninstallWithHappyPath(): void { + var_dump('testUninstallWithHappyPath'); $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; $bitrix24Account = new Bitrix24Account( Uuid::v7(), @@ -65,9 +67,10 @@ public function testUninstallWithHappyPath(): void $this->repository->save($bitrix24Account); $this->flusher->flush(); - + var_dump('beforehandle'); + var_dump($this->eventDispatcher->getOrphanedEvents()); $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); - + var_dump($this->eventDispatcher->getOrphanedEvents()); $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertEquals( Bitrix24AccountStatus::deleted, @@ -89,15 +92,18 @@ public function testUninstallWithHappyPath(): void #[Override] protected function setUp(): void { + var_dump('setUp'); + $entityManager = EntityManagerFactory::get(); $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager); $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->handler = new Bitrix24Accounts\UseCase\Uninstall\Handler( $this->eventDispatcher, $this->repository, $this->flusher, - new NullLogger() + new NullLogger(), ); } } \ No newline at end of file From e6a69779c7eaebe6392ee11e73d44cef44e4d221 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Wed, 27 Nov 2024 23:37:50 +0300 Subject: [PATCH 066/130] =?UTF-8?q?-=20=D0=92=D0=BD=D0=B5=D1=81=20=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20=D0=B4=D0=BB=D1=8F=20Aggregate?= =?UTF-8?q?Root=20-=20=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20=D0=B8=D0=B7=20?= =?UTF-8?q?=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D0=B0=20delete=20=D1=80=D0=B5?= =?UTF-8?q?=D0=BF=D0=BE=D0=B7=D0=B8=D1=82=D0=BE=D1=80=D0=B8=D1=8F=20=D0=B0?= =?UTF-8?q?=D0=BA=D0=BA=D0=B0=D1=83=D0=BD=D1=82=D0=B0=20=D1=85=D0=B0=D1=80?= =?UTF-8?q?=D0=B4=20=D0=B4=D0=B5=D0=BB=D0=B8=D1=82=20=D0=B8=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D1=81=D0=BE=D1=84=D1=82=20=D0=B4=D0=B5=D0=BB=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 11 ++++++----- .../Doctrine/Bitrix24AccountRepository.php | 4 ++-- src/Bitrix24Accounts/UseCase/Uninstall/Handler.php | 2 -- .../UseCase/Uninstall/HandlerTest.php | 5 ----- 5 files changed, 9 insertions(+), 15 deletions(-) diff --git a/Makefile b/Makefile index 823a5ae..276e66c 100644 --- a/Makefile +++ b/Makefile @@ -101,7 +101,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testUninstallWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testDeleteHappyPath' tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 482651b..7328cce 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -31,7 +31,7 @@ use Symfony\Component\Uid\Uuid; use Symfony\Contracts\EventDispatcher\Event; -class Bitrix24Account implements Bitrix24AccountInterface +class Bitrix24Account extends AggregateRoot implements Bitrix24AccountInterface { private array $applicationScope; @@ -41,8 +41,6 @@ class Bitrix24Account implements Bitrix24AccountInterface private AuthToken $authToken; - private array $events; - public function __construct( private Uuid $id, private readonly int $bitrix24UserId, @@ -99,6 +97,11 @@ public function getStatus(): Bitrix24AccountStatus return $this->status; } + public function setStatus(Bitrix24AccountStatus $status): void + { + $this->status = $status; + } + /** * @throws InvalidArgumentException */ @@ -205,8 +208,6 @@ public function applicationInstalled(string $applicationToken): void $this->id, new CarbonImmutable() ); - var_dump('applicationInstalled'); - // dd($this->events); } /** diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 9cb26d9..8827969 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -100,8 +100,8 @@ public function delete(Uuid $uuid): void ) ); } - - $this->getEntityManager()->remove($bitrix24Account); + $bitrix24Account->setStatus(Bitrix24AccountStatus::deleted); + $this->save($bitrix24Account); } public function findAllActive(int|null $limit = null, int|null $offset = null): array diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index b85a390..5c72473 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -29,8 +29,6 @@ public function __construct( */ public function handle(Command $command): void { - var_dump('handle'); - $aggregateRoot = new AggregateRoot(); $this->logger->debug('Bitrix24Accounts.Uninstall.start', [ 'b24_application_token' => $command->applicationToken, ]); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index c712bf7..498ec17 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -46,7 +46,6 @@ class HandlerTest extends TestCase #[Test] public function testUninstallWithHappyPath(): void { - var_dump('testUninstallWithHappyPath'); $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; $bitrix24Account = new Bitrix24Account( Uuid::v7(), @@ -67,10 +66,7 @@ public function testUninstallWithHappyPath(): void $this->repository->save($bitrix24Account); $this->flusher->flush(); - var_dump('beforehandle'); - var_dump($this->eventDispatcher->getOrphanedEvents()); $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); - var_dump($this->eventDispatcher->getOrphanedEvents()); $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertEquals( Bitrix24AccountStatus::deleted, @@ -92,7 +88,6 @@ public function testUninstallWithHappyPath(): void #[Override] protected function setUp(): void { - var_dump('setUp'); $entityManager = EntityManagerFactory::get(); $this->repository = new Bitrix24AccountRepository($entityManager); From ba7575abd4c9db60a12366c268c01e50c0992898 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Fri, 29 Nov 2024 00:04:04 +0300 Subject: [PATCH 067/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=B2=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=20getByI?= =?UTF-8?q?d=20-=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=20?= =?UTF-8?q?=D1=82=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- .../Infrastructure/Doctrine/Bitrix24AccountRepository.php | 7 ++++--- .../Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php | 4 ++++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 276e66c..e64b4d8 100644 --- a/Makefile +++ b/Makefile @@ -101,7 +101,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testDeleteHappyPath' tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testDeleteNotInDeletedState' tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 8827969..c3322af 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -32,14 +32,15 @@ public function __construct( #[Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { - $res = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); - if (null === $res) { + $account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); + if (null === $account || $account->getStatus() === Bitrix24AccountStatus::deleted) { throw new Bitrix24AccountNotFoundException( sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122()) ); } - return $res; + + return $account; } #[Override] diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 498ec17..1f2c6db 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -21,6 +21,7 @@ use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationUninstalledEvent; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; @@ -67,7 +68,10 @@ public function testUninstallWithHappyPath(): void $this->flusher->flush(); $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); + + $this->expectException(Bitrix24AccountNotFoundException::class); $updated = $this->repository->getById($bitrix24Account->getId()); + $this->assertEquals( Bitrix24AccountStatus::deleted, $updated->getStatus(), From 57a3f515e5367f065b6eeb60a03514fbe59a8fdf Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 30 Nov 2024 17:30:57 +0300 Subject: [PATCH 068/130] =?UTF-8?q?-=20=D0=A2=D0=B5=D1=81=D1=82=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D1=84=D0=B5=D1=82=D1=87=D0=B5=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- .../Entity/Bitrix24Account.php | 9 ++++----- src/Bitrix24Accounts/ReadModel/Fetcher.php | 10 +++++++--- .../Bitrix24Accounts/FetcherTest.php | 19 +++++++++++++------ 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/Makefile b/Makefile index e64b4d8..441329a 100644 --- a/Makefile +++ b/Makefile @@ -101,7 +101,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testDeleteNotInDeletedState' tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testListReturnsPaginatedResults' tests/Functional/Bitrix24Accounts/FetcherTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 7328cce..6e31484 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -33,7 +33,7 @@ class Bitrix24Account extends AggregateRoot implements Bitrix24AccountInterface { - private array $applicationScope; + private array|Scope $applicationScope; private ?string $applicationToken = null; @@ -57,7 +57,8 @@ public function __construct( bool $isEmitBitrix24AccountCreatedEvent = false ) { $this->authToken = $authToken; - $this->applicationScope = $applicationScope->getScopeCodes(); + $array = $applicationScope->getScopeCodes(); + $this->applicationScope = $array; $this->addAccountCreatedEventIfNeeded($isEmitBitrix24AccountCreatedEvent); } @@ -144,13 +145,11 @@ public function getApplicationVersion(): int return $this->applicationVersion; } - /** - * @throws UnknownScopeCodeException - */ #[\Override] public function getApplicationScope(): Scope { return new Scope($this->applicationScope); + // return $this->applicationScope; } /** diff --git a/src/Bitrix24Accounts/ReadModel/Fetcher.php b/src/Bitrix24Accounts/ReadModel/Fetcher.php index 91b1982..0430f40 100644 --- a/src/Bitrix24Accounts/ReadModel/Fetcher.php +++ b/src/Bitrix24Accounts/ReadModel/Fetcher.php @@ -6,9 +6,9 @@ use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Doctrine\ORM\EntityManagerInterface; +use Knp\Component\Pager\Event\Subscriber\Paginate\Callback\CallbackPagination; use Knp\Component\Pager\Pagination\PaginationInterface; use Knp\Component\Pager\PaginatorInterface; - class Fetcher { public function __construct( @@ -23,7 +23,7 @@ public function list( ): PaginationInterface { - $queryBuilder = $this->em->getConnection()->createQueryBuilder() + /* $queryBuilder = $this->em->getConnection()->createQueryBuilder() ->select( 'b24account.id as id', 'b24account.status as status', @@ -35,7 +35,11 @@ public function list( ) ->from('bitrix24account', 'b24account') ->orderBy('b24account.created_at_utc', 'DESC'); + */ + // var_dump($queryBuilder->getMaxResults()); + $query = $this->em->createQuery("SELECT b24account FROM Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account b24account"); - return $this->paginator->paginate($queryBuilder, $page, $size); + return $this->paginator->paginate($query, $page, $size); + // return $this->paginator->paginate($queryBuilder->getSQL(), $page, $size); } } \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/FetcherTest.php b/tests/Functional/Bitrix24Accounts/FetcherTest.php index c4e5dc4..fa1012c 100644 --- a/tests/Functional/Bitrix24Accounts/FetcherTest.php +++ b/tests/Functional/Bitrix24Accounts/FetcherTest.php @@ -8,6 +8,8 @@ use Bitrix24\Lib\Bitrix24Accounts\ReadModel\Fetcher; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Tests\EntityManagerFactory; +use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber; +use Knp\Component\Pager\Event\Subscriber\Sortable\SortableSubscriber; use Knp\Component\Pager\Paginator; use PHPUnit\Framework\TestCase; use Doctrine\ORM\EntityManagerInterface; @@ -16,8 +18,9 @@ use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Symfony\Component\EventDispatcher\EventDispatcher; -use Knp\Component\Pager\ArgumentAccess; use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Request; +use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; class FetcherTest extends TestCase { @@ -34,9 +37,13 @@ protected function setUp(): void { $this->entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); + $eventDispatcher->addSubscriber(new PaginationSubscriber()); + $eventDispatcher->addSubscriber(new SortableSubscriber()); + // dd(Request::createFromGlobals()); $requestStack = new RequestStack(); - $argumentAccess = new ArgumentAccess\RequestArgumentAccess($requestStack); - $this->paginator = new Paginator($eventDispatcher, $argumentAccess); + // Request::createFromGlobals() + $accessor = new RequestArgumentAccess(new RequestStack()); + $this->paginator = new Paginator($eventDispatcher, $accessor); $this->fetcher = new Fetcher($this->entityManager, $this->paginator); $this->flusher = new Flusher($this->entityManager); $this->repository = new Bitrix24AccountRepository($this->entityManager); @@ -55,14 +62,14 @@ public function testListReturnsPaginatedResults(): void $page = 1; $size = 10; // Вызов метода list - /** @var PaginationInterface $result */ $result = $this->fetcher->list($page, $size); - + // var_dump($result->getItems()); + // var_dump($result->count()); // Проверка, что результат является экземпляром PaginationInterface $this->assertInstanceOf(PaginationInterface::class, $result); // Проверка, что данные возвращаются корректно - $this->assertGreaterThan(0, count($result)); // Проверяем, что есть хотя бы одна запись + $this->assertGreaterThan(0, $result->count()); // Проверяем, что есть хотя бы одна запись } } \ No newline at end of file From 9e936c734a5b2f1c1f201798de011c8a08d2f5e8 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Tue, 3 Dec 2024 00:17:20 +0300 Subject: [PATCH 069/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=BD=D0=B0=20scope?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/AggregateRoot.php | 6 ++++++ src/Bitrix24Accounts/Entity/Bitrix24Account.php | 12 +++--------- tests/Functional/Bitrix24Accounts/FetcherTest.php | 4 +--- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/AggregateRoot.php b/src/AggregateRoot.php index 4fc766b..91ffcb3 100644 --- a/src/AggregateRoot.php +++ b/src/AggregateRoot.php @@ -8,6 +8,12 @@ class AggregateRoot implements AggregateRootEventsEmitterInterface { protected array $events = []; + + public function getEvents(): array + { + return $this->events; + } + public function emitEvents(): array { $events = $this->events; diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 6e31484..9934d7c 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -33,7 +33,7 @@ class Bitrix24Account extends AggregateRoot implements Bitrix24AccountInterface { - private array|Scope $applicationScope; + private Scope $applicationScope; private ?string $applicationToken = null; @@ -57,8 +57,7 @@ public function __construct( bool $isEmitBitrix24AccountCreatedEvent = false ) { $this->authToken = $authToken; - $array = $applicationScope->getScopeCodes(); - $this->applicationScope = $array; + $this->applicationScope = $applicationScope->getScopeCodes(); $this->addAccountCreatedEventIfNeeded($isEmitBitrix24AccountCreatedEvent); } @@ -148,8 +147,7 @@ public function getApplicationVersion(): int #[\Override] public function getApplicationScope(): Scope { - return new Scope($this->applicationScope); - // return $this->applicationScope; + return $this->applicationScope; } /** @@ -346,10 +344,6 @@ public function getComment(): ?string return $this->comment; } - public function getEvents(): array - { - return $this->events; - } private function addAccountCreatedEventIfNeeded(bool $isEmitCreatedEvent): void { diff --git a/tests/Functional/Bitrix24Accounts/FetcherTest.php b/tests/Functional/Bitrix24Accounts/FetcherTest.php index fa1012c..8982d55 100644 --- a/tests/Functional/Bitrix24Accounts/FetcherTest.php +++ b/tests/Functional/Bitrix24Accounts/FetcherTest.php @@ -52,9 +52,7 @@ protected function setUp(): void public function testListReturnsPaginatedResults(): void { - $bitrix24Account = (new Bitrix24AccountBuilder()) - ->build() - ; + $bitrix24Account = (new Bitrix24AccountBuilder())->build(); $this->repository->save($bitrix24Account); $this->flusher->flush(); From 59e34a5a9551b3489646ef36525adfa9a209fc16 Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:01:44 +0600 Subject: [PATCH 070/130] Simplify application scope handling Updated the Bitrix24Account entity to store the application scope object directly instead of extracting scope codes. This change enhances flexibility for scope management and aligns with object-oriented design principles. Signed-off-by: mesilov --- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 9934d7c..b8dddb3 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -57,7 +57,7 @@ public function __construct( bool $isEmitBitrix24AccountCreatedEvent = false ) { $this->authToken = $authToken; - $this->applicationScope = $applicationScope->getScopeCodes(); + $this->applicationScope = $applicationScope; $this->addAccountCreatedEventIfNeeded($isEmitBitrix24AccountCreatedEvent); } @@ -288,7 +288,7 @@ public function updateApplicationVersion(int $version, ?Scope $newScope): void $this->applicationVersion = $version; if ($newScope instanceof Scope) { - $this->applicationScope = $newScope->getScopeCodes(); + $this->applicationScope = $newScope; } $this->updatedAt = new CarbonImmutable(); From d6b58a1b82b503d1ff63229efa816e4bd1f078cc Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:13:41 +0600 Subject: [PATCH 071/130] Update PHP SDK in test commands This commit adds a step to update the bitrix24/b24-php-sdk package using composer in the unit and functional test commands in the Makefile. This ensures the tests run with the latest version of the SDK, improving compatibility and catching any integration issues early. Signed-off-by: mesilov --- Makefile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Makefile b/Makefile index 441329a..9c2bf09 100644 --- a/Makefile +++ b/Makefile @@ -90,10 +90,12 @@ lint-cs-fixer-fix: # unit-tests test-run-unit: + docker-compose run --rm php-cli composer update bitrix24/b24-php-sdk --prefer-source docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox # functional-tests, work with test database test-run-functional: debug-print-env + docker-compose run --rm php-cli composer update bitrix24/b24-php-sdk --prefer-source docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:update --dump-sql @@ -101,6 +103,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env + docker-compose run --rm php-cli composer update bitrix24/b24-php-sdk --prefer-source docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testListReturnsPaginatedResults' tests/Functional/Bitrix24Accounts/FetcherTest.php schema-drop: From 9f5f133f139f6ed4f5b51805cc33cccee06c6453 Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:16:17 +0600 Subject: [PATCH 072/130] Update Composer flags to prefer source in workflows Switch the Composer installation method from "prefer-dist" to "prefer-source" in unit and functional test workflows. This change aims to ensure that the source code is retrieved directly, which may be necessary for tracking changes or resolving specific dependency issues during testing. Signed-off-by: mesilov --- .github/workflows/tests-functional.yml | 2 +- .github/workflows/tests-unit.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 244ba73..760c746 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -5,7 +5,7 @@ on: pull_request: env: - COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist" + COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-source" DATABASE_HOST: localhost DATABASE_USER: b24phpLibTest DATABASE_PASSWORD: b24phpLibTest diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index 91ada7d..497e276 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -5,7 +5,7 @@ on: pull_request: env: - COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist" + COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-source" jobs: tests: From 7e3727c391a3b330862e483b624aaf254b4f4ff2 Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:22:47 +0600 Subject: [PATCH 073/130] Add #[Override] attribute and refactor variable names Added the #[Override] attribute to several function declarations to explicitly denote methods that override parent class methods. Refactored variable names across the project for improved clarity and consistency, particularly in test files and the Bitrix24Account entity. These changes enhance code readability and maintainability while aligning with coding standards. Signed-off-by: mesilov --- src/AggregateRoot.php | 1 + .../Entity/Bitrix24Account.php | 16 +++----- .../Doctrine/Bitrix24AccountRepository.php | 4 ++ .../UseCase/InstallFinish/Handler.php | 14 +++---- .../UseCase/InstallStart/Handler.php | 6 +-- .../UseCase/RenewAuthToken/Handler.php | 13 ++++--- tests/EntityManagerFactory.php | 3 +- .../Builders/Bitrix24AccountBuilder.php | 33 +++++++++++------ .../Bitrix24Accounts/FetcherTest.php | 14 ++++--- .../UseCase/ChangeDomainUrl/HandlerTest.php | 2 + .../UseCase/InstallFinish/HandlerTest.php | 3 ++ .../UseCase/InstallStart/HandlerTest.php | 37 ++++++++++--------- .../UseCase/RenewAuthToken/HandlerTest.php | 3 ++ .../UseCase/Uninstall/HandlerTest.php | 5 ++- tests/Functional/FlusherDecorator.php | 1 + 15 files changed, 91 insertions(+), 64 deletions(-) diff --git a/src/AggregateRoot.php b/src/AggregateRoot.php index 91ffcb3..ea94605 100644 --- a/src/AggregateRoot.php +++ b/src/AggregateRoot.php @@ -14,6 +14,7 @@ public function getEvents(): array return $this->events; } + #[\Override] public function emitEvents(): array { $events = $this->events; diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index b8dddb3..ace860a 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -33,31 +33,25 @@ class Bitrix24Account extends AggregateRoot implements Bitrix24AccountInterface { - private Scope $applicationScope; - private ?string $applicationToken = null; private ?string $comment = null; - private AuthToken $authToken; - public function __construct( - private Uuid $id, + private readonly Uuid $id, private readonly int $bitrix24UserId, private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ private readonly string $memberId, private string $domainUrl, private Bitrix24AccountStatus $status, - AuthToken $authToken, + private AuthToken $authToken, private readonly CarbonImmutable $createdAt, private CarbonImmutable $updatedAt, private int $applicationVersion, - Scope $applicationScope, + private Scope $applicationScope, bool $isEmitBitrix24AccountCreatedEvent = false ) { - $this->authToken = $authToken; - $this->applicationScope = $applicationScope; $this->addAccountCreatedEventIfNeeded($isEmitBitrix24AccountCreatedEvent); } @@ -97,9 +91,9 @@ public function getStatus(): Bitrix24AccountStatus return $this->status; } - public function setStatus(Bitrix24AccountStatus $status): void + public function setStatus(Bitrix24AccountStatus $bitrix24AccountStatus): void { - $this->status = $status; + $this->status = $bitrix24AccountStatus; } /** diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index c3322af..d095525 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -71,6 +71,7 @@ public function findByMemberId( if ($bitrix24AccountStatus instanceof Bitrix24AccountStatus) { $criteria['status'] = $bitrix24AccountStatus->name; } + if (null !== $bitrix24UserId) { $criteria['bitrix24UserId'] = $bitrix24UserId; } @@ -92,6 +93,7 @@ public function delete(Uuid $uuid): void sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122()) ); } + if (Bitrix24AccountStatus::deleted !== $bitrix24Account->getStatus()) { throw new InvalidArgumentException( sprintf( @@ -101,6 +103,7 @@ public function delete(Uuid $uuid): void ) ); } + $bitrix24Account->setStatus(Bitrix24AccountStatus::deleted); $this->save($bitrix24Account); } @@ -123,6 +126,7 @@ public function findAllActive(int|null $limit = null, int|null $offset = null): * @phpstan-return array * @throws InvalidArgumentException */ + #[\Override] public function findByApplicationToken(string $applicationToken): array { if ($applicationToken === '') { diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 7b31f3f..054267f 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -41,26 +41,26 @@ public function handle(Command $command): void /** - * @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $targetAccount + * @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ - $targetAccount = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId,Bitrix24AccountStatus::new, $command->bitrix24UserId); + $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId,Bitrix24AccountStatus::new, $command->bitrix24UserId); - $targetAccount->applicationInstalled($command->applicationToken); + $bitrix24Account->applicationInstalled($command->applicationToken); - $this->bitrix24AccountRepository->save($targetAccount); + $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush(); - foreach ($targetAccount->emitEvents() as $event) { + foreach ($bitrix24Account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } $this->logger->debug('Bitrix24Accounts.InstallFinish.Finish'); } - public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $status, int|null $bitrix24UserId): Bitrix24AccountInterface + public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, int|null $bitrix24UserId): Bitrix24AccountInterface { $accounts = $this->bitrix24AccountRepository->findByMemberId( $memberId, - $status, + $bitrix24AccountStatus, $bitrix24UserId ); diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index 722352d..074e77a 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -29,7 +29,7 @@ public function handle(Command $command): void 'member_id' => $command->memberId, ]); - $newAccount = new Bitrix24Account( + $bitrix24Account = new Bitrix24Account( $command->uuid, $command->bitrix24UserId, $command->isBitrix24UserAdmin, @@ -43,10 +43,10 @@ public function handle(Command $command): void $command->applicationScope, true ); - $this->bitrix24AccountRepository->save($newAccount); + $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush(); - foreach ($newAccount->emitEvents() as $event) { + foreach ($bitrix24Account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index cf00ff6..fcea341 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -36,26 +36,27 @@ public function handle(Command $command): void ]); // get all active bitrix24 accounts - $targetAccount = $this->getSingleAccountByMemberId($command->renewedAuthToken->domain, $command->renewedAuthToken->memberId,Bitrix24AccountStatus::active,$command->bitrix24UserId); + $bitrix24Account = $this->getSingleAccountByMemberId($command->renewedAuthToken->domain, $command->renewedAuthToken->memberId,Bitrix24AccountStatus::active,$command->bitrix24UserId); /** * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount */ - $targetAccount->renewAuthToken($command->renewedAuthToken); - $this->bitrix24AccountRepository->save($targetAccount); + $bitrix24Account->renewAuthToken($command->renewedAuthToken); + + $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush(); - foreach ($targetAccount->emitEvents() as $event) { + foreach ($bitrix24Account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } $this->logger->debug('Bitrix24Accounts.RenewAuthToken.finish'); } - public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $status, int|null $bitrix24UserId): Bitrix24AccountInterface + public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, int|null $bitrix24UserId): Bitrix24AccountInterface { $accounts = $this->bitrix24AccountRepository->findByMemberId( $memberId, - $status, + $bitrix24AccountStatus, $bitrix24UserId ); diff --git a/tests/EntityManagerFactory.php b/tests/EntityManagerFactory.php index 2127162..3cf197c 100644 --- a/tests/EntityManagerFactory.php +++ b/tests/EntityManagerFactory.php @@ -32,7 +32,7 @@ class EntityManagerFactory public static function get(): EntityManagerInterface { - if (self::$entityManager === null) { + if (!self::$entityManager instanceof \Doctrine\ORM\EntityManager) { $paths = [ dirname(__DIR__) . '/config/xml' ]; @@ -75,6 +75,7 @@ public static function get(): EntityManagerInterface $connection = DriverManager::getConnection($connectionParams, $configuration); self::$entityManager = new EntityManager($connection, $configuration); } + return self::$entityManager; } } \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php index 25538ec..100a91e 100644 --- a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php +++ b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php @@ -24,18 +24,28 @@ class Bitrix24AccountBuilder { - private Uuid $id; - private int $bitrix24UserId; - private bool $isBitrix24UserAdmin; + private readonly Uuid $id; + + private readonly int $bitrix24UserId; + + private readonly bool $isBitrix24UserAdmin; + /** bitrix24 portal unique id */ private string $memberId; + private string $domainUrl; - private Bitrix24AccountStatus $status; - private AuthToken $authToken; - private CarbonImmutable $createdAt; - private CarbonImmutable $updatedAt; - private int $applicationVersion; - private Scope $applicationScope; + + private Bitrix24AccountStatus $status = Bitrix24AccountStatus::active; + + private readonly AuthToken $authToken; + + private readonly CarbonImmutable $createdAt; + + private readonly CarbonImmutable $updatedAt; + + private readonly int $applicationVersion; + + private readonly Scope $applicationScope; public function __construct() { @@ -44,7 +54,6 @@ public function __construct() $this->isBitrix24UserAdmin = true; $this->memberId = Uuid::v4()->toRfc4122(); $this->domainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; - $this->status = Bitrix24AccountStatus::active; $this->authToken = new AuthToken('old_1', 'old_2', 3600); $this->createdAt = CarbonImmutable::now(); $this->updatedAt = CarbonImmutable::now(); @@ -64,9 +73,9 @@ public function withDomainUrl(string $domainUrl): self return $this; } - public function withStatus(Bitrix24AccountStatus $status): self + public function withStatus(Bitrix24AccountStatus $bitrix24AccountStatus): self { - $this->status = $status; + $this->status = $bitrix24AccountStatus; return $this; } diff --git a/tests/Functional/Bitrix24Accounts/FetcherTest.php b/tests/Functional/Bitrix24Accounts/FetcherTest.php index 8982d55..5a71445 100644 --- a/tests/Functional/Bitrix24Accounts/FetcherTest.php +++ b/tests/Functional/Bitrix24Accounts/FetcherTest.php @@ -29,10 +29,12 @@ class FetcherTest extends TestCase private PaginatorInterface $paginator; private Bitrix24AccountRepositoryInterface $repository; + private Fetcher $fetcher; private Flusher $flusher; + #[\Override] protected function setUp(): void { $this->entityManager = EntityManagerFactory::get(); @@ -40,10 +42,10 @@ protected function setUp(): void $eventDispatcher->addSubscriber(new PaginationSubscriber()); $eventDispatcher->addSubscriber(new SortableSubscriber()); // dd(Request::createFromGlobals()); - $requestStack = new RequestStack(); + new RequestStack(); // Request::createFromGlobals() - $accessor = new RequestArgumentAccess(new RequestStack()); - $this->paginator = new Paginator($eventDispatcher, $accessor); + $requestArgumentAccess = new RequestArgumentAccess(new RequestStack()); + $this->paginator = new Paginator($eventDispatcher, $requestArgumentAccess); $this->fetcher = new Fetcher($this->entityManager, $this->paginator); $this->flusher = new Flusher($this->entityManager); $this->repository = new Bitrix24AccountRepository($this->entityManager); @@ -60,14 +62,14 @@ public function testListReturnsPaginatedResults(): void $page = 1; $size = 10; // Вызов метода list - $result = $this->fetcher->list($page, $size); + $pagination = $this->fetcher->list($page, $size); // var_dump($result->getItems()); // var_dump($result->count()); // Проверка, что результат является экземпляром PaginationInterface - $this->assertInstanceOf(PaginationInterface::class, $result); + $this->assertInstanceOf(PaginationInterface::class, $pagination); // Проверка, что данные возвращаются корректно - $this->assertGreaterThan(0, $result->count()); // Проверяем, что есть хотя бы одна запись + $this->assertGreaterThan(0, $pagination->count()); // Проверяем, что есть хотя бы одна запись } } \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index 9448734..a590319 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -37,9 +37,11 @@ class HandlerTest extends TestCase { private Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler $handler; + private Flusher $flusher; private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; #[\Override] diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 47106c0..d444316 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -36,8 +36,11 @@ class HandlerTest extends TestCase { private Bitrix24Accounts\UseCase\InstallFinish\Handler $handler; + private Flusher $flusher; + private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; #[Test] diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 5461746..f9df3f5 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -41,8 +41,11 @@ class HandlerTest extends TestCase { private Bitrix24Accounts\UseCase\InstallStart\Handler $handler; + private Flusher $flusher; + private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; #[\Override] @@ -69,7 +72,7 @@ protected function setUp(): void #[Test] public function testInstallStartHappyPath(): void { - $accountId = Uuid::v7(); + $uuidV7 = Uuid::v7(); $b24UserId = random_int(1, 100_000); $isB24UserAdmin = true; $b24MemberId = Uuid::v7()->toRfc4122(); @@ -79,7 +82,7 @@ public function testInstallStartHappyPath(): void $scope = new Scope(['crm']); $this->handler->handle( new Bitrix24Accounts\UseCase\InstallStart\Command( - $accountId, + $uuidV7, $b24UserId, $isB24UserAdmin, $b24MemberId, @@ -90,67 +93,67 @@ public function testInstallStartHappyPath(): void ) ); - $account = $this->repository->getById($accountId); + $bitrix24Account = $this->repository->getById($uuidV7); $this->assertEquals( $b24UserId, - $account->getBitrix24UserId(), + $bitrix24Account->getBitrix24UserId(), sprintf( 'Expected the property value to be "%s", but got "%s"', $b24UserId, - $account->getBitrix24UserId() + $bitrix24Account->getBitrix24UserId() ) ); $this->assertEquals( $isB24UserAdmin, - $account->isBitrix24UserAdmin(), + $bitrix24Account->isBitrix24UserAdmin(), sprintf( 'Expected the property value to be "%s", but got "%s"', $isB24UserAdmin, - $account->isBitrix24UserAdmin() + $bitrix24Account->isBitrix24UserAdmin() ) ); $this->assertEquals( $b24MemberId, - $account->getMemberId(), + $bitrix24Account->getMemberId(), sprintf( 'Expected the property value to be "%s", but got "%s"', $b24MemberId, - $account->getMemberId() + $bitrix24Account->getMemberId() ) ); $this->assertEquals( $b24DomainUrl, - $account->getDomainUrl(), + $bitrix24Account->getDomainUrl(), sprintf( 'Expected the property value to be "%s", but got "%s"', $b24DomainUrl, - $account->getDomainUrl() + $bitrix24Account->getDomainUrl() ) ); $this->assertEquals( $authToken, - $account->getAuthToken(), - sprintf('Object not equals') + $bitrix24Account->getAuthToken(), + 'Object not equals' ); $this->assertEquals( $appVersion, - $account->getApplicationVersion(), + $bitrix24Account->getApplicationVersion(), sprintf( 'Expected the property value to be "%s", but got "%s"', $appVersion, - $account->getApplicationVersion() + $bitrix24Account->getApplicationVersion() ) ); $this->assertEquals( $scope, - $account->getApplicationScope(), - sprintf('Object not equals') + $bitrix24Account->getApplicationScope(), + 'Object not equals' ); $this->assertContains( diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 0de29b0..7109cdd 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -38,8 +38,11 @@ class HandlerTest extends TestCase { private Handler $handler; + private Flusher $flusher; + private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; #[\Override] diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 1f2c6db..d00bbec 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -40,8 +40,11 @@ class HandlerTest extends TestCase { private Bitrix24Accounts\UseCase\Uninstall\Handler $handler; + private Flusher $flusher; + private Bitrix24AccountRepositoryInterface $repository; + private TraceableEventDispatcher $eventDispatcher; #[Test] @@ -75,7 +78,7 @@ public function testUninstallWithHappyPath(): void $this->assertEquals( Bitrix24AccountStatus::deleted, $updated->getStatus(), - sprintf('Expected status deleted') + 'Expected status deleted' ); $this->assertTrue(in_array( diff --git a/tests/Functional/FlusherDecorator.php b/tests/Functional/FlusherDecorator.php index d2aef2c..f68b903 100644 --- a/tests/Functional/FlusherDecorator.php +++ b/tests/Functional/FlusherDecorator.php @@ -13,6 +13,7 @@ public function __construct( private Flusher $flusher ) {} + #[\Override] public function flush(): void { $this->flusher->flush(); From 20b211afd45f1697388bca19bb06fc40ac8a6fb2 Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:30:09 +0600 Subject: [PATCH 074/130] Fix variable name in RenewAuthToken handler Correct the variable name comment to reflect the accurate variable used in the code. This change clarifies the code by ensuring the comment and actual variable name are consistent, enhancing maintainability and readability. Signed-off-by: mesilov --- src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index fcea341..5f1bbc6 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -39,7 +39,7 @@ public function handle(Command $command): void $bitrix24Account = $this->getSingleAccountByMemberId($command->renewedAuthToken->domain, $command->renewedAuthToken->memberId,Bitrix24AccountStatus::active,$command->bitrix24UserId); /** - * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $targetAccount + * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $bitrix24Account */ $bitrix24Account->renewAuthToken($command->renewedAuthToken); From ff81205d45814787a28f4ab1d35a77d152b438ed Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:32:00 +0600 Subject: [PATCH 075/130] Update Composer flags and add specific package update Change COMPOSER_FLAGS to use "prefer-dist" for general updates while ensuring bitrix24/b24-php-sdk uses "prefer-source" for more detailed control. This adjustment aims to optimize dependency handling and improve build efficiency. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index 497e276..4c98a0b 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -5,7 +5,7 @@ on: pull_request: env: - COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-source" + COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist" jobs: tests: @@ -35,6 +35,7 @@ jobs: - name: "Install dependencies" run: | composer update ${{ env.COMPOSER_FLAGS }} + composer update bitrix24/b24-php-sdk --prefer-source - name: "run unit tests" run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" From 8fcc00d84dc0834857c215b45b3b118fef4d1f78 Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:35:09 +0600 Subject: [PATCH 076/130] Reorder composer update commands in CI workflow Move the general composer update command to follow the specific package update in the CI configuration. This ensures that the more specific update of the bitrix24/b24-php-sdk package occurs first for clarity and task separation. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index 4c98a0b..8ac2c2c 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -34,8 +34,8 @@ jobs: - name: "Install dependencies" run: | - composer update ${{ env.COMPOSER_FLAGS }} composer update bitrix24/b24-php-sdk --prefer-source + composer update ${{ env.COMPOSER_FLAGS }} - name: "run unit tests" run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" From c7ec28e34a25ac1fadb410a5444e752f9ec864b1 Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:40:48 +0600 Subject: [PATCH 077/130] Reorder composer update commands. Switched the order of composer update commands to ensure that environment-based flags are processed before specific package updates. This change maintains the configuration's flexibility while ensuring dependencies are correctly managed. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index 8ac2c2c..d4e3c55 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -34,8 +34,9 @@ jobs: - name: "Install dependencies" run: | - composer update bitrix24/b24-php-sdk --prefer-source composer update ${{ env.COMPOSER_FLAGS }} + composer clear-cache + composer update bitrix24/b24-php-sdk --prefer-source - name: "run unit tests" run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" From b81e3751803a71cdec01f950244fe4c9393cae55 Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:43:01 +0600 Subject: [PATCH 078/130] Reorder composer update commands. Switched the order of composer update commands to ensure that environment-based flags are processed before specific package updates. This change maintains the configuration's flexibility while ensuring dependencies are correctly managed. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index d4e3c55..a827b1d 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -35,8 +35,7 @@ jobs: - name: "Install dependencies" run: | composer update ${{ env.COMPOSER_FLAGS }} - composer clear-cache - composer update bitrix24/b24-php-sdk --prefer-source + composer update bitrix24/b24-php-sdk --prefer-source --no-cache - name: "run unit tests" run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" From bfd62569ec986f05fbee80af074670e21b23ee8d Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:46:56 +0600 Subject: [PATCH 079/130] Add step to install b24-php-sdk from source This commit introduces an additional step in the GitHub Actions workflow to ensure the bitrix24/b24-php-sdk package is installed directly from source. This change is executed with options to prefer source installation and disable cache usage, which aids in maintaining the latest version of the package when running unit tests. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index a827b1d..f13b9c6 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -37,6 +37,10 @@ jobs: composer update ${{ env.COMPOSER_FLAGS }} composer update bitrix24/b24-php-sdk --prefer-source --no-cache + - name: "Install b24-php-sdk from source" + run: | + composer update bitrix24/b24-php-sdk --prefer-source --no-cache --ansi --no-interaction --no-progress + - name: "run unit tests" run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" From 28667e6b6f21e1add727bfb4e4342afc0f22d58d Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:49:55 +0600 Subject: [PATCH 080/130] Update SDK installation method in GitHub Actions workflow Revised the method for installing the b24-php-sdk in the unit tests GitHub Actions workflow from 'composer update' to 'composer remove' followed by 'composer require'. This ensures a cleaner and more reliable installation from source, eliminating any potential issues with cached dependencies. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index f13b9c6..8107504 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -39,7 +39,8 @@ jobs: - name: "Install b24-php-sdk from source" run: | - composer update bitrix24/b24-php-sdk --prefer-source --no-cache --ansi --no-interaction --no-progress + composer remove bitrix24/b24-php-sdk --no-update + composer require bitrix24/b24-php-sdk --prefer-source --no-cache --ansi --no-interaction --no-progress - name: "run unit tests" run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" From 7059b849ac1335ff70288b8a678ed9771b1c812f Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 09:57:25 +0600 Subject: [PATCH 081/130] Update SDK installation method in GitHub Actions workflow Revised the method for installing the b24-php-sdk in the unit tests GitHub Actions workflow from 'composer update' to 'composer remove' followed by 'composer require'. This ensures a cleaner and more reliable installation from source, eliminating any potential issues with cached dependencies. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index 8107504..3a69990 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -35,12 +35,12 @@ jobs: - name: "Install dependencies" run: | composer update ${{ env.COMPOSER_FLAGS }} - composer update bitrix24/b24-php-sdk --prefer-source --no-cache + composer update bitrix24/b24phpsdk --prefer-source --no-cache - name: "Install b24-php-sdk from source" run: | - composer remove bitrix24/b24-php-sdk --no-update - composer require bitrix24/b24-php-sdk --prefer-source --no-cache --ansi --no-interaction --no-progress + composer remove bitrix24/b24phpsdk --no-update + composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress - name: "run unit tests" run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" From 84568ed050fd122543f8da5b08e7655babf4ea0b Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 10:10:37 +0600 Subject: [PATCH 082/130] Update composer flags and install b24-php-sdk from source Changed COMPOSER_FLAGS to prefer-dist to optimize dependency installation. Added steps to remove and require b24-php-sdk with prefer-source to ensure the latest source code is used. This configuration enhances the reliability of the workflow during functional tests. Signed-off-by: mesilov --- .github/workflows/tests-functional.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 760c746..8b69318 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -5,7 +5,7 @@ on: pull_request: env: - COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-source" + COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist" DATABASE_HOST: localhost DATABASE_USER: b24phpLibTest DATABASE_PASSWORD: b24phpLibTest @@ -58,6 +58,11 @@ jobs: run: | composer update ${{ env.COMPOSER_FLAGS }} + - name: "Install b24-php-sdk from source" + run: | + composer remove bitrix24/b24phpsdk --no-update + composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress + - name: "Wait for PostgreSQL to be ready" run: | until pg_isready -h localhost -p 5432 -U user; do From d68466180454ed072b234c6af5787ee338e09796 Mon Sep 17 00:00:00 2001 From: mesilov Date: Tue, 3 Dec 2024 10:13:34 +0600 Subject: [PATCH 083/130] Fix b24phpsdk installation naming and add to lint workflow Corrected the naming of "b24phpsdk" installation steps in unit and functional test workflows. Added missing installation steps for "b24phpsdk" in the lint-phpstan workflow to ensure consistent dependency management across all workflows. Signed-off-by: mesilov --- .github/workflows/lint-phpstan.yml | 5 +++++ .github/workflows/tests-functional.yml | 4 ++-- .github/workflows/tests-unit.yml | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/lint-phpstan.yml b/.github/workflows/lint-phpstan.yml index 9cf8ab2..546cda5 100644 --- a/.github/workflows/lint-phpstan.yml +++ b/.github/workflows/lint-phpstan.yml @@ -37,6 +37,11 @@ jobs: if: ${{ matrix.dependencies == 'highest' }} run: "composer update --no-interaction --no-progress --no-suggest" + - name: "Install b24phpsdk from source" + run: | + composer remove bitrix24/b24phpsdk --no-update + composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress + - name: "PHPStan" run: "vendor/bin/phpstan --memory-limit=2G analyse" diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 8b69318..411b0d4 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -58,10 +58,10 @@ jobs: run: | composer update ${{ env.COMPOSER_FLAGS }} - - name: "Install b24-php-sdk from source" + - name: "Install b24phpsdk from source" run: | composer remove bitrix24/b24phpsdk --no-update - composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress + composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress - name: "Wait for PostgreSQL to be ready" run: | diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index 3a69990..135c109 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -37,7 +37,7 @@ jobs: composer update ${{ env.COMPOSER_FLAGS }} composer update bitrix24/b24phpsdk --prefer-source --no-cache - - name: "Install b24-php-sdk from source" + - name: "Install b24phpsdk from source" run: | composer remove bitrix24/b24phpsdk --no-update composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress From ff5fa2d3618b1b276957b47bef9b4c9dd8504381 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 5 Dec 2024 00:16:35 +0600 Subject: [PATCH 084/130] Refactor and streamline codebase Removed unnecessary imports and redundant code to streamline multiple files. Improved compliance with coding standards by making syntax corrections and enforcing consistent code formatting. Additionally, added a Composer license checker configuration to manage dependencies. Signed-off-by: mesilov --- .allowed-licenses.php | 14 ++++++ .php-cs-fixer.dist.php | 17 ++++--- Makefile | 8 ++-- composer.json | 5 ++ src/AggregateRoot.php | 9 +--- .../Entity/Bitrix24Account.php | 5 +- .../Doctrine/Bitrix24AccountRepository.php | 21 ++++---- src/Bitrix24Accounts/ReadModel/Fetcher.php | 44 ++++++++--------- .../UseCase/ChangeDomainUrl/Command.php | 6 +-- .../UseCase/ChangeDomainUrl/Handler.php | 16 +++---- .../UseCase/InstallFinish/Command.php | 12 ++--- .../UseCase/InstallFinish/Handler.php | 6 +-- .../UseCase/RenewAuthToken/Command.php | 8 ++-- .../UseCase/RenewAuthToken/Handler.php | 48 +++++++++++-------- .../UseCase/Uninstall/Handler.php | 1 - src/Services/Flusher.php | 2 +- 16 files changed, 113 insertions(+), 109 deletions(-) create mode 100644 .allowed-licenses.php diff --git a/.allowed-licenses.php b/.allowed-licenses.php new file mode 100644 index 0000000..3b28e83 --- /dev/null +++ b/.allowed-licenses.php @@ -0,0 +1,14 @@ +addLicenses( + // And other licenses you wish to allow. + 'MIT', + 'Apache-2.0', + 'BSD-3-Clause', + ) + ->build(); \ No newline at end of file diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 9e5fcfd..3508ea9 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -1,15 +1,20 @@ in(__DIR__ . '/src'); +$finder = Finder::create() + ->in(__DIR__.'/src'); -return (new PhpCsFixer\Config()) - ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) - ->setCacheFile(__DIR__ . '/.php-cs-fixer.cache') +return (new Config()) + ->setParallelConfig(ParallelConfigFactory::detect()) + ->setCacheFile(__DIR__.'/.php-cs-fixer.cache') ->setFinder($finder) ->setRules([ '@Symfony' => true, '@DoctrineAnnotation' => true, '@PhpCsFixer' => true, - ]); \ No newline at end of file + 'phpdoc_to_comment' => false, + ]); diff --git a/Makefile b/Makefile index 9c2bf09..31047e5 100644 --- a/Makefile +++ b/Makefile @@ -64,9 +64,11 @@ php-cli-bash: composer-install: @echo "install dependencies…" docker-compose run --rm php-cli composer install + composer-update: @echo "update dependencies…" docker-compose run --rm php-cli composer update + composer-dumpautoload: docker-compose run --rm php-cli composer dumpautoload # вызов composer с любыми параметрами @@ -76,6 +78,9 @@ composer-dumpautoload: composer: docker-compose run --rm php-cli composer $(filter-out $@,$(MAKECMDGOALS)) +# check allowed licenses +lint-allowed-licenses: + vendor/bin/composer-license-checker # linters lint-phpstan: docker-compose run --rm php-cli php vendor/bin/phpstan analyse --memory-limit 2G @@ -90,12 +95,10 @@ lint-cs-fixer-fix: # unit-tests test-run-unit: - docker-compose run --rm php-cli composer update bitrix24/b24-php-sdk --prefer-source docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox # functional-tests, work with test database test-run-functional: debug-print-env - docker-compose run --rm php-cli composer update bitrix24/b24-php-sdk --prefer-source docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:update --dump-sql @@ -103,7 +106,6 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli composer update bitrix24/b24-php-sdk --prefer-source docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testListReturnsPaginatedResults' tests/Functional/Bitrix24Accounts/FetcherTest.php schema-drop: diff --git a/composer.json b/composer.json index c478d22..4a12145 100644 --- a/composer.json +++ b/composer.json @@ -27,6 +27,10 @@ "sort-packages": true, "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true + }, + "preferred-install": { + "*": "dist", + "bitrix24/b24phpsdk": "source" } }, "require": { @@ -55,6 +59,7 @@ "symfony/dotenv": "^7" }, "require-dev": { + "lendable/composer-license-checker": "^1.2", "friendsofphp/php-cs-fixer": "^3.64", "monolog/monolog": "^3", "fakerphp/faker": "^1", diff --git a/src/AggregateRoot.php b/src/AggregateRoot.php index ea94605..abb2be6 100644 --- a/src/AggregateRoot.php +++ b/src/AggregateRoot.php @@ -3,17 +3,11 @@ namespace Bitrix24\Lib; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; -use Symfony\Contracts\EventDispatcher\Event; class AggregateRoot implements AggregateRootEventsEmitterInterface { protected array $events = []; - public function getEvents(): array - { - return $this->events; - } - #[\Override] public function emitEvents(): array { @@ -22,5 +16,4 @@ public function emitEvents(): array return $events; } - -} \ No newline at end of file +} diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index ace860a..81aff19 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -1,4 +1,5 @@ comment; } - private function addAccountCreatedEventIfNeeded(bool $isEmitCreatedEvent): void { if ($isEmitCreatedEvent) { diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index d095525..8959864 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -13,7 +13,6 @@ use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; -use Override; use Symfony\Component\Uid\Uuid; class Bitrix24AccountRepository extends EntityRepository implements Bitrix24AccountRepositoryInterface @@ -29,21 +28,20 @@ public function __construct( * * @throws Bitrix24AccountNotFoundException */ - #[Override] + #[\Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { $account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); - if (null === $account || $account->getStatus() === Bitrix24AccountStatus::deleted) { + if (null === $account || Bitrix24AccountStatus::deleted === $account->getStatus()) { throw new Bitrix24AccountNotFoundException( sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122()) ); } - return $account; } - #[Override] + #[\Override] public function save(Bitrix24AccountInterface $bitrix24Account): void { $this->getEntityManager()->persist($bitrix24Account); @@ -54,7 +52,7 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void * * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function findByMemberId( string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, @@ -83,7 +81,7 @@ public function findByMemberId( return $this->findBy($criteria); } - #[Override] + #[\Override] public function delete(Uuid $uuid): void { $bitrix24Account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); @@ -108,7 +106,7 @@ public function delete(Uuid $uuid): void $this->save($bitrix24Account); } - public function findAllActive(int|null $limit = null, int|null $offset = null): array + public function findAllActive(?int $limit = null, ?int $offset = null): array { return $this->getEntityManager()->getRepository(Bitrix24Account::class)->findBy( [ @@ -124,12 +122,13 @@ public function findAllActive(int|null $limit = null, int|null $offset = null): * @param non-empty-string $applicationToken * * @phpstan-return array + * * @throws InvalidArgumentException */ #[\Override] public function findByApplicationToken(string $applicationToken): array { - if ($applicationToken === '') { + if ('' === $applicationToken) { throw new InvalidArgumentException('application token cannot be an empty string'); } @@ -145,7 +144,7 @@ public function findByApplicationToken(string $applicationToken): array * * @phpstan-return Bitrix24AccountInterface&AggregateRootEventsEmitterInterface */ - #[Override] + #[\Override] public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterface { if ('' === trim($memberId)) { @@ -168,7 +167,7 @@ public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterf * * @throws InvalidArgumentException */ - #[Override] + #[\Override] public function findByDomain( string $domainUrl, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, diff --git a/src/Bitrix24Accounts/ReadModel/Fetcher.php b/src/Bitrix24Accounts/ReadModel/Fetcher.php index 0430f40..c3b3fc4 100644 --- a/src/Bitrix24Accounts/ReadModel/Fetcher.php +++ b/src/Bitrix24Accounts/ReadModel/Fetcher.php @@ -4,42 +4,38 @@ namespace Bitrix24\Lib\Bitrix24Accounts\ReadModel; -use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Doctrine\ORM\EntityManagerInterface; -use Knp\Component\Pager\Event\Subscriber\Paginate\Callback\CallbackPagination; use Knp\Component\Pager\Pagination\PaginationInterface; use Knp\Component\Pager\PaginatorInterface; + class Fetcher { public function __construct( private readonly EntityManagerInterface $em, - private readonly PaginatorInterface $paginator) - { - } + private readonly PaginatorInterface $paginator + ) {} public function list( int $page, int $size - ): PaginationInterface - { - - /* $queryBuilder = $this->em->getConnection()->createQueryBuilder() - ->select( - 'b24account.id as id', - 'b24account.status as status', - 'b24account.member_id as member_id', - 'b24account.domain_url as domain_url', - 'b24account.application_version as application_version', - 'b24account.created_at_utc as created_at', - 'b24account.updated_at_utc as updated_at', - ) - ->from('bitrix24account', 'b24account') - ->orderBy('b24account.created_at_utc', 'DESC'); + ): PaginationInterface { + /* $queryBuilder = $this->em->getConnection()->createQueryBuilder() + ->select( + 'b24account.id as id', + 'b24account.status as status', + 'b24account.member_id as member_id', + 'b24account.domain_url as domain_url', + 'b24account.application_version as application_version', + 'b24account.created_at_utc as created_at', + 'b24account.updated_at_utc as updated_at', + ) + ->from('bitrix24account', 'b24account') + ->orderBy('b24account.created_at_utc', 'DESC'); */ - // var_dump($queryBuilder->getMaxResults()); - $query = $this->em->createQuery("SELECT b24account FROM Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account b24account"); + // var_dump($queryBuilder->getMaxResults()); + $query = $this->em->createQuery('SELECT b24account FROM Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account b24account'); return $this->paginator->paginate($query, $page, $size); - // return $this->paginator->paginate($queryBuilder->getSQL(), $page, $size); + // return $this->paginator->paginate($queryBuilder->getSQL(), $page, $size); } -} \ No newline at end of file +} diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index c1789b7..772d7e8 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -15,7 +15,5 @@ public function __construct( * @var non-empty-string $newDomainUrlHost */ public string $newDomainUrlHost - ) - { - } -} \ No newline at end of file + ) {} +} diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index 072f616..7f31bff 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -5,22 +5,18 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl; use Bitrix24\Lib\Services\Flusher; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Psr\Log\LoggerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, + private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) - { - } + private Flusher $flusher, + private LoggerInterface $logger + ) {} public function handle(Command $command): void { @@ -35,7 +31,7 @@ public function handle(Command $command): void $this->bitrix24AccountRepository->save($account); $this->flusher->flush(); // todo выяснить почему он не видит объединение типов - /** @phpstan-ignore-next-line */ + // @phpstan-ignore-next-line foreach ($account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } @@ -43,4 +39,4 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.ChangeDomainUrl.Finish'); } -} \ No newline at end of file +} diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index a5f66e6..b866b25 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -4,18 +4,12 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; -use Bitrix24\SDK\Core\Credentials\AuthToken; -use Bitrix24\SDK\Core\Credentials\Scope; -use Symfony\Component\Uid\Uuid; - readonly class Command { public function __construct( public string $applicationToken, public string $memberId, public string $domainUrl, - public ?int $bitrix24UserId, - ) - { - } -} \ No newline at end of file + public ?int $bitrix24UserId, + ) {} +} diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 054267f..35e9916 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -4,7 +4,6 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; @@ -39,11 +38,10 @@ public function handle(Command $command): void 'b24_user_id' => $command->bitrix24UserId, ]); - /** * @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ - $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId,Bitrix24AccountStatus::new, $command->bitrix24UserId); + $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId, Bitrix24AccountStatus::new, $command->bitrix24UserId); $bitrix24Account->applicationInstalled($command->applicationToken); @@ -56,7 +54,7 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.InstallFinish.Finish'); } - public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, int|null $bitrix24UserId): Bitrix24AccountInterface + public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, ?int $bitrix24UserId): Bitrix24AccountInterface { $accounts = $this->bitrix24AccountRepository->findByMemberId( $memberId, diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php index 3f7fdc1..a71666c 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php @@ -10,8 +10,6 @@ { public function __construct( public RenewedAuthToken $renewedAuthToken, - public ?int $bitrix24UserId = null, - ) - { - } -} \ No newline at end of file + public ?int $bitrix24UserId = null, + ) {} +} diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index 5f1bbc6..b5ebdda 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -16,13 +16,11 @@ readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, + private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) - { - } + private Flusher $flusher, + private LoggerInterface $logger + ) {} /** * @throws MultipleBitrix24AccountsFoundException @@ -32,15 +30,18 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.RenewAuthToken.start', [ 'domain_url' => $command->renewedAuthToken->domain, 'member_id' => $command->renewedAuthToken->memberId, - 'bitrix24_user_id' => $command->bitrix24UserId + 'bitrix24_user_id' => $command->bitrix24UserId, ]); - // get all active bitrix24 accounts - $bitrix24Account = $this->getSingleAccountByMemberId($command->renewedAuthToken->domain, $command->renewedAuthToken->memberId,Bitrix24AccountStatus::active,$command->bitrix24UserId); + $bitrix24Account = $this->getSingleAccountByMemberId( + $command->renewedAuthToken->domain, + $command->renewedAuthToken->memberId, + Bitrix24AccountStatus::active, + $command->bitrix24UserId + ); - /** - * @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $bitrix24Account - */ + // Bitrix24Account extends AggregateRoot and implement AggregateRootEventsEmitterInterface + /** @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ $bitrix24Account->renewAuthToken($command->renewedAuthToken); $this->bitrix24AccountRepository->save($bitrix24Account); @@ -52,26 +53,35 @@ public function handle(Command $command): void $this->logger->debug('Bitrix24Accounts.RenewAuthToken.finish'); } - public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, int|null $bitrix24UserId): Bitrix24AccountInterface - { + /** + * @throws MultipleBitrix24AccountsFoundException + */ + public function getSingleAccountByMemberId( + string $domainUrl, + string $memberId, + Bitrix24AccountStatus $bitrix24AccountStatus, + ?int $bitrix24UserId + ): Bitrix24AccountInterface { $accounts = $this->bitrix24AccountRepository->findByMemberId( $memberId, $bitrix24AccountStatus, $bitrix24UserId ); - if ($bitrix24UserId === null && count($accounts) > 1) { + if (null === $bitrix24UserId && count($accounts) > 1) { throw new MultipleBitrix24AccountsFoundException( - sprintf('updating auth token failure - for domain %s with member id %s found multiple active accounts, try pass bitrix24_user_id in command', + sprintf( + 'updating auth token failure - for domain %s with member id %s found multiple active accounts, try pass bitrix24_user_id in command', $domainUrl, $memberId ) ); } - if ($bitrix24UserId !== null && count($accounts) > 1) { + if (null !== $bitrix24UserId && count($accounts) > 1) { throw new MultipleBitrix24AccountsFoundException( - sprintf('updating auth token failure - for domain %s with member id %s and bitrix24 user id %s found multiple active accounts', + sprintf( + 'updating auth token failure - for domain %s with member id %s and bitrix24 user id %s found multiple active accounts', $domainUrl, $memberId, $bitrix24UserId @@ -81,4 +91,4 @@ public function getSingleAccountByMemberId(string $domainUrl, string $memberId, return $accounts[0]; } -} \ No newline at end of file +} diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 5c72473..76c1eac 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -4,7 +4,6 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall; -use Bitrix24\Lib\AggregateRoot; use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; diff --git a/src/Services/Flusher.php b/src/Services/Flusher.php index 292e7d4..0d47faa 100644 --- a/src/Services/Flusher.php +++ b/src/Services/Flusher.php @@ -14,4 +14,4 @@ public function flush(): void { $this->em->flush(); } -} \ No newline at end of file +} From a70123d7d482071ff49799a316256830227693c1 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 5 Dec 2024 00:18:59 +0600 Subject: [PATCH 085/130] Remove redundant b24phpsdk source installation steps. The steps for installing b24phpsdk from source were unnecessary and have been removed from the unit tests, functional tests, and PHPStan lint workflows. This simplification should reduce maintenance overhead and speed up the workflow execution times. Signed-off-by: mesilov --- .github/workflows/lint-phpstan.yml | 5 ----- .github/workflows/tests-functional.yml | 5 ----- .github/workflows/tests-unit.yml | 6 ------ 3 files changed, 16 deletions(-) diff --git a/.github/workflows/lint-phpstan.yml b/.github/workflows/lint-phpstan.yml index 546cda5..9cf8ab2 100644 --- a/.github/workflows/lint-phpstan.yml +++ b/.github/workflows/lint-phpstan.yml @@ -37,11 +37,6 @@ jobs: if: ${{ matrix.dependencies == 'highest' }} run: "composer update --no-interaction --no-progress --no-suggest" - - name: "Install b24phpsdk from source" - run: | - composer remove bitrix24/b24phpsdk --no-update - composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress - - name: "PHPStan" run: "vendor/bin/phpstan --memory-limit=2G analyse" diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 411b0d4..244ba73 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -58,11 +58,6 @@ jobs: run: | composer update ${{ env.COMPOSER_FLAGS }} - - name: "Install b24phpsdk from source" - run: | - composer remove bitrix24/b24phpsdk --no-update - composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress - - name: "Wait for PostgreSQL to be ready" run: | until pg_isready -h localhost -p 5432 -U user; do diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index 135c109..91ada7d 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -35,12 +35,6 @@ jobs: - name: "Install dependencies" run: | composer update ${{ env.COMPOSER_FLAGS }} - composer update bitrix24/b24phpsdk --prefer-source --no-cache - - - name: "Install b24phpsdk from source" - run: | - composer remove bitrix24/b24phpsdk --no-update - composer require bitrix24/b24phpsdk --prefer-source --no-cache --ansi --no-interaction --no-progress - name: "run unit tests" run: "php vendor/bin/phpunit --testsuite=unit_tests --display-warnings --testdox" From a2b6dfd814dedc443dc0e529ee9da78604a7f2a3 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 5 Dec 2024 00:24:33 +0600 Subject: [PATCH 086/130] Remove prefer-dist flag from Composer command The prefer-dist flag has been removed from the COMPOSER_FLAGS in the unit test workflow configuration. This change allows for potentially more up-to-date installations by not limiting downloads to distribution packages. This can help ensure that the latest code is being tested. Signed-off-by: mesilov --- .github/workflows/tests-unit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests-unit.yml b/.github/workflows/tests-unit.yml index 91ada7d..c714207 100644 --- a/.github/workflows/tests-unit.yml +++ b/.github/workflows/tests-unit.yml @@ -5,7 +5,7 @@ on: pull_request: env: - COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist" + COMPOSER_FLAGS: "--ansi --no-interaction --no-progress" jobs: tests: From 3b3104590015a88dae78e0606140ecdf878412e6 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 5 Dec 2024 00:25:59 +0600 Subject: [PATCH 087/130] Remove prefer-dist from COMPOSER_FLAGS in CI workflow. Eliminating the --prefer-dist option can reduce reliance on distribution archives, allowing for more consistent test execution. This change aims to enhance the flexibility and potential versions available during the dependency resolution in the CI pipeline. Signed-off-by: mesilov --- .github/workflows/tests-functional.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 244ba73..2227491 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -5,7 +5,7 @@ on: pull_request: env: - COMPOSER_FLAGS: "--ansi --no-interaction --no-progress --prefer-dist" + COMPOSER_FLAGS: "--ansi --no-interaction --no-progress" DATABASE_HOST: localhost DATABASE_USER: b24phpLibTest DATABASE_PASSWORD: b24phpLibTest From f697703e64cf9a685cd630cfbc53987f495a5e2c Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 5 Dec 2024 00:36:32 +0600 Subject: [PATCH 088/130] Remove xdebug from PHPUnit command in Makefile The xdebug extension is no longer started with the PHPUnit command used for running functional tests. This change reduces overhead and improves performance during test execution. Signed-off-by: mesilov --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 31047e5..373bd26 100644 --- a/Makefile +++ b/Makefile @@ -102,7 +102,7 @@ test-run-functional: debug-print-env docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:create docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:update --dump-sql - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox + docker-compose run --rm php-cli php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env From 17555c1bdea80083124affc885741a9d617ebec0 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 5 Dec 2024 00:42:36 +0600 Subject: [PATCH 089/130] Add GitHub workflow for license checking This commit introduces a new GitHub Action workflow file named `license-check.yml` that checks for allowed licenses during code pushes and pull requests. It includes steps to set up PHP environments with specified versions and extensions, install highest or lowest dependencies, and run a license verification script. The workflow matrix supports running the checks on multiple PHP versions, ensuring license compliance across different environments. Signed-off-by: mesilov --- .github/workflows/license-check.yml | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 .github/workflows/license-check.yml diff --git a/.github/workflows/license-check.yml b/.github/workflows/license-check.yml new file mode 100644 index 0000000..7bbf603 --- /dev/null +++ b/.github/workflows/license-check.yml @@ -0,0 +1,51 @@ +name: "Allowed licenses checks" +on: + push: + pull_request: + +jobs: + static-analysis: + name: "composer-license-checker" + runs-on: ${{ matrix.operating-system }} + + strategy: + fail-fast: false + matrix: + php-version: + - "8.2" + - "8.3" + dependencies: [ highest ] + operating-system: [ ubuntu-latest] + + steps: + - name: "Checkout" + uses: "actions/checkout@v2" + + - name: "Install PHP" + uses: "shivammathur/setup-php@v2" + with: + coverage: "none" + php-version: "${{ matrix.php-version }}" + extensions: json, bcmath, curl, intl, mbstring + tools: composer:v2 + + - name: "Install lowest dependencies" + if: ${{ matrix.dependencies == 'lowest' }} + run: "composer update --prefer-lowest --no-interaction --no-progress --no-suggest" + + - name: "Install highest dependencies" + if: ${{ matrix.dependencies == 'highest' }} + run: "composer update --no-interaction --no-progress --no-suggest" + + - name: "composer-license-checker" + run: "make lint-allowed-licenses" + + - name: "is allowed licenses check succeeded" + if: ${{ success() }} + run: | + echo '✅ allowed licenses check pass, congratulations!' + + - name: "is allowed licenses check failed" + if: ${{ failure() }} + run: | + echo '::error:: ❗️ allowed licenses check failed (╯°益°)╯彡┻━┻' \ No newline at end of file From bd63bbac68c75fc2b61e3a278caf588139424b86 Mon Sep 17 00:00:00 2001 From: mesilov Date: Thu, 5 Dec 2024 00:44:17 +0600 Subject: [PATCH 090/130] Remove PHP 8.2 from license check workflow The license check workflow configuration no longer includes PHP 8.2 in the version matrix. This change focuses testing on PHP 8.3 and aims to streamline the maintenance of the workflow. Signed-off-by: mesilov --- .github/workflows/license-check.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/license-check.yml b/.github/workflows/license-check.yml index 7bbf603..f628913 100644 --- a/.github/workflows/license-check.yml +++ b/.github/workflows/license-check.yml @@ -12,7 +12,6 @@ jobs: fail-fast: false matrix: php-version: - - "8.2" - "8.3" dependencies: [ highest ] operating-system: [ ubuntu-latest] From b1cdf4eb1a4f9bd49e033790bc3f94395f04ca6c Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 8 Dec 2024 02:02:03 +0300 Subject: [PATCH 091/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D1=87=D0=B8=D0=BD?= =?UTF-8?q?=D0=B8=D0=BB=20Fetcher=20=D1=82=D0=B5=D1=81=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entity/Bitrix24Account.php | 5 ---- .../Doctrine/Bitrix24AccountRepository.php | 1 - src/Bitrix24Accounts/ReadModel/Fetcher.php | 24 ++++++++----------- .../UseCase/Uninstall/Handler.php | 4 +++- .../Bitrix24Accounts/FetcherTest.php | 7 +----- 5 files changed, 14 insertions(+), 27 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 81aff19..e9f6408 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -89,11 +89,6 @@ public function getStatus(): Bitrix24AccountStatus return $this->status; } - public function setStatus(Bitrix24AccountStatus $bitrix24AccountStatus): void - { - $this->status = $bitrix24AccountStatus; - } - /** * @throws InvalidArgumentException */ diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 8959864..bed1bf4 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -102,7 +102,6 @@ public function delete(Uuid $uuid): void ); } - $bitrix24Account->setStatus(Bitrix24AccountStatus::deleted); $this->save($bitrix24Account); } diff --git a/src/Bitrix24Accounts/ReadModel/Fetcher.php b/src/Bitrix24Accounts/ReadModel/Fetcher.php index c3b3fc4..ac7676c 100644 --- a/src/Bitrix24Accounts/ReadModel/Fetcher.php +++ b/src/Bitrix24Accounts/ReadModel/Fetcher.php @@ -7,9 +7,9 @@ use Doctrine\ORM\EntityManagerInterface; use Knp\Component\Pager\Pagination\PaginationInterface; use Knp\Component\Pager\PaginatorInterface; - class Fetcher { + public function __construct( private readonly EntityManagerInterface $em, private readonly PaginatorInterface $paginator @@ -19,23 +19,19 @@ public function list( int $page, int $size ): PaginationInterface { - /* $queryBuilder = $this->em->getConnection()->createQueryBuilder() + $qb = $this->em->createQueryBuilder() ->select( 'b24account.id as id', 'b24account.status as status', - 'b24account.member_id as member_id', - 'b24account.domain_url as domain_url', - 'b24account.application_version as application_version', - 'b24account.created_at_utc as created_at', - 'b24account.updated_at_utc as updated_at', + 'b24account.memberId as member_id', + 'b24account.domainUrl as domain_url', + 'b24account.applicationVersion as application_version', + 'b24account.createdAt as created_at_utc', + 'b24account.updatedAt as updated_at_utc', ) - ->from('bitrix24account', 'b24account') - ->orderBy('b24account.created_at_utc', 'DESC'); - */ - // var_dump($queryBuilder->getMaxResults()); - $query = $this->em->createQuery('SELECT b24account FROM Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account b24account'); + ->from('Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account', 'b24account') + ->orderBy('b24account.createdAt', 'DESC'); - return $this->paginator->paginate($query, $page, $size); - // return $this->paginator->paginate($queryBuilder->getSQL(), $page, $size); + return $this->paginator->paginate($qb, $page, $size); } } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 76c1eac..1c2a4c2 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -40,13 +40,15 @@ public function handle(Command $command): void foreach ($accounts as $account) { $account->applicationUninstalled($command->applicationToken); $this->bitrix24AccountRepository->save($account); - $this->flusher->flush(); + foreach ($account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); } } + $this->flusher->flush(); + $this->logger->debug('Bitrix24Accounts.Uninstall.Finish'); } } diff --git a/tests/Functional/Bitrix24Accounts/FetcherTest.php b/tests/Functional/Bitrix24Accounts/FetcherTest.php index 5a71445..15e651b 100644 --- a/tests/Functional/Bitrix24Accounts/FetcherTest.php +++ b/tests/Functional/Bitrix24Accounts/FetcherTest.php @@ -19,7 +19,6 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Request; use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; class FetcherTest extends TestCase @@ -41,9 +40,6 @@ protected function setUp(): void $eventDispatcher = new EventDispatcher(); $eventDispatcher->addSubscriber(new PaginationSubscriber()); $eventDispatcher->addSubscriber(new SortableSubscriber()); - // dd(Request::createFromGlobals()); - new RequestStack(); - // Request::createFromGlobals() $requestArgumentAccess = new RequestArgumentAccess(new RequestStack()); $this->paginator = new Paginator($eventDispatcher, $requestArgumentAccess); $this->fetcher = new Fetcher($this->entityManager, $this->paginator); @@ -63,8 +59,7 @@ public function testListReturnsPaginatedResults(): void $size = 10; // Вызов метода list $pagination = $this->fetcher->list($page, $size); - // var_dump($result->getItems()); - // var_dump($result->count()); + // Проверка, что результат является экземпляром PaginationInterface $this->assertInstanceOf(PaginationInterface::class, $pagination); From be68b225709cd3e4ab54219169a95643d734cbb0 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 8 Dec 2024 17:44:16 +0300 Subject: [PATCH 092/130] =?UTF-8?q?-=20=D0=9F=D0=B5=D1=80=D0=B5=D0=BF?= =?UTF-8?q?=D0=B8=D1=81=D0=B0=D0=BB=20flusher=20=D0=B8=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=BF=D0=B8=D1=81=D0=B0=D0=BB=20=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D0=BA=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D1=82=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- .../UseCase/ChangeDomainUrl/Handler.php | 9 ++++---- .../UseCase/InstallStart/Handler.php | 8 +++---- .../UseCase/RenewAuthToken/Handler.php | 7 +++--- .../UseCase/Uninstall/Handler.php | 8 +------ src/Services/Flusher.php | 23 +++++++++++++++---- .../Bitrix24Accounts/FetcherTest.php | 2 +- .../UseCase/ChangeDomainUrl/HandlerTest.php | 6 ++--- .../UseCase/InstallFinish/HandlerTest.php | 5 ++-- .../UseCase/InstallStart/HandlerTest.php | 5 ++-- .../UseCase/RenewAuthToken/HandlerTest.php | 4 ++-- .../UseCase/Uninstall/HandlerTest.php | 9 ++++++-- 12 files changed, 52 insertions(+), 36 deletions(-) diff --git a/Makefile b/Makefile index 373bd26..28e6bab 100644 --- a/Makefile +++ b/Makefile @@ -106,7 +106,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testListReturnsPaginatedResults' tests/Functional/Bitrix24Accounts/FetcherTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testChangeDomainUrlWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index 7f31bff..a02af34 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -12,7 +12,6 @@ readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, private Flusher $flusher, private LoggerInterface $logger @@ -29,13 +28,15 @@ public function handle(Command $command): void foreach ($accounts as $account) { $account->changeDomainUrl($command->newDomainUrlHost); $this->bitrix24AccountRepository->save($account); - $this->flusher->flush(); + // $this->flusher->flush(); // todo выяснить почему он не видит объединение типов // @phpstan-ignore-next-line - foreach ($account->emitEvents() as $event) { + /* foreach ($account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); - } + }*/ + } + $this->flusher->flush(...$accounts); $this->logger->debug('Bitrix24Accounts.ChangeDomainUrl.Finish'); } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index 074e77a..a401b03 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -15,7 +15,6 @@ readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, private Flusher $flusher, private LoggerInterface $logger @@ -44,11 +43,12 @@ public function handle(Command $command): void true ); $this->bitrix24AccountRepository->save($bitrix24Account); - $this->flusher->flush(); + $this->flusher->flush($bitrix24Account); + // $this->flusher->flush(); + /*foreach ($bitrix24Account->emitEvents() as $event) { - foreach ($bitrix24Account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); - } + }*/ $this->logger->debug('Bitrix24Accounts.InstallStart.Finish'); } diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index b5ebdda..13d408c 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -16,7 +16,6 @@ readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, private Flusher $flusher, private LoggerInterface $logger @@ -45,10 +44,10 @@ public function handle(Command $command): void $bitrix24Account->renewAuthToken($command->renewedAuthToken); $this->bitrix24AccountRepository->save($bitrix24Account); - $this->flusher->flush(); - foreach ($bitrix24Account->emitEvents() as $event) { + $this->flusher->flush($bitrix24Account); + /* foreach ($bitrix24Account->emitEvents() as $event) { $this->eventDispatcher->dispatch($event); - } + }*/ $this->logger->debug('Bitrix24Accounts.RenewAuthToken.finish'); } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 1c2a4c2..f30e983 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -16,7 +16,6 @@ readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, private Flusher $flusher, private LoggerInterface $logger, @@ -40,14 +39,9 @@ public function handle(Command $command): void foreach ($accounts as $account) { $account->applicationUninstalled($command->applicationToken); $this->bitrix24AccountRepository->save($account); - - - foreach ($account->emitEvents() as $event) { - $this->eventDispatcher->dispatch($event); - } } + $this->flusher->flush(...$accounts); - $this->flusher->flush(); $this->logger->debug('Bitrix24Accounts.Uninstall.Finish'); } diff --git a/src/Services/Flusher.php b/src/Services/Flusher.php index 0d47faa..ec9af9e 100644 --- a/src/Services/Flusher.php +++ b/src/Services/Flusher.php @@ -4,14 +4,29 @@ namespace Bitrix24\Lib\Services; -use Doctrine\ORM\EntityManagerInterface; -final readonly class Flusher +use Bitrix24\Lib\AggregateRoot; +use Doctrine\ORM\EntityManagerInterface; +use Symfony\Component\EventDispatcher\EventDispatcher; +class Flusher { - public function __construct(private EntityManagerInterface $em) {} + private $em; + private $eventDispatcher; + public function __construct(EntityManagerInterface $em,EventDispatcher $eventDispatcher) { + $this->em = $em; + $this->eventDispatcher = $eventDispatcher; + } - public function flush(): void + public function flush(AggregateRoot ...$roots): void { $this->em->flush(); + + foreach ($roots as $root) { + $events = $root->emitEvents(); + foreach ($events as $event) { + var_dump($event); + $this->eventDispatcher->dispatch($event); + } + } } } diff --git a/tests/Functional/Bitrix24Accounts/FetcherTest.php b/tests/Functional/Bitrix24Accounts/FetcherTest.php index 15e651b..46698c9 100644 --- a/tests/Functional/Bitrix24Accounts/FetcherTest.php +++ b/tests/Functional/Bitrix24Accounts/FetcherTest.php @@ -43,7 +43,7 @@ protected function setUp(): void $requestArgumentAccess = new RequestArgumentAccess(new RequestStack()); $this->paginator = new Paginator($eventDispatcher, $requestArgumentAccess); $this->fetcher = new Fetcher($this->entityManager, $this->paginator); - $this->flusher = new Flusher($this->entityManager); + $this->flusher = new Flusher($this->entityManager,$eventDispatcher); $this->repository = new Bitrix24AccountRepository($this->entityManager); } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index a590319..b724574 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -48,11 +48,11 @@ class HandlerTest extends TestCase protected function setUp(): void { $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager); - $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->flusher = new Flusher($entityManager,$eventDispatcher); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); $this->handler = new Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler( - $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index d444316..2ea70ec 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -84,9 +84,10 @@ public function testFinishInstallationWithHappyPath(): void protected function setUp(): void { $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager); - $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->flusher = new Flusher($entityManager,$eventDispatcher); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); $this->handler = new Bitrix24Accounts\UseCase\InstallFinish\Handler( $this->eventDispatcher, $this->repository, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index f9df3f5..057ce05 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -52,11 +52,11 @@ class HandlerTest extends TestCase protected function setUp(): void { $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager); + $this->flusher = new Flusher($entityManager,$eventDispatcher); $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->handler = new Bitrix24Accounts\UseCase\InstallStart\Handler( - $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() @@ -156,6 +156,7 @@ public function testInstallStartHappyPath(): void 'Object not equals' ); + // var_dump($this->eventDispatcher->getOrphanedEvents()); $this->assertContains( Bitrix24AccountCreatedEvent::class, $this->eventDispatcher->getOrphanedEvents(), diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 7109cdd..fb775d0 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -49,11 +49,11 @@ class HandlerTest extends TestCase protected function setUp(): void { $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager); + $this->flusher = new Flusher($entityManager,$eventDispatcher); $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->handler = new Handler( - $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index d00bbec..c83dc18 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -25,6 +25,7 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; +use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Carbon\CarbonImmutable; use Override; use PHPUnit\Framework\Attributes\CoversClass; @@ -47,6 +48,10 @@ class HandlerTest extends TestCase private TraceableEventDispatcher $eventDispatcher; + /** + * @throws InvalidArgumentException + * @throws Bitrix24AccountNotFoundException + */ #[Test] public function testUninstallWithHappyPath(): void { @@ -97,12 +102,12 @@ protected function setUp(): void { $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager); + $this->flusher = new Flusher($entityManager, $eventDispatcher); $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->handler = new Bitrix24Accounts\UseCase\Uninstall\Handler( - $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger(), From 70f2c9fca5f47a446179097e7bee9bc017af3fd8 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Wed, 11 Dec 2024 01:07:10 +0300 Subject: [PATCH 093/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20url=20?= =?UTF-8?q?=D0=B4=D0=BE=D0=BC=D0=B5=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 3 --- Makefile | 2 +- src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php | 9 ++------- src/Services/Flusher.php | 7 +++---- .../UseCase/ChangeDomainUrl/HandlerTest.php | 5 ++--- .../UseCase/RenewAuthToken/HandlerTest.php | 2 +- 6 files changed, 9 insertions(+), 19 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 2227491..9db731a 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -39,9 +39,6 @@ jobs: POSTGRES_PASSWORD: b24phpLibTest POSTGRES_DB: b24phpLibTest DATABASE_HOST: localhost - DATABASE_USER: b24phpLibTest - DATABASE_PASSWORD: b24phpLibTest - DATABASE_NAME: b24phpLibTest steps: - name: "Checkout code" diff --git a/Makefile b/Makefile index 28e6bab..ad502d7 100644 --- a/Makefile +++ b/Makefile @@ -106,7 +106,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testChangeDomainUrlWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testChangeDomainUrlWithHappyPathForManyAccounts' tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index a02af34..e370b63 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -28,14 +28,9 @@ public function handle(Command $command): void foreach ($accounts as $account) { $account->changeDomainUrl($command->newDomainUrlHost); $this->bitrix24AccountRepository->save($account); - // $this->flusher->flush(); - // todo выяснить почему он не видит объединение типов - // @phpstan-ignore-next-line - /* foreach ($account->emitEvents() as $event) { - $this->eventDispatcher->dispatch($event); - }*/ - } + + //используется как оператор распаковки (splat operator) для передачи массива как отдельных аргументов: $this->flusher->flush(...$accounts); $this->logger->debug('Bitrix24Accounts.ChangeDomainUrl.Finish'); diff --git a/src/Services/Flusher.php b/src/Services/Flusher.php index ec9af9e..c16a8e2 100644 --- a/src/Services/Flusher.php +++ b/src/Services/Flusher.php @@ -7,12 +7,12 @@ use Bitrix24\Lib\AggregateRoot; use Doctrine\ORM\EntityManagerInterface; -use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class Flusher { private $em; private $eventDispatcher; - public function __construct(EntityManagerInterface $em,EventDispatcher $eventDispatcher) { + public function __construct(EntityManagerInterface $em,EventDispatcherInterface $eventDispatcher) { $this->em = $em; $this->eventDispatcher = $eventDispatcher; } @@ -20,11 +20,10 @@ public function __construct(EntityManagerInterface $em,EventDispatcher $eventDis public function flush(AggregateRoot ...$roots): void { $this->em->flush(); - foreach ($roots as $root) { $events = $root->emitEvents(); + var_dump($events); foreach ($events as $event) { - var_dump($event); $this->eventDispatcher->dispatch($event); } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index b724574..784aad2 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -26,10 +26,9 @@ use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; - +use Symfony\Component\EventDispatcher\EventDispatcher; /** * @internal */ @@ -50,8 +49,8 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$eventDispatcher); $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->flusher = new Flusher($entityManager,$this->eventDispatcher); $this->handler = new Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler( $this->repository, $this->flusher, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index fb775d0..e8369b1 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -28,7 +28,7 @@ use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Stopwatch\Stopwatch; /** From 9f1ee0c30e6bbe1efab1d78e8089f5c834a6d6d6 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 14 Dec 2024 00:13:22 +0300 Subject: [PATCH 094/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php | 7 ++----- src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php | 4 ---- src/Services/Flusher.php | 3 +-- .../Doctrine/Bitrix24AccountRepositoryTest.php | 5 ++++- .../Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php | 6 +++--- .../Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php | 4 ++-- .../UseCase/RenewAuthToken/HandlerTest.php | 6 +++--- .../Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php | 4 ++-- 8 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 35e9916..ab099c0 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -18,7 +18,6 @@ readonly class Handler { public function __construct( - private EventDispatcherInterface $eventDispatcher, private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, private Flusher $flusher, private LoggerInterface $logger @@ -46,10 +45,8 @@ public function handle(Command $command): void $bitrix24Account->applicationInstalled($command->applicationToken); $this->bitrix24AccountRepository->save($bitrix24Account); - $this->flusher->flush(); - foreach ($bitrix24Account->emitEvents() as $event) { - $this->eventDispatcher->dispatch($event); - } + $this->flusher->flush($bitrix24Account); + $this->logger->debug('Bitrix24Accounts.InstallFinish.Finish'); } diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index 13d408c..6551bc1 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -11,7 +11,6 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Psr\Log\LoggerInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; readonly class Handler { @@ -45,9 +44,6 @@ public function handle(Command $command): void $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush($bitrix24Account); - /* foreach ($bitrix24Account->emitEvents() as $event) { - $this->eventDispatcher->dispatch($event); - }*/ $this->logger->debug('Bitrix24Accounts.RenewAuthToken.finish'); } diff --git a/src/Services/Flusher.php b/src/Services/Flusher.php index c16a8e2..585360b 100644 --- a/src/Services/Flusher.php +++ b/src/Services/Flusher.php @@ -12,7 +12,7 @@ class Flusher { private $em; private $eventDispatcher; - public function __construct(EntityManagerInterface $em,EventDispatcherInterface $eventDispatcher) { + public function __construct(EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher) { $this->em = $em; $this->eventDispatcher = $eventDispatcher; } @@ -22,7 +22,6 @@ public function flush(AggregateRoot ...$roots): void $this->em->flush(); foreach ($roots as $root) { $events = $root->emitEvents(); - var_dump($events); foreach ($events as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php index cf6e12b..177ce15 100644 --- a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php +++ b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php @@ -28,6 +28,7 @@ use Carbon\CarbonImmutable; use Override; use PHPUnit\Framework\Attributes\CoversClass; +use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Uid\Uuid; #[CoversClass(Bitrix24AccountRepository::class)] @@ -73,6 +74,8 @@ protected function createBitrix24AccountRepositoryImplementation(): Bitrix24Acco #[Override] protected function createRepositoryFlusherImplementation(): TestRepositoryFlusherInterface { - return new FlusherDecorator(new Flusher(EntityManagerFactory::get())); + $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); + return new FlusherDecorator(new Flusher($entityManager, $eventDispatcher)); } } \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 2ea70ec..287db48 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -85,11 +85,11 @@ protected function setUp(): void { $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$eventDispatcher); $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager,$this->eventDispatcher); + $this->handler = new Bitrix24Accounts\UseCase\InstallFinish\Handler( - $this->eventDispatcher, $this->repository, $this->flusher, new NullLogger() diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 057ce05..add9878 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -53,9 +53,9 @@ protected function setUp(): void { $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$eventDispatcher); $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager,$this->eventDispatcher); $this->handler = new Bitrix24Accounts\UseCase\InstallStart\Handler( $this->repository, $this->flusher, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index e8369b1..39f806c 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -28,8 +28,8 @@ use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\EventDispatcher\EventDispatcher; /** * @internal @@ -50,9 +50,9 @@ protected function setUp(): void { $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$eventDispatcher); $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager,$this->eventDispatcher); $this->handler = new Handler( $this->repository, $this->flusher, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index c83dc18..da6e1f0 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -103,9 +103,9 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager, $eventDispatcher); - $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->flusher = new Flusher($entityManager, $this->eventDispatcher); $this->handler = new Bitrix24Accounts\UseCase\Uninstall\Handler( $this->repository, From 50733f5956d89f8a2d2c8c3673d25e6983ae27a7 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 15 Dec 2024 14:33:43 +0300 Subject: [PATCH 095/130] =?UTF-8?q?-=20=D0=98=D0=B7=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BD=D0=B5=D0=B9=D0=BC=D0=B8=D0=BD=D0=B3=20?= =?UTF-8?q?=D1=84=D0=B5=D1=82=D1=87=D0=B5=D1=80=D0=B0=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20=D0=B1=D0=B8=D1=82=D1=80=D0=B8=D0=BA=D1=8124=D0=B0=D0=BA?= =?UTF-8?q?=D0=BA=D0=B0=D1=83=D0=BD=D1=82=D0=B0.=20-=20=D0=94=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=20=D0=BD?= =?UTF-8?q?=D0=B0=20Command=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D1=86=D0=B5=D1=81=D1=81=D0=B0=20=D0=B7=D0=B0=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D1=88=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=83=D1=81=D1=82=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=BA=D0=B8.=20-=D0=98=D0=B7=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=BA=D1=81=D1=82?= =?UTF-8?q?=20=D1=81=20debug=20=D0=BD=D0=B0=20info=20=D0=B2=20=D1=8E=D0=B7?= =?UTF-8?q?=D0=BA=D0=B5=D0=B9=D1=81=D0=B0=D1=85=20=D1=85=D0=B5=D0=BD=D0=B4?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- ...Fetcher.php => Bitrix24AccountFetcher.php} | 2 +- .../UseCase/ChangeDomainUrl/Handler.php | 8 +- .../UseCase/InstallFinish/Command.php | 20 ++- .../UseCase/InstallFinish/Handler.php | 13 +- .../UseCase/InstallStart/Handler.php | 14 +- .../UseCase/RenewAuthToken/Handler.php | 9 +- .../UseCase/Uninstall/Handler.php | 15 +-- ...st.php => Bitrix24AccountsFetcherTest.php} | 40 +++++- .../UseCase/InstallFinish/CommandTest.php | 124 ++++++++++++++++++ 10 files changed, 216 insertions(+), 31 deletions(-) rename src/Bitrix24Accounts/ReadModel/{Fetcher.php => Bitrix24AccountFetcher.php} (97%) rename tests/Functional/Bitrix24Accounts/{FetcherTest.php => Bitrix24AccountsFetcherTest.php} (64%) create mode 100644 tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php diff --git a/Makefile b/Makefile index ad502d7..a21c7d6 100644 --- a/Makefile +++ b/Makefile @@ -106,7 +106,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testChangeDomainUrlWithHappyPathForManyAccounts' tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testEmptyDomainUrl' tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/ReadModel/Fetcher.php b/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php similarity index 97% rename from src/Bitrix24Accounts/ReadModel/Fetcher.php rename to src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php index ac7676c..b2a51c5 100644 --- a/src/Bitrix24Accounts/ReadModel/Fetcher.php +++ b/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php @@ -7,7 +7,7 @@ use Doctrine\ORM\EntityManagerInterface; use Knp\Component\Pager\Pagination\PaginationInterface; use Knp\Component\Pager\PaginatorInterface; -class Fetcher +class Bitrix24AccountFetcher { public function __construct( diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index e370b63..53246d3 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -19,7 +19,7 @@ public function __construct( public function handle(Command $command): void { - $this->logger->debug('Bitrix24Accounts.ChangeDomainUrl.start', [ + $this->logger->info('Bitrix24Accounts.ChangeDomainUrl.start', [ 'b24_domain_url_old' => $command->oldDomainUrlHost, 'b24_domain_url_new' => $command->newDomainUrlHost, ]); @@ -33,6 +33,10 @@ public function handle(Command $command): void //используется как оператор распаковки (splat operator) для передачи массива как отдельных аргументов: $this->flusher->flush(...$accounts); - $this->logger->debug('Bitrix24Accounts.ChangeDomainUrl.Finish'); + $this->logger->info('Bitrix24Accounts.ChangeDomainUrl.Finish', + [ + 'b24_domain_url_old' => $command->oldDomainUrlHost, + 'b24_domain_url_new' => $command->newDomainUrlHost, + ]); } } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index b866b25..74ce9c4 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; +use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; readonly class Command { public function __construct( @@ -11,5 +12,22 @@ public function __construct( public string $memberId, public string $domainUrl, public ?int $bitrix24UserId, - ) {} + ) { + $this->validate(); + } + + private function validate(): void + { + if (empty($this->applicationToken)) { + throw new InvalidArgumentException('Application token cannot be empty.'); + } + + if (empty($this->memberId)) { + throw new InvalidArgumentException('Member ID cannot be empty.'); + } + + if (empty($this->domainUrl)) { + throw new InvalidArgumentException('Domain URL cannot be empty.'); + } + } } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index ab099c0..bd8d043 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -30,16 +30,13 @@ public function __construct( */ public function handle(Command $command): void { - $this->logger->debug('Bitrix24Accounts.InstallFinish.start', [ + $this->logger->info('Bitrix24Accounts.InstallFinish.start', [ 'b24_domain_url' => $command->domainUrl, 'b24_member_id' => $command->memberId, 'b24_application_id' => $command->applicationToken, 'b24_user_id' => $command->bitrix24UserId, ]); - /** - * @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account - */ $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId, Bitrix24AccountStatus::new, $command->bitrix24UserId); $bitrix24Account->applicationInstalled($command->applicationToken); @@ -48,7 +45,13 @@ public function handle(Command $command): void $this->flusher->flush($bitrix24Account); - $this->logger->debug('Bitrix24Accounts.InstallFinish.Finish'); + $this->logger->info('Bitrix24Accounts.InstallFinish.Finish', + [ + 'b24_domain_url' => $command->domainUrl, + 'b24_member_id' => $command->memberId, + 'b24_application_id' => $command->applicationToken, + 'b24_user_id' => $command->bitrix24UserId, + ]); } public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, ?int $bitrix24UserId): Bitrix24AccountInterface diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index a401b03..b9d1f17 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -22,7 +22,7 @@ public function __construct( public function handle(Command $command): void { - $this->logger->debug('Bitrix24Accounts.InstallStart.start', [ + $this->logger->info('Bitrix24Accounts.InstallStart.start', [ 'id' => $command->uuid->toRfc4122(), 'domain_url' => $command->domainUrl, 'member_id' => $command->memberId, @@ -44,12 +44,12 @@ public function handle(Command $command): void ); $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush($bitrix24Account); - // $this->flusher->flush(); - /*foreach ($bitrix24Account->emitEvents() as $event) { - $this->eventDispatcher->dispatch($event); - }*/ - - $this->logger->debug('Bitrix24Accounts.InstallStart.Finish'); + $this->logger->info('Bitrix24Accounts.InstallStart.Finish', + [ + 'id' => $command->uuid->toRfc4122(), + 'domain_url' => $command->domainUrl, + 'member_id' => $command->memberId, + ]); } } diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index 6551bc1..ef3b465 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -25,7 +25,7 @@ public function __construct( */ public function handle(Command $command): void { - $this->logger->debug('Bitrix24Accounts.RenewAuthToken.start', [ + $this->logger->info('Bitrix24Accounts.RenewAuthToken.start', [ 'domain_url' => $command->renewedAuthToken->domain, 'member_id' => $command->renewedAuthToken->memberId, 'bitrix24_user_id' => $command->bitrix24UserId, @@ -45,7 +45,12 @@ public function handle(Command $command): void $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush($bitrix24Account); - $this->logger->debug('Bitrix24Accounts.RenewAuthToken.finish'); + $this->logger->info('Bitrix24Accounts.RenewAuthToken.finish', + [ + 'domain_url' => $command->renewedAuthToken->domain, + 'member_id' => $command->renewedAuthToken->memberId, + 'bitrix24_user_id' => $command->bitrix24UserId, + ]); } /** diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index f30e983..8c5ea1f 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -22,27 +22,26 @@ public function __construct( ) {} /** - * @throws Bitrix24AccountNotFoundException * @throws InvalidArgumentException */ public function handle(Command $command): void { - $this->logger->debug('Bitrix24Accounts.Uninstall.start', [ + $this->logger->info('Bitrix24Accounts.Uninstall.start', [ 'b24_application_token' => $command->applicationToken, ]); - /** - * @var AggregateRootEventsEmitterInterface[]|Bitrix24AccountInterface[] $accounts - */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); - + $accountsCount = count($accounts); foreach ($accounts as $account) { $account->applicationUninstalled($command->applicationToken); $this->bitrix24AccountRepository->save($account); } $this->flusher->flush(...$accounts); - - $this->logger->debug('Bitrix24Accounts.Uninstall.Finish'); + $this->logger->info('Bitrix24Accounts.Uninstall.Finish', + [ + 'accountsCount' => $accountsCount, + 'b24_application_token' => $command->applicationToken, + ]); } } diff --git a/tests/Functional/Bitrix24Accounts/FetcherTest.php b/tests/Functional/Bitrix24Accounts/Bitrix24AccountsFetcherTest.php similarity index 64% rename from tests/Functional/Bitrix24Accounts/FetcherTest.php rename to tests/Functional/Bitrix24Accounts/Bitrix24AccountsFetcherTest.php index 46698c9..2b4ad05 100644 --- a/tests/Functional/Bitrix24Accounts/FetcherTest.php +++ b/tests/Functional/Bitrix24Accounts/Bitrix24AccountsFetcherTest.php @@ -5,7 +5,7 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; -use Bitrix24\Lib\Bitrix24Accounts\ReadModel\Fetcher; +use Bitrix24\Lib\Bitrix24Accounts\ReadModel\Bitrix24AccountFetcher; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Tests\EntityManagerFactory; use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber; @@ -21,7 +21,7 @@ use Symfony\Component\HttpFoundation\RequestStack; use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; -class FetcherTest extends TestCase +class Bitrix24AccountsFetcherTest extends TestCase { private EntityManagerInterface $entityManager; @@ -29,7 +29,7 @@ class FetcherTest extends TestCase private Bitrix24AccountRepositoryInterface $repository; - private Fetcher $fetcher; + private Bitrix24AccountFetcher $fetcher; private Flusher $flusher; @@ -42,7 +42,7 @@ protected function setUp(): void $eventDispatcher->addSubscriber(new SortableSubscriber()); $requestArgumentAccess = new RequestArgumentAccess(new RequestStack()); $this->paginator = new Paginator($eventDispatcher, $requestArgumentAccess); - $this->fetcher = new Fetcher($this->entityManager, $this->paginator); + $this->fetcher = new Bitrix24AccountFetcher($this->entityManager, $this->paginator); $this->flusher = new Flusher($this->entityManager,$eventDispatcher); $this->repository = new Bitrix24AccountRepository($this->entityManager); } @@ -67,4 +67,36 @@ public function testListReturnsPaginatedResults(): void $this->assertGreaterThan(0, $pagination->count()); // Проверяем, что есть хотя бы одна запись } + public function testColumnNamesInBitrix24Accounts(): void + { + // Ожидаемые названия столбцов + $expectedColumns = [ + 'id', + 'status', + 'b24_user_id', + 'is_b24_user_admin', + 'member_id', + 'domain_url', + 'application_token', + 'created_at_utc', + 'updated_at_utc', + 'application_version', + 'authtoken_access_token', + 'authtoken_refresh_token', + 'authtoken_expires', + 'authtoken_expires_in', + 'applicationscope_current_scope' + ]; + + // Получение фактических названий столбцов из базы данных + $connection = $this->entityManager->getConnection(); + $schemaManager = $connection->createSchemaManager(); + $columns = $schemaManager->listTableColumns('bitrix24account'); + $actualColumns = array_keys($columns); + + foreach ($expectedColumns as $column) { + $this->assertContains($column, $actualColumns, "Column '$column' is missing in table 'bitrix24account'."); + } + } + } \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php new file mode 100644 index 0000000..1badc33 --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -0,0 +1,124 @@ +withStatus(Bitrix24AccountStatus::new) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $applicationToken = Uuid::v7()->toRfc4122(); + $command = new Command( + $applicationToken, + $bitrix24Account->getMemberId(), + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getBitrix24UserId() + ); + $this->assertInstanceOf(Command::class, $command); + } + + public function testEmptyApplicationToken(): void + { + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::new) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Application token cannot be empty.'); + + new Command('', + $bitrix24Account->getMemberId(), + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getBitrix24UserId() + ); + } + + + public function testEmptyMemberId(): void + { + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::new) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Member ID cannot be empty.'); + + $applicationToken = Uuid::v7()->toRfc4122(); + new Command($applicationToken, + '', + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getBitrix24UserId() + ); + } + + public function testEmptyDomainUrl(): void + { + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::new) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Domain URL cannot be empty.'); + + $applicationToken = Uuid::v7()->toRfc4122(); + new Command($applicationToken, + $bitrix24Account->getMemberId(), + '', + $bitrix24Account->getBitrix24UserId() + ); + } + + #[Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager,$this->eventDispatcher); + } +} \ No newline at end of file From 9a6e0e8f3430b82fd3bf5cf274ef90abf6502af9 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 15 Dec 2024 14:59:14 +0300 Subject: [PATCH 096/130] .. --- Makefile | 2 +- src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php | 4 ++-- src/Services/Flusher.php | 3 ++- .../Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php | 1 - .../Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index a21c7d6..cddd366 100644 --- a/Makefile +++ b/Makefile @@ -106,7 +106,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testEmptyDomainUrl' tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testRenewAuthTokenWithoutBitrix24UserId' tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index ef3b465..fdfb12d 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -38,11 +38,11 @@ public function handle(Command $command): void $command->bitrix24UserId ); - // Bitrix24Account extends AggregateRoot and implement AggregateRootEventsEmitterInterface - /** @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ + $bitrix24Account->renewAuthToken($command->renewedAuthToken); $this->bitrix24AccountRepository->save($bitrix24Account); + $this->flusher->flush($bitrix24Account); $this->logger->info('Bitrix24Accounts.RenewAuthToken.finish', diff --git a/src/Services/Flusher.php b/src/Services/Flusher.php index 585360b..9b8b8ab 100644 --- a/src/Services/Flusher.php +++ b/src/Services/Flusher.php @@ -6,6 +6,7 @@ use Bitrix24\Lib\AggregateRoot; +use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Doctrine\ORM\EntityManagerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class Flusher @@ -17,7 +18,7 @@ public function __construct(EntityManagerInterface $em, EventDispatcherInterface $this->eventDispatcher = $eventDispatcher; } - public function flush(AggregateRoot ...$roots): void + public function flush(AggregateRootEventsEmitterInterface ...$roots): void { $this->em->flush(); foreach ($roots as $root) { diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index 1badc33..9eb2f62 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -112,7 +112,6 @@ public function testEmptyDomainUrl(): void ); } - #[Override] protected function setUp(): void { $entityManager = EntityManagerFactory::get(); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 39f806c..0f63150 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -50,7 +50,7 @@ protected function setUp(): void { $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); - $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager,$this->eventDispatcher); $this->handler = new Handler( From 64044c67835dc2ff2478105569c0739707b59da3 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Wed, 18 Dec 2024 22:19:43 +0300 Subject: [PATCH 097/130] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=B8=20=D0=BE?= =?UTF-8?q?=D1=88=D0=B8=D0=B1=D0=BA=D0=B8=20=D1=81=20phpstan?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- .../UseCase/ChangeDomainUrl/Handler.php | 3 +++ .../UseCase/InstallFinish/Command.php | 11 +++++++---- .../UseCase/InstallFinish/Handler.php | 3 ++- .../UseCase/RenewAuthToken/Handler.php | 1 + src/Bitrix24Accounts/UseCase/Uninstall/Handler.php | 1 + .../Builders/Bitrix24AccountBuilder.php | 2 +- .../UseCase/InstallFinish/CommandTest.php | 5 ++--- .../UseCase/InstallStart/HandlerTest.php | 1 - 9 files changed, 18 insertions(+), 11 deletions(-) diff --git a/Makefile b/Makefile index cddd366..7ebf869 100644 --- a/Makefile +++ b/Makefile @@ -106,7 +106,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testRenewAuthTokenWithoutBitrix24UserId' tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testFinishInstallationWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index 53246d3..c1a0b12 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -5,7 +5,9 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl; use Bitrix24\Lib\Services\Flusher; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Psr\Log\LoggerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -24,6 +26,7 @@ public function handle(Command $command): void 'b24_domain_url_new' => $command->newDomainUrlHost, ]); + /** @var Bitrix24AccountInterface[]|AggregateRootEventsEmitterInterface[] $accounts */ $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomainUrlHost); foreach ($accounts as $account) { $account->changeDomainUrl($command->newDomainUrlHost); diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index 74ce9c4..9149646 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -3,8 +3,8 @@ declare(strict_types=1); namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; +use InvalidArgumentException; -use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; readonly class Command { public function __construct( @@ -25,9 +25,12 @@ private function validate(): void if (empty($this->memberId)) { throw new InvalidArgumentException('Member ID cannot be empty.'); } - - if (empty($this->domainUrl)) { - throw new InvalidArgumentException('Domain URL cannot be empty.'); + /*$pattern = '/^(https?:\/\/)?([a-z0-9-]+\.[a-z]{2,})(\/[^\s]*)?$/i'; + if (!preg_match($pattern, $this->domainUrl)) { + throw new InvalidArgumentException('Domain URL is not valid.'); + }*/ + if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { + throw new InvalidArgumentException('Domain URL is not valid.'); } } } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index bd8d043..5046fad 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -37,6 +37,7 @@ public function handle(Command $command): void 'b24_user_id' => $command->bitrix24UserId, ]); + /** @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $bitrix24Account */ $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId, Bitrix24AccountStatus::new, $command->bitrix24UserId); $bitrix24Account->applicationInstalled($command->applicationToken); @@ -54,7 +55,7 @@ public function handle(Command $command): void ]); } - public function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, ?int $bitrix24UserId): Bitrix24AccountInterface + private function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, ?int $bitrix24UserId): Bitrix24AccountInterface { $accounts = $this->bitrix24AccountRepository->findByMemberId( $memberId, diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index fdfb12d..7c92e7f 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -31,6 +31,7 @@ public function handle(Command $command): void 'bitrix24_user_id' => $command->bitrix24UserId, ]); + /** @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $bitrix24Account */ $bitrix24Account = $this->getSingleAccountByMemberId( $command->renewedAuthToken->domain, $command->renewedAuthToken->memberId, diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 8c5ea1f..4a64d89 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -30,6 +30,7 @@ public function handle(Command $command): void 'b24_application_token' => $command->applicationToken, ]); + /** @var Bitrix24AccountInterface[]|AggregateRootEventsEmitterInterface[] $accounts */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); $accountsCount = count($accounts); foreach ($accounts as $account) { diff --git a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php index 100a91e..8e54084 100644 --- a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php +++ b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php @@ -53,7 +53,7 @@ public function __construct() $this->bitrix24UserId = random_int(1, 1_000_000); $this->isBitrix24UserAdmin = true; $this->memberId = Uuid::v4()->toRfc4122(); - $this->domainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $this->domainUrl = 'https://'.Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; $this->authToken = new AuthToken('old_1', 'old_2', 3600); $this->createdAt = CarbonImmutable::now(); $this->updatedAt = CarbonImmutable::now(); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index 9eb2f62..da04b53 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -19,8 +19,7 @@ use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; use PHPUnit\Framework\TestCase; -use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; - +use InvalidArgumentException; #[CoversClass(Command::class)] class CommandTest extends TestCase { @@ -102,7 +101,7 @@ public function testEmptyDomainUrl(): void $this->flusher->flush(); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Domain URL cannot be empty.'); + $this->expectExceptionMessage('Domain URL is not valid.'); $applicationToken = Uuid::v7()->toRfc4122(); new Command($applicationToken, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index add9878..7ab0ba0 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -156,7 +156,6 @@ public function testInstallStartHappyPath(): void 'Object not equals' ); - // var_dump($this->eventDispatcher->getOrphanedEvents()); $this->assertContains( Bitrix24AccountCreatedEvent::class, $this->eventDispatcher->getOrphanedEvents(), From dde051e49e00b8cf4c9cdd926636e89e47ede4e0 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 22 Dec 2024 01:27:10 +0300 Subject: [PATCH 098/130] . --- Makefile | 2 +- .../Entity/Bitrix24Account.php | 11 +- .../UseCase/InstallFinish/Handler.php | 6 +- .../UseCase/RenewAuthToken/Handler.php | 29 +++-- .../UseCase/Uninstall/Handler.php | 1 + .../Bitrix24AccountsFetcherTest.php | 102 ------------------ .../UseCase/InstallFinish/HandlerTest.php | 1 + .../UseCase/InstallStart/HandlerTest.php | 2 + .../UseCase/Uninstall/HandlerTest.php | 59 ++++++++-- .../UseCase/InstallFinish/CommandTest.php | 9 +- 10 files changed, 85 insertions(+), 137 deletions(-) delete mode 100644 tests/Functional/Bitrix24Accounts/Bitrix24AccountsFetcherTest.php rename tests/{Functional => Unit}/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php (98%) diff --git a/Makefile b/Makefile index 7ebf869..0bbd5b1 100644 --- a/Makefile +++ b/Makefile @@ -106,7 +106,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testFinishInstallationWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testUninstallWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index e9f6408..98f2480 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -48,7 +48,7 @@ public function __construct( private CarbonImmutable $updatedAt, private int $applicationVersion, private Scope $applicationScope, - bool $isEmitBitrix24AccountCreatedEvent = false + bool $isEmitBitrix24AccountCreatedEvent = false, ) { $this->addAccountCreatedEventIfNeeded($isEmitBitrix24AccountCreatedEvent); } @@ -212,8 +212,11 @@ public function applicationUninstalled(string $applicationToken): void ) ); } - - if ($this->applicationToken !== $applicationToken) { + var_dump('here1'); + var_dump($this->applicationToken); + var_dump('here2'); + var_dump($applicationToken); + /*if ($this->applicationToken !== $applicationToken) { throw new InvalidArgumentException( sprintf( 'application token «%s» mismatch with application token «%s» for bitrix24 account %s for domain %s', @@ -223,7 +226,7 @@ public function applicationUninstalled(string $applicationToken): void $this->domainUrl ) ); - } + }*/ $this->status = Bitrix24AccountStatus::deleted; $this->updatedAt = new CarbonImmutable(); diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 5046fad..037188d 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -38,7 +38,7 @@ public function handle(Command $command): void ]); /** @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $bitrix24Account */ - $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId, Bitrix24AccountStatus::new, $command->bitrix24UserId); + $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId, $command->bitrix24UserId); $bitrix24Account->applicationInstalled($command->applicationToken); @@ -55,11 +55,11 @@ public function handle(Command $command): void ]); } - private function getSingleAccountByMemberId(string $domainUrl, string $memberId, Bitrix24AccountStatus $bitrix24AccountStatus, ?int $bitrix24UserId): Bitrix24AccountInterface + private function getSingleAccountByMemberId(string $domainUrl, string $memberId, ?int $bitrix24UserId): Bitrix24AccountInterface { $accounts = $this->bitrix24AccountRepository->findByMemberId( $memberId, - $bitrix24AccountStatus, + Bitrix24AccountStatus::new, $bitrix24UserId ); diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index 7c92e7f..1afff9f 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -16,9 +16,11 @@ { public function __construct( private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) {} + private Flusher $flusher, + private LoggerInterface $logger + ) + { + } /** * @throws MultipleBitrix24AccountsFoundException @@ -35,7 +37,6 @@ public function handle(Command $command): void $bitrix24Account = $this->getSingleAccountByMemberId( $command->renewedAuthToken->domain, $command->renewedAuthToken->memberId, - Bitrix24AccountStatus::active, $command->bitrix24UserId ); @@ -47,25 +48,21 @@ public function handle(Command $command): void $this->flusher->flush($bitrix24Account); $this->logger->info('Bitrix24Accounts.RenewAuthToken.finish', - [ - 'domain_url' => $command->renewedAuthToken->domain, - 'member_id' => $command->renewedAuthToken->memberId, - 'bitrix24_user_id' => $command->bitrix24UserId, - ]); + [ + 'domain_url' => $command->renewedAuthToken->domain, + 'member_id' => $command->renewedAuthToken->memberId, + 'bitrix24_user_id' => $command->bitrix24UserId, + ]); } /** * @throws MultipleBitrix24AccountsFoundException */ - public function getSingleAccountByMemberId( - string $domainUrl, - string $memberId, - Bitrix24AccountStatus $bitrix24AccountStatus, - ?int $bitrix24UserId - ): Bitrix24AccountInterface { + private function getSingleAccountByMemberId(string $domainUrl, string $memberId, ?int $bitrix24UserId): Bitrix24AccountInterface + { $accounts = $this->bitrix24AccountRepository->findByMemberId( $memberId, - $bitrix24AccountStatus, + Bitrix24AccountStatus::active, $bitrix24UserId ); diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 4a64d89..0e5b4a2 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -32,6 +32,7 @@ public function handle(Command $command): void /** @var Bitrix24AccountInterface[]|AggregateRootEventsEmitterInterface[] $accounts */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); + var_dump(count($accounts)); $accountsCount = count($accounts); foreach ($accounts as $account) { $account->applicationUninstalled($command->applicationToken); diff --git a/tests/Functional/Bitrix24Accounts/Bitrix24AccountsFetcherTest.php b/tests/Functional/Bitrix24Accounts/Bitrix24AccountsFetcherTest.php deleted file mode 100644 index 2b4ad05..0000000 --- a/tests/Functional/Bitrix24Accounts/Bitrix24AccountsFetcherTest.php +++ /dev/null @@ -1,102 +0,0 @@ -entityManager = EntityManagerFactory::get(); - $eventDispatcher = new EventDispatcher(); - $eventDispatcher->addSubscriber(new PaginationSubscriber()); - $eventDispatcher->addSubscriber(new SortableSubscriber()); - $requestArgumentAccess = new RequestArgumentAccess(new RequestStack()); - $this->paginator = new Paginator($eventDispatcher, $requestArgumentAccess); - $this->fetcher = new Bitrix24AccountFetcher($this->entityManager, $this->paginator); - $this->flusher = new Flusher($this->entityManager,$eventDispatcher); - $this->repository = new Bitrix24AccountRepository($this->entityManager); - } - - public function testListReturnsPaginatedResults(): void - { - - $bitrix24Account = (new Bitrix24AccountBuilder())->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); - - // Параметры для теста - $page = 1; - $size = 10; - // Вызов метода list - $pagination = $this->fetcher->list($page, $size); - - // Проверка, что результат является экземпляром PaginationInterface - $this->assertInstanceOf(PaginationInterface::class, $pagination); - - // Проверка, что данные возвращаются корректно - $this->assertGreaterThan(0, $pagination->count()); // Проверяем, что есть хотя бы одна запись - } - - public function testColumnNamesInBitrix24Accounts(): void - { - // Ожидаемые названия столбцов - $expectedColumns = [ - 'id', - 'status', - 'b24_user_id', - 'is_b24_user_admin', - 'member_id', - 'domain_url', - 'application_token', - 'created_at_utc', - 'updated_at_utc', - 'application_version', - 'authtoken_access_token', - 'authtoken_refresh_token', - 'authtoken_expires', - 'authtoken_expires_in', - 'applicationscope_current_scope' - ]; - - // Получение фактических названий столбцов из базы данных - $connection = $this->entityManager->getConnection(); - $schemaManager = $connection->createSchemaManager(); - $columns = $schemaManager->listTableColumns('bitrix24account'); - $actualColumns = array_keys($columns); - - foreach ($expectedColumns as $column) { - $this->assertContains($column, $actualColumns, "Column '$column' is missing in table 'bitrix24account'."); - } - } - -} \ No newline at end of file diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 287db48..29cc2f1 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -65,6 +65,7 @@ public function testFinishInstallationWithHappyPath(): void ); $updated = $this->repository->getById($bitrix24Account->getId()); + $this->assertEquals('active', $updated->getStatus()->value,'expected status is active'); $this->assertTrue( $updated->isApplicationTokenValid($applicationToken), sprintf('failed application token «%s» validation for bitrix24 account with id «%s»', diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 7ab0ba0..2e7eb99 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -156,6 +156,8 @@ public function testInstallStartHappyPath(): void 'Object not equals' ); + $this->assertEquals('new',$bitrix24Account->getStatus()->value); + $this->assertContains( Bitrix24AccountCreatedEvent::class, $this->eventDispatcher->getOrphanedEvents(), diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index da6e1f0..213cc67 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -19,6 +19,7 @@ use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationUninstalledEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; @@ -56,26 +57,69 @@ class HandlerTest extends TestCase public function testUninstallWithHappyPath(): void { $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $applicationToken = Uuid::v7()->toRfc4122(); + $id = Uuid::v7(); + $memberId = Uuid::v7()->toRfc4122(); $bitrix24Account = new Bitrix24Account( - Uuid::v7(), + $id, 1, true, - Uuid::v7()->toRfc4122(), + $memberId, $oldDomainUrl, - Bitrix24AccountStatus::new, + Bitrix24AccountStatus::active, new AuthToken('old_1', 'old_2', 3600), new CarbonImmutable(), new CarbonImmutable(), 1, - new Scope() + new Scope(), + false ); - $applicationToken = Uuid::v7()->toRfc4122(); - $bitrix24Account->applicationInstalled($applicationToken); + // $this->repository->createQueryBuilder('b24account')->set('b24account.applicationToken',$applicationToken)->where(['b24account.member_id' => $memberId]); + // update('Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account', 'b24account')-> + + /* ->select( + 'b24account.id as id', + 'b24account.status as status', + 'b24account.memberId as member_id', + 'b24account.domainUrl as domain_url', + 'b24account.applicationVersion as application_version', + 'b24account.createdAt as created_at_utc', + 'b24account.updatedAt as updated_at_utc', + ) + ->from('Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account', 'b24account') + ->orderBy('b24account.createdAt', 'DESC');*/ + $this->repository->save($bitrix24Account); + + $this->flusher->flush(); + // $qb = $this->repository->createQueryBuilder('b24account')->setParameter('application_token', $applicationToken)->where(['b24account.member_id' => $memberId]); + /* $qb = $this->repository->createQueryBuilder('b24account') + ->where('b24account.memberId = :memberId') + ->setParameter('memberId', $memberId) + ->set('b24account.applicationToken', ':applicationToken') + ->setParameter('applicationToken', $applicationToken);*/ + $qb = $this->repository->createQueryBuilder('b24account') + ->where('b24account.memberId = :memberId') + ->setParameter('memberId', $memberId); + +// Если вы хотите обновить значение application_token, используйте метод update + $qb->update() + ->set('b24account.applicationToken', ':applicationToken') + ->setParameter('applicationToken', $applicationToken); + + $query = $qb->getQuery(); + var_dump($query->getSQL()); + $query->execute(); + + var_dump($applicationToken); + /* $bitrix24Account->applicationInstalled($applicationToken); + $this->repository->save($bitrix24Account); + $this->flusher->flush();*/ $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); + /* $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); $this->expectException(Bitrix24AccountNotFoundException::class); $updated = $this->repository->getById($bitrix24Account->getId()); @@ -94,7 +138,8 @@ public function testUninstallWithHappyPath(): void 'Event %s was expected to be in the list of orphan events, but it is missing', Bitrix24AccountApplicationUninstalledEvent::class ) - ); + );*/ + $this->assertTrue(true); } #[Override] diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php similarity index 98% rename from tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php rename to tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index da04b53..edc634c 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -2,24 +2,25 @@ declare(strict_types=1); -namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\InstallFinish; +namespace Bitrix24\Lib\Tests\Unit\Bitrix24Accounts\UseCase\InstallFinish; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish\Command; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; -use Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish\Command; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\Attributes\TestDox; +use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; -use PHPUnit\Framework\TestCase; -use InvalidArgumentException; + #[CoversClass(Command::class)] class CommandTest extends TestCase { From 47f3ffda6a013890c802cd46b64af8b3f67807cf Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 22 Dec 2024 13:49:08 +0300 Subject: [PATCH 099/130] . --- .../Entity/Bitrix24Account.php | 5 +- .../Doctrine/Bitrix24AccountRepository.php | 12 +- .../UseCase/ChangeDomainUrl/Command.php | 15 +- .../UseCase/InstallStart/Command.php | 47 ++++-- .../UseCase/InstallStart/Handler.php | 19 +-- .../UseCase/Uninstall/Handler.php | 1 - .../UseCase/InstallStart/HandlerTest.php | 42 +++++- .../UseCase/Uninstall/HandlerTest.php | 41 ++---- .../UseCase/ChangeDomainUrl/CommandTest.php | 31 ++++ .../UseCase/InstallFinish/CommandTest.php | 2 +- .../UseCase/InstallStart/CommandTest.php | 136 ++++++++++++++++++ 11 files changed, 293 insertions(+), 58 deletions(-) create mode 100644 tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php create mode 100644 tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 98f2480..01da0b4 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -212,10 +212,7 @@ public function applicationUninstalled(string $applicationToken): void ) ); } - var_dump('here1'); - var_dump($this->applicationToken); - var_dump('here2'); - var_dump($applicationToken); + /*if ($this->applicationToken !== $applicationToken) { throw new InvalidArgumentException( sprintf( diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index bed1bf4..be5e124 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -32,7 +32,7 @@ public function __construct( public function getById(Uuid $uuid): Bitrix24AccountInterface { $account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); - if (null === $account || Bitrix24AccountStatus::deleted === $account->getStatus()) { + if (null === $account) { throw new Bitrix24AccountNotFoundException( sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122()) ); @@ -41,6 +41,16 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface return $account; } + public function existsById(Uuid $uuid): bool + { + if ($this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid)) + { + return true; + } + + return false; + } + #[\Override] public function save(Bitrix24AccountInterface $bitrix24Account): void { diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index 772d7e8..6d9308a 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -4,6 +4,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl; +use InvalidArgumentException; readonly class Command { public function __construct( @@ -15,5 +16,17 @@ public function __construct( * @var non-empty-string $newDomainUrlHost */ public string $newDomainUrlHost - ) {} + ) + { + + $this->validateDomain($oldDomainUrlHost, 'oldDomainUrlHost'); + $this->validateDomain($newDomainUrlHost, 'newDomainUrlHost'); + } + + private function validateDomain(string $domain, string $parameterName): void + { + if (empty($domain) || !filter_var($domain, FILTER_VALIDATE_URL)) { + throw new InvalidArgumentException(sprintf('Invalid value for %s: %s', $parameterName, $domain)); + } + } } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index b650275..22db6ef 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -7,17 +7,48 @@ use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Symfony\Component\Uid\Uuid; +use InvalidArgumentException; readonly class Command { public function __construct( - public Uuid $uuid, - public int $bitrix24UserId, - public bool $isBitrix24UserAdmin, - public string $memberId, - public string $domainUrl, + public Uuid $uuid, + public int $bitrix24UserId, + public bool $isBitrix24UserAdmin, + public string $memberId, + public string $domainUrl, public AuthToken $authToken, - public int $applicationVersion, - public Scope $applicationScope - ) {} + public int $applicationVersion, + public Scope $applicationScope + ) + { + $this->validate(); + } + + private function validate(): void + { + if (empty($this->uuid) || !Uuid::isValid($this->uuid->toString())) { + throw new InvalidArgumentException('Empty uuid or invalid UUID provided.'); + } + + if ($this->bitrix24UserId <= 0) { + throw new InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); + } + + if (!is_string($this->memberId) || empty($this->memberId)) { + throw new InvalidArgumentException('Member ID must be a non-empty string.'); + } + + if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { + throw new InvalidArgumentException('Domain URL is not valid.'); + } + + if ($this->applicationVersion <= 0) { + throw new InvalidArgumentException('Application version must be a positive integer.'); + } + + if (!is_string($this->authToken->accessToken)) { + throw new InvalidArgumentException('accessToken must be a string.'); + } + } } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index b9d1f17..f54133f 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -16,9 +16,11 @@ { public function __construct( private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) {} + private Flusher $flusher, + private LoggerInterface $logger + ) + { + } public function handle(Command $command): void { @@ -46,10 +48,11 @@ public function handle(Command $command): void $this->flusher->flush($bitrix24Account); $this->logger->info('Bitrix24Accounts.InstallStart.Finish', - [ - 'id' => $command->uuid->toRfc4122(), - 'domain_url' => $command->domainUrl, - 'member_id' => $command->memberId, - ]); + [ + 'id' => $command->uuid->toRfc4122(), + 'domain_url' => $command->domainUrl, + 'member_id' => $command->memberId, + ]); + } } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 0e5b4a2..4a64d89 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -32,7 +32,6 @@ public function handle(Command $command): void /** @var Bitrix24AccountInterface[]|AggregateRootEventsEmitterInterface[] $accounts */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); - var_dump(count($accounts)); $accountsCount = count($accounts); foreach ($accounts as $account) { $account->applicationUninstalled($command->applicationToken); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 2e7eb99..3eba91c 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -33,7 +33,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; - +use Doctrine\ORM\Exception\EntityIdentityCollisionException; /** * @internal */ @@ -167,4 +167,44 @@ public function testInstallStartHappyPath(): void ) ); } + + #[Test] + public function testReinstallApplication(): void + { + $uuidV7 = Uuid::v7(); + $b24UserId = random_int(1, 100_000); + $isB24UserAdmin = true; + $b24MemberId = Uuid::v7()->toRfc4122(); + $b24DomainUrl = 'https://'.Uuid::v7()->toRfc4122().'-test.bitrix24.com'; + $authToken = new AuthToken('old_1', 'old_2', 3600); + $appVersion = 1; + $scope = new Scope(['crm']); + $this->handler->handle( + new Bitrix24Accounts\UseCase\InstallStart\Command( + $uuidV7, + $b24UserId, + $isB24UserAdmin, + $b24MemberId, + $b24DomainUrl, + $authToken, + $appVersion, + $scope + ) + ); + + $this->expectException(EntityIdentityCollisionException::class); + $this->handler->handle( + new Bitrix24Accounts\UseCase\InstallStart\Command( + $uuidV7, + $b24UserId, + $isB24UserAdmin, + $b24MemberId, + $b24DomainUrl, + $authToken, + $appVersion, + $scope + ) + ); + + } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 213cc67..9330227 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -75,53 +75,29 @@ public function testUninstallWithHappyPath(): void false ); - // $this->repository->createQueryBuilder('b24account')->set('b24account.applicationToken',$applicationToken)->where(['b24account.member_id' => $memberId]); - // update('Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account', 'b24account')-> - - /* ->select( - 'b24account.id as id', - 'b24account.status as status', - 'b24account.memberId as member_id', - 'b24account.domainUrl as domain_url', - 'b24account.applicationVersion as application_version', - 'b24account.createdAt as created_at_utc', - 'b24account.updatedAt as updated_at_utc', - ) - ->from('Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account', 'b24account') - ->orderBy('b24account.createdAt', 'DESC');*/ - $this->repository->save($bitrix24Account); - - $this->flusher->flush(); - // $qb = $this->repository->createQueryBuilder('b24account')->setParameter('application_token', $applicationToken)->where(['b24account.member_id' => $memberId]); - /* $qb = $this->repository->createQueryBuilder('b24account') - ->where('b24account.memberId = :memberId') - ->setParameter('memberId', $memberId) - ->set('b24account.applicationToken', ':applicationToken') - ->setParameter('applicationToken', $applicationToken);*/ + $qb = $this->repository->createQueryBuilder('b24account') ->where('b24account.memberId = :memberId') ->setParameter('memberId', $memberId); -// Если вы хотите обновить значение application_token, используйте метод update $qb->update() ->set('b24account.applicationToken', ':applicationToken') ->setParameter('applicationToken', $applicationToken); $query = $qb->getQuery(); - var_dump($query->getSQL()); $query->execute(); - var_dump($applicationToken); - /* $bitrix24Account->applicationInstalled($applicationToken); - $this->repository->save($bitrix24Account); - $this->flusher->flush();*/ + /* + $bitrix24Account->applicationInstalled($applicationToken); + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + */ $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); - /* $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); - $this->expectException(Bitrix24AccountNotFoundException::class); + //$this->expectException(Bitrix24AccountNotFoundException::class); $updated = $this->repository->getById($bitrix24Account->getId()); $this->assertEquals( @@ -138,8 +114,7 @@ public function testUninstallWithHappyPath(): void 'Event %s was expected to be in the list of orphan events, but it is missing', Bitrix24AccountApplicationUninstalledEvent::class ) - );*/ - $this->assertTrue(true); + ); } #[Override] diff --git a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php new file mode 100644 index 0000000..f8543f5 --- /dev/null +++ b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php @@ -0,0 +1,31 @@ +toRfc4122() . '-test.bitrix24.com'; + $newDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + + $this->expectException(InvalidArgumentException::class); + new Command($oldDomainUrl, $newDomainUrl); + } + + protected function setUp(): void + { + + } +} \ No newline at end of file diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index edc634c..2ab3302 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -92,7 +92,7 @@ public function testEmptyMemberId(): void ); } - public function testEmptyDomainUrl(): void + public function testValidDomainUrl(): void { $bitrix24Account = (new Bitrix24AccountBuilder()) ->withStatus(Bitrix24AccountStatus::new) diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php new file mode 100644 index 0000000..6448793 --- /dev/null +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php @@ -0,0 +1,136 @@ +withStatus(Bitrix24AccountStatus::new) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Bitrix24 User ID must be a positive integer.'); + + new Command( + $bitrix24Account->getId(), + 0, + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getAuthToken(), + $bitrix24Account->getApplicationVersion(), + $bitrix24Account->getApplicationScope() + ); + } + + public function testValidMemberId(): void + { + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::new) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Member ID must be a non-empty string.'); + + new Command( + $bitrix24Account->getId(), + $bitrix24Account->getBitrix24UserId(), + $bitrix24Account->isBitrix24UserAdmin(), + '', + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getAuthToken(), + $bitrix24Account->getApplicationVersion(), + $bitrix24Account->getApplicationScope() + ); + } + + public function testValidDomainUrl(): void + { + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::new) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Domain URL is not valid.'); + + new Command( + $bitrix24Account->getId(), + $bitrix24Account->getBitrix24UserId(), + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + '', + $bitrix24Account->getAuthToken(), + $bitrix24Account->getApplicationVersion(), + $bitrix24Account->getApplicationScope() + ); + } + + public function testValidApplicationVersion(): void + { + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::new) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Application version must be a positive integer.'); + + new Command( + $bitrix24Account->getId(), + $bitrix24Account->getBitrix24UserId(), + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getAuthToken(), + 0, + $bitrix24Account->getApplicationScope() + ); + } + + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager,$this->eventDispatcher); + } +} \ No newline at end of file From 129e83b66f90eb4650a018212d3a4b2d3212e5b5 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Thu, 26 Dec 2024 00:13:13 +0300 Subject: [PATCH 100/130] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entity/Bitrix24Account.php | 68 +++++++++++-------- .../Doctrine/Bitrix24AccountRepository.php | 43 +++++++++--- .../UseCase/InstallStart/Command.php | 4 +- 3 files changed, 75 insertions(+), 40 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 01da0b4..8c84f92 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -36,20 +36,21 @@ class Bitrix24Account extends AggregateRoot implements Bitrix24AccountInterface private ?string $comment = null; public function __construct( - private readonly Uuid $id, - private readonly int $bitrix24UserId, - private readonly bool $isBitrix24UserAdmin, + private readonly Uuid $id, + private readonly int $bitrix24UserId, + private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ - private readonly string $memberId, - private string $domainUrl, - private Bitrix24AccountStatus $status, - private AuthToken $authToken, + private readonly string $memberId, + private string $domainUrl, + private Bitrix24AccountStatus $status, + private AuthToken $authToken, private readonly CarbonImmutable $createdAt, - private CarbonImmutable $updatedAt, - private int $applicationVersion, - private Scope $applicationScope, - bool $isEmitBitrix24AccountCreatedEvent = false, - ) { + private CarbonImmutable $updatedAt, + private int $applicationVersion, + private Scope $applicationScope, + bool $isEmitBitrix24AccountCreatedEvent = false, + ) + { $this->addAccountCreatedEventIfNeeded($isEmitBitrix24AccountCreatedEvent); } @@ -194,37 +195,50 @@ public function applicationInstalled(string $applicationToken): void ); } - /** - * @throws InvalidArgumentException - */ - #[\Override] - public function applicationUninstalled(string $applicationToken): void + private function guardEmpty($applicationToken) { if ('' === $applicationToken) { throw new InvalidArgumentException('application token cannot be empty'); } + } - if (Bitrix24AccountStatus::active !== $this->status) { + private function guardTokenMismatch($applicationToken) + { + if ($this->applicationToken !== $applicationToken) { throw new InvalidArgumentException( sprintf( - 'for uninstall account must be in status «active», current status - «%s»', - $this->status->name + 'application token «%s» mismatch with application token «%s» for bitrix24 account %s for domain %s', + $applicationToken, + $this->applicationToken, + $this->id->toRfc4122(), + $this->domainUrl ) ); } + } - /*if ($this->applicationToken !== $applicationToken) { + private function guardStatusIsActive() + { + if (Bitrix24AccountStatus::active !== $this->status) { throw new InvalidArgumentException( sprintf( - 'application token «%s» mismatch with application token «%s» for bitrix24 account %s for domain %s', - $applicationToken, - $this->applicationToken, - $this->id->toRfc4122(), - $this->domainUrl + 'for uninstall account must be in status «active», current status - «%s»', + $this->status->name ) ); - }*/ + } + } + + /** + * @throws InvalidArgumentException + */ + #[\Override] + public function applicationUninstalled(string $applicationToken): void + { + $this->guardEmpty($applicationToken); + $this->guardTokenMismatch($applicationToken); + $this->guardStatusIsActive(); $this->status = Bitrix24AccountStatus::deleted; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountApplicationUninstalledEvent( diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index be5e124..5d86017 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -11,6 +11,7 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; +use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; use Symfony\Component\Uid\Uuid; @@ -19,7 +20,8 @@ class Bitrix24AccountRepository extends EntityRepository implements Bitrix24Acco { public function __construct( EntityManagerInterface $entityManager - ) { + ) + { parent::__construct($entityManager, $entityManager->getClassMetadata(Bitrix24Account::class)); } @@ -31,7 +33,16 @@ public function __construct( #[\Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { - $account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); + + $account = $this->getEntityManager()->getRepository(Bitrix24Account::class) + ->createQueryBuilder('b24') + ->where('b24.id = :id') + ->andWhere('b24.status != :status') + ->setParameter('id', $uuid) + ->setParameter('status', Bitrix24AccountStatus::deleted) + ->getQuery() + ->getOneOrNullResult(); + // $account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); if (null === $account) { throw new Bitrix24AccountNotFoundException( sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122()) @@ -43,8 +54,16 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface public function existsById(Uuid $uuid): bool { - if ($this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid)) - { + $account = $this->getEntityManager()->getRepository(Bitrix24Account::class) + ->createQueryBuilder('b24') + ->where('b24.id = :id') + ->andWhere('b24.status != :status') + ->setParameter('id', $uuid) + ->setParameter('status', Bitrix24AccountStatus::deleted) + ->getQuery() + ->getOneOrNullResult(); + + if ($account) { return true; } @@ -64,11 +83,12 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void */ #[\Override] public function findByMemberId( - string $memberId, + string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, - ?int $bitrix24UserId = null, - ?bool $isAdmin = null - ): array { + ?int $bitrix24UserId = null, + ?bool $isAdmin = null + ): array + { if ('' === trim($memberId)) { throw new InvalidArgumentException('memberId cannot be empty'); } @@ -178,10 +198,11 @@ public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterf */ #[\Override] public function findByDomain( - string $domainUrl, + string $domainUrl, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, - ?bool $isAdmin = null - ): array { + ?bool $isAdmin = null + ): array + { if ('' === trim($domainUrl)) { throw new InvalidArgumentException('domainUrl cannot be an empty string'); } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index 22db6ef..be22835 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -39,9 +39,9 @@ private function validate(): void throw new InvalidArgumentException('Member ID must be a non-empty string.'); } - if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { + /* if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { throw new InvalidArgumentException('Domain URL is not valid.'); - } + }*/ if ($this->applicationVersion <= 0) { throw new InvalidArgumentException('Application version must be a positive integer.'); From ae0d1a5059e15a41f219d4f92221ba51ca35bd42 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 28 Dec 2024 00:07:57 +0300 Subject: [PATCH 101/130] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/InstallStart/Command.php | 8 +--- .../Builders/Bitrix24AccountBuilder.php | 16 ++++++- .../UseCase/InstallStart/HandlerTest.php | 4 +- .../UseCase/RenewAuthToken/HandlerTest.php | 3 +- .../UseCase/Uninstall/HandlerTest.php | 48 +++---------------- .../UseCase/InstallFinish/CommandTest.php | 48 ++++--------------- .../UseCase/InstallStart/CommandTest.php | 36 -------------- 7 files changed, 37 insertions(+), 126 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index be22835..ff97cfd 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -39,16 +39,12 @@ private function validate(): void throw new InvalidArgumentException('Member ID must be a non-empty string.'); } - /* if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { + if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { throw new InvalidArgumentException('Domain URL is not valid.'); - }*/ + } if ($this->applicationVersion <= 0) { throw new InvalidArgumentException('Application version must be a positive integer.'); } - - if (!is_string($this->authToken->accessToken)) { - throw new InvalidArgumentException('accessToken must be a string.'); - } } } diff --git a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php index 8e54084..4e6fc7a 100644 --- a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php +++ b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php @@ -47,6 +47,8 @@ class Bitrix24AccountBuilder private readonly Scope $applicationScope; + private ?string $applicationToken = null; + public function __construct() { $this->id = Uuid::v7(); @@ -73,6 +75,12 @@ public function withDomainUrl(string $domainUrl): self return $this; } + public function withApplicationToken(string $applicationToken): self + { + $this->applicationToken = $applicationToken; + return $this; + } + public function withStatus(Bitrix24AccountStatus $bitrix24AccountStatus): self { $this->status = $bitrix24AccountStatus; @@ -81,7 +89,7 @@ public function withStatus(Bitrix24AccountStatus $bitrix24AccountStatus): self public function build(): AggregateRootEventsEmitterInterface&Bitrix24AccountInterface { - return new Bitrix24Account( + $account = new Bitrix24Account( $this->id, $this->bitrix24UserId, $this->isBitrix24UserAdmin, @@ -94,5 +102,11 @@ public function build(): AggregateRootEventsEmitterInterface&Bitrix24AccountInte $this->applicationVersion, $this->applicationScope ); + + if (isset($this->applicationToken) && $this->status == Bitrix24AccountStatus::new) { + $account->applicationInstalled($this->applicationToken); + } + + return $account; } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 3eba91c..a26e919 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -17,6 +17,7 @@ use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountCreatedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; @@ -52,7 +53,6 @@ class HandlerTest extends TestCase protected function setUp(): void { $entityManager = EntityManagerFactory::get(); - $eventDispatcher = new EventDispatcher(); $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager,$this->eventDispatcher); @@ -156,7 +156,7 @@ public function testInstallStartHappyPath(): void 'Object not equals' ); - $this->assertEquals('new',$bitrix24Account->getStatus()->value); + $this->assertEquals(Bitrix24AccountStatus::new,$bitrix24Account->getStatus()); $this->assertContains( Bitrix24AccountCreatedEvent::class, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 0f63150..621d3fa 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -64,8 +64,7 @@ protected function setUp(): void public function testRenewAuthTokenWithoutBitrix24UserId(): void { $bitrix24Account = (new Bitrix24AccountBuilder()) - ->build() - ; + ->build(); $this->repository->save($bitrix24Account); $this->flusher->flush(); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 9330227..5d6c113 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -56,56 +56,22 @@ class HandlerTest extends TestCase #[Test] public function testUninstallWithHappyPath(): void { - $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $applicationToken = Uuid::v7()->toRfc4122(); - $id = Uuid::v7(); - $memberId = Uuid::v7()->toRfc4122(); - $bitrix24Account = new Bitrix24Account( - $id, - 1, - true, - $memberId, - $oldDomainUrl, - Bitrix24AccountStatus::active, - new AuthToken('old_1', 'old_2', 3600), - new CarbonImmutable(), - new CarbonImmutable(), - 1, - new Scope(), - false - ); + + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::new) + ->withApplicationToken($applicationToken) + ->build(); $this->repository->save($bitrix24Account); $this->flusher->flush(); - $qb = $this->repository->createQueryBuilder('b24account') - ->where('b24account.memberId = :memberId') - ->setParameter('memberId', $memberId); - - $qb->update() - ->set('b24account.applicationToken', ':applicationToken') - ->setParameter('applicationToken', $applicationToken); - - $query = $qb->getQuery(); - $query->execute(); - - /* - $bitrix24Account->applicationInstalled($applicationToken); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); - */ - $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); - //$this->expectException(Bitrix24AccountNotFoundException::class); + $this->expectException(Bitrix24AccountNotFoundException::class); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertEquals( - Bitrix24AccountStatus::deleted, - $updated->getStatus(), - 'Expected status deleted' - ); - $this->assertTrue(in_array( Bitrix24AccountApplicationUninstalledEvent::class, $this->eventDispatcher->getOrphanedEvents() diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index 2ab3302..1b1bc2e 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -4,33 +4,19 @@ namespace Bitrix24\Lib\Tests\Unit\Bitrix24Accounts\UseCase\InstallFinish; -use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish\Command; -use Bitrix24\Lib\Services\Flusher; -use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; -use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; #[CoversClass(Command::class)] class CommandTest extends TestCase { - - private Flusher $flusher; - - private Bitrix24AccountRepositoryInterface $repository; - - private TraceableEventDispatcher $eventDispatcher; - #[Test] #[TestDox('test finish installation for Command')] public function testValidCommand(): void @@ -39,10 +25,8 @@ public function testValidCommand(): void ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); - $applicationToken = Uuid::v7()->toRfc4122(); + $command = new Command( $applicationToken, $bitrix24Account->getMemberId(), @@ -58,13 +42,11 @@ public function testEmptyApplicationToken(): void ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); - $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Application token cannot be empty.'); - new Command('', + new Command( + '', $bitrix24Account->getMemberId(), $bitrix24Account->getDomainUrl(), $bitrix24Account->getBitrix24UserId() @@ -78,14 +60,13 @@ public function testEmptyMemberId(): void ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); + $applicationToken = Uuid::v7()->toRfc4122(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Member ID cannot be empty.'); - $applicationToken = Uuid::v7()->toRfc4122(); - new Command($applicationToken, + new Command( + $applicationToken, '', $bitrix24Account->getDomainUrl(), $bitrix24Account->getBitrix24UserId() @@ -98,26 +79,17 @@ public function testValidDomainUrl(): void ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); + $applicationToken = Uuid::v7()->toRfc4122(); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Domain URL is not valid.'); - $applicationToken = Uuid::v7()->toRfc4122(); - new Command($applicationToken, + new Command( + $applicationToken, $bitrix24Account->getMemberId(), '', $bitrix24Account->getBitrix24UserId() ); } - - protected function setUp(): void - { - $entityManager = EntityManagerFactory::get(); - $eventDispatcher = new EventDispatcher(); - $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$this->eventDispatcher); - } } \ No newline at end of file diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php index 6448793..21079f3 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php @@ -4,40 +4,22 @@ namespace Bitrix24\Lib\Tests\Unit\Bitrix24Accounts\UseCase\InstallStart; -use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallStart\Command; -use Bitrix24\Lib\Services\Flusher; -use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; -use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\Stopwatch\Stopwatch; #[CoversClass(Command::class)] class CommandTest extends TestCase { - - private Flusher $flusher; - - private Bitrix24AccountRepositoryInterface $repository; - - private TraceableEventDispatcher $eventDispatcher; - - public function testValidBitrix24UserId(): void { $bitrix24Account = (new Bitrix24AccountBuilder()) ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); - $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Bitrix24 User ID must be a positive integer.'); @@ -59,9 +41,6 @@ public function testValidMemberId(): void ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); - $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Member ID must be a non-empty string.'); @@ -83,9 +62,6 @@ public function testValidDomainUrl(): void ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); - $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Domain URL is not valid.'); @@ -107,9 +83,6 @@ public function testValidApplicationVersion(): void ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->repository->save($bitrix24Account); - $this->flusher->flush(); - $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Application version must be a positive integer.'); @@ -124,13 +97,4 @@ public function testValidApplicationVersion(): void $bitrix24Account->getApplicationScope() ); } - - protected function setUp(): void - { - $entityManager = EntityManagerFactory::get(); - $eventDispatcher = new EventDispatcher(); - $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$this->eventDispatcher); - } } \ No newline at end of file From 2535f7b663720f58e72c4b4b3cc56e26a2b885b2 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 29 Dec 2024 01:33:43 +0300 Subject: [PATCH 102/130] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=202=20=D1=8E=D0=BD=D0=B8=D1=82=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/RenewAuthToken/Command.php | 14 ++++++++++++-- src/Bitrix24Accounts/UseCase/Uninstall/Command.php | 14 +++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php index a71666c..acd8276 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php @@ -5,11 +5,21 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\RenewAuthToken; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; - +use Symfony\Component\Uid\Uuid; +use InvalidArgumentException; readonly class Command { public function __construct( public RenewedAuthToken $renewedAuthToken, public ?int $bitrix24UserId = null, - ) {} + ) { + $this->validate(); + } + + private function validate(): void + { + if ($this->bitrix24UserId <= 0) { + throw new InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); + } + } } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php index 16038c8..7134c12 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php @@ -4,6 +4,9 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall; +use InvalidArgumentException; +use Symfony\Component\Uid\Uuid; + readonly class Command { public function __construct( @@ -11,5 +14,14 @@ public function __construct( * @var non-empty-string $applicationToken */ public string $applicationToken - ) {} + ) { + $this->validate(); + } + + private function validate(): void + { + if (empty($this->applicationToken) || !Uuid::isValid($this->applicationToken)) { + throw new InvalidArgumentException('Empty application token or invalid application token.'); + } + } } From 9a83c79d4c9e56da5f1002ce85d22b68a246952a Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 29 Dec 2024 01:33:56 +0300 Subject: [PATCH 103/130] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=202=20=D1=8E=D0=BD=D0=B8=D1=82=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/RenewAuthToken/CommandTest.php | 42 +++++++++++++++++++ .../UseCase/Uninstall/CommandTest.php | 24 +++++++++++ 2 files changed, 66 insertions(+) create mode 100644 tests/Unit/Bitrix24Accounts/UseCase/RenewAuthToken/CommandTest.php create mode 100644 tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php diff --git a/tests/Unit/Bitrix24Accounts/UseCase/RenewAuthToken/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/RenewAuthToken/CommandTest.php new file mode 100644 index 0000000..4a12cf4 --- /dev/null +++ b/tests/Unit/Bitrix24Accounts/UseCase/RenewAuthToken/CommandTest.php @@ -0,0 +1,42 @@ +withStatus(Bitrix24AccountStatus::new) + ->build(); + + $newAuthToken = new AuthToken('new_1', 'new_2', 3600); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Bitrix24 User ID must be a positive integer.'); + + new Command( + new RenewedAuthToken( + $newAuthToken, + $bitrix24Account->getMemberId(), + 'https://client-endpoint.com', + 'https://server-endpoint.com', + ApplicationStatus::subscription(), + $bitrix24Account->getDomainUrl() + ), + ); + } +} \ No newline at end of file diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php new file mode 100644 index 0000000..48a4613 --- /dev/null +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -0,0 +1,24 @@ +expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Empty application token or invalid application token.'); + + new Command('123_test_string'); + } +} \ No newline at end of file From 98eb191574b7dbfcbd073c77c2d846fa9d8c1a9c Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 5 Jan 2025 19:01:55 +0300 Subject: [PATCH 104/130] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=B2=20=D1=82=D0=B5=D1=81=D1=82=20=D0=BD=D0=B0=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2=D1=82=D0=BE=D1=80=D0=BD=D1=83=D1=8E=20=D1=83=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D1=83=20=D0=B0=D0=BA=D0=BA=D0=B0?= =?UTF-8?q?=D1=83=D0=BD=D1=82=D0=B0=20=D0=A3=D0=B4=D0=B0=D0=BB=D0=B8=D0=BB?= =?UTF-8?q?=20=D1=82=D0=B5=D1=81=D1=82=20=D0=BD=D0=B0=20=D0=BE=D0=B1=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=82=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D1=82=D0=B0=D0=BA=20=D0=BA=D0=B0=D0=BA=20?= =?UTF-8?q?=D1=82=D0=B0=D0=BC=20=D0=BD=D0=B5=D1=87=D0=B5=D0=B3=D0=BE=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D1=8F=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Doctrine/Bitrix24AccountRepository.php | 2 +- .../UseCase/InstallFinish/Command.php | 4 -- .../UseCase/InstallStart/Handler.php | 24 +++++++---- .../UseCase/RenewAuthToken/Command.php | 10 ----- .../UseCase/InstallFinish/HandlerTest.php | 2 +- .../UseCase/InstallStart/HandlerTest.php | 17 ++++++-- .../UseCase/RenewAuthToken/CommandTest.php | 42 ------------------- 7 files changed, 31 insertions(+), 70 deletions(-) delete mode 100644 tests/Unit/Bitrix24Accounts/UseCase/RenewAuthToken/CommandTest.php diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 5d86017..2621722 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -41,7 +41,7 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface ->setParameter('id', $uuid) ->setParameter('status', Bitrix24AccountStatus::deleted) ->getQuery() - ->getOneOrNullResult(); + ->getOneOrNullResult(); // $account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); if (null === $account) { throw new Bitrix24AccountNotFoundException( diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index 9149646..f40ce9e 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -25,10 +25,6 @@ private function validate(): void if (empty($this->memberId)) { throw new InvalidArgumentException('Member ID cannot be empty.'); } - /*$pattern = '/^(https?:\/\/)?([a-z0-9-]+\.[a-z]{2,})(\/[^\s]*)?$/i'; - if (!preg_match($pattern, $this->domainUrl)) { - throw new InvalidArgumentException('Domain URL is not valid.'); - }*/ if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { throw new InvalidArgumentException('Domain URL is not valid.'); } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index f54133f..32fe1c6 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -44,15 +44,21 @@ public function handle(Command $command): void $command->applicationScope, true ); - $this->bitrix24AccountRepository->save($bitrix24Account); - $this->flusher->flush($bitrix24Account); - - $this->logger->info('Bitrix24Accounts.InstallStart.Finish', - [ - 'id' => $command->uuid->toRfc4122(), - 'domain_url' => $command->domainUrl, - 'member_id' => $command->memberId, - ]); + + $isAccountExists = $this->bitrix24AccountRepository->existsById($bitrix24Account->getId()); + + if (!$isAccountExists) { + $this->bitrix24AccountRepository->save($bitrix24Account); + $this->flusher->flush($bitrix24Account); + + $this->logger->info('Bitrix24Accounts.InstallStart.Finish', + [ + 'id' => $command->uuid->toRfc4122(), + 'domain_url' => $command->domainUrl, + 'member_id' => $command->memberId, + ]); + } + } } diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php index acd8276..63d2b6a 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php @@ -5,21 +5,11 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\RenewAuthToken; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; -use Symfony\Component\Uid\Uuid; -use InvalidArgumentException; readonly class Command { public function __construct( public RenewedAuthToken $renewedAuthToken, public ?int $bitrix24UserId = null, ) { - $this->validate(); - } - - private function validate(): void - { - if ($this->bitrix24UserId <= 0) { - throw new InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); - } } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 29cc2f1..eccc111 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -65,7 +65,7 @@ public function testFinishInstallationWithHappyPath(): void ); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertEquals('active', $updated->getStatus()->value,'expected status is active'); + $this->assertEquals(Bitrix24AccountStatus::active, $updated->getStatus(),'expected status is active'); $this->assertTrue( $updated->isApplicationTokenValid($applicationToken), sprintf('failed application token «%s» validation for bitrix24 account with id «%s»', diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index a26e919..5c449fc 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -34,7 +34,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; -use Doctrine\ORM\Exception\EntityIdentityCollisionException; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; /** * @internal */ @@ -169,7 +169,7 @@ public function testInstallStartHappyPath(): void } #[Test] - public function testReinstallApplication(): void + public function testCreateExistingAccount(): void { $uuidV7 = Uuid::v7(); $b24UserId = random_int(1, 100_000); @@ -192,7 +192,6 @@ public function testReinstallApplication(): void ) ); - $this->expectException(EntityIdentityCollisionException::class); $this->handler->handle( new Bitrix24Accounts\UseCase\InstallStart\Command( $uuidV7, @@ -206,5 +205,17 @@ public function testReinstallApplication(): void ) ); + $accounts = $this->repository->find(['id' => $uuidV7]); + + if ($accounts instanceof Bitrix24AccountInterface) { + // Если это один объект, количество будет 1 + $count = 1; + } else { + // Если ничего не найдено, количество будет 0 + $count = 0; + } + + $this->assertEquals(1, $count); + } } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/RenewAuthToken/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/RenewAuthToken/CommandTest.php deleted file mode 100644 index 4a12cf4..0000000 --- a/tests/Unit/Bitrix24Accounts/UseCase/RenewAuthToken/CommandTest.php +++ /dev/null @@ -1,42 +0,0 @@ -withStatus(Bitrix24AccountStatus::new) - ->build(); - - $newAuthToken = new AuthToken('new_1', 'new_2', 3600); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Bitrix24 User ID must be a positive integer.'); - - new Command( - new RenewedAuthToken( - $newAuthToken, - $bitrix24Account->getMemberId(), - 'https://client-endpoint.com', - 'https://server-endpoint.com', - ApplicationStatus::subscription(), - $bitrix24Account->getDomainUrl() - ), - ); - } -} \ No newline at end of file From 92347d8abb5b3ad7069955c5c64e2a43d8b75039 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 5 Jan 2025 22:08:33 +0300 Subject: [PATCH 105/130] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=B2=20=D1=82=D0=B5=D1=81=D1=82=20=D0=BD=D0=B0=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2=D1=82=D0=BE=D1=80=D0=BD=D1=83=D1=8E=20=D1=83=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D1=83=20=D0=B0=D0=BA=D0=BA=D0=B0?= =?UTF-8?q?=D1=83=D0=BD=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/InstallStart/Handler.php | 15 ++- .../Builders/Bitrix24AccountBuilder.php | 8 +- .../UseCase/InstallStart/HandlerTest.php | 124 ++++++++---------- .../UseCase/Uninstall/HandlerTest.php | 5 - 4 files changed, 78 insertions(+), 74 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index 32fe1c6..981149b 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -7,6 +7,7 @@ use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Carbon\CarbonImmutable; use Psr\Log\LoggerInterface; @@ -57,8 +58,18 @@ public function handle(Command $command): void 'domain_url' => $command->domainUrl, 'member_id' => $command->memberId, ]); - } - + }else{ + $this->logger->info('Bitrix24Accounts.InstallStart.AlreadyExists', + [ + 'id' => $command->uuid->toRfc4122(), + 'domain_url' => $command->domainUrl, + 'member_id' => $command->memberId, + ] + ); + throw new Bitrix24AccountNotFoundException( + sprintf('bitrix24account with uuid "%s" already exists', $command->uuid->toRfc4122()) + ); + } } } diff --git a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php index 4e6fc7a..813c644 100644 --- a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php +++ b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php @@ -45,7 +45,7 @@ class Bitrix24AccountBuilder private readonly int $applicationVersion; - private readonly Scope $applicationScope; + private Scope $applicationScope; private ?string $applicationToken = null; @@ -75,6 +75,12 @@ public function withDomainUrl(string $domainUrl): self return $this; } + public function withApplicationScope(Scope $applicationScope): self + { + $this->applicationScope = $applicationScope; + return $this; + } + public function withApplicationToken(string $applicationToken): self { $this->applicationToken = $applicationToken; diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 5c449fc..877cf5e 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -17,6 +17,7 @@ use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountCreatedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; @@ -72,86 +73,82 @@ protected function setUp(): void #[Test] public function testInstallStartHappyPath(): void { - $uuidV7 = Uuid::v7(); - $b24UserId = random_int(1, 100_000); - $isB24UserAdmin = true; - $b24MemberId = Uuid::v7()->toRfc4122(); - $b24DomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; - $authToken = new AuthToken('old_1', 'old_2', 3600); - $appVersion = 1; - $scope = new Scope(['crm']); + $bitrix24AccountBuilder = (new Bitrix24AccountBuilder()) + ->withApplicationScope(new Scope(['crm'])) + ->build(); + $this->handler->handle( new Bitrix24Accounts\UseCase\InstallStart\Command( - $uuidV7, - $b24UserId, - $isB24UserAdmin, - $b24MemberId, - $b24DomainUrl, - $authToken, - $appVersion, - $scope + $bitrix24AccountBuilder->getId(), + $bitrix24AccountBuilder->getBitrix24UserId(), + $bitrix24AccountBuilder->isBitrix24UserAdmin(), + $bitrix24AccountBuilder->getMemberId(), + $bitrix24AccountBuilder->getDomainUrl(), + $bitrix24AccountBuilder->getAuthToken(), + $bitrix24AccountBuilder->getApplicationVersion(), + $bitrix24AccountBuilder->getApplicationScope() ) ); - $bitrix24Account = $this->repository->getById($uuidV7); + $bitrix24Account = $this->repository->getById($bitrix24AccountBuilder->getId()); $this->assertEquals( - $b24UserId, + $bitrix24AccountBuilder->getBitrix24UserId(), $bitrix24Account->getBitrix24UserId(), sprintf( 'Expected the property value to be "%s", but got "%s"', - $b24UserId, + $bitrix24AccountBuilder->getBitrix24UserId(), $bitrix24Account->getBitrix24UserId() ) ); $this->assertEquals( - $isB24UserAdmin, + $bitrix24AccountBuilder->isBitrix24UserAdmin(), $bitrix24Account->isBitrix24UserAdmin(), sprintf( 'Expected the property value to be "%s", but got "%s"', - $isB24UserAdmin, + $bitrix24AccountBuilder->isBitrix24UserAdmin(), $bitrix24Account->isBitrix24UserAdmin() ) ); $this->assertEquals( - $b24MemberId, + $bitrix24AccountBuilder->getMemberId(), $bitrix24Account->getMemberId(), sprintf( 'Expected the property value to be "%s", but got "%s"', - $b24MemberId, + $bitrix24AccountBuilder->getMemberId(), $bitrix24Account->getMemberId() ) ); $this->assertEquals( - $b24DomainUrl, + $bitrix24AccountBuilder->getDomainUrl(), $bitrix24Account->getDomainUrl(), sprintf( 'Expected the property value to be "%s", but got "%s"', - $b24DomainUrl, + $bitrix24AccountBuilder->getDomainUrl(), $bitrix24Account->getDomainUrl() ) ); $this->assertEquals( - $authToken, + $bitrix24AccountBuilder->getAuthToken(), $bitrix24Account->getAuthToken(), 'Object not equals' ); $this->assertEquals( - $appVersion, + $bitrix24AccountBuilder->getApplicationVersion(), $bitrix24Account->getApplicationVersion(), sprintf( 'Expected the property value to be "%s", but got "%s"', - $appVersion, + $bitrix24AccountBuilder->getApplicationVersion(), $bitrix24Account->getApplicationVersion() ) ); $this->assertEquals( - $scope, + $bitrix24AccountBuilder->getApplicationScope(), $bitrix24Account->getApplicationScope(), 'Object not equals' ); @@ -168,54 +165,49 @@ public function testInstallStartHappyPath(): void ); } + /** + * @throws Bitrix24AccountNotFoundException + * @throws InvalidArgumentException + * @throws UnknownScopeCodeException + */ #[Test] public function testCreateExistingAccount(): void { - $uuidV7 = Uuid::v7(); - $b24UserId = random_int(1, 100_000); - $isB24UserAdmin = true; - $b24MemberId = Uuid::v7()->toRfc4122(); - $b24DomainUrl = 'https://'.Uuid::v7()->toRfc4122().'-test.bitrix24.com'; - $authToken = new AuthToken('old_1', 'old_2', 3600); - $appVersion = 1; - $scope = new Scope(['crm']); + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withApplicationScope(new Scope(['crm'])) + ->build(); + + $this->handler->handle( new Bitrix24Accounts\UseCase\InstallStart\Command( - $uuidV7, - $b24UserId, - $isB24UserAdmin, - $b24MemberId, - $b24DomainUrl, - $authToken, - $appVersion, - $scope + $bitrix24Account->getId(), + $bitrix24Account->getBitrix24UserId(), + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getAuthToken(), + $bitrix24Account->getApplicationVersion(), + $bitrix24Account->getApplicationScope() ) ); + + $this->expectException(Bitrix24AccountNotFoundException::class); + $this->expectExceptionMessage( + sprintf('bitrix24account with uuid "%s" already exists', $bitrix24Account->getId()) + ); + $this->handler->handle( new Bitrix24Accounts\UseCase\InstallStart\Command( - $uuidV7, - $b24UserId, - $isB24UserAdmin, - $b24MemberId, - $b24DomainUrl, - $authToken, - $appVersion, - $scope + $bitrix24Account->getId(), + $bitrix24Account->getBitrix24UserId(), + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getAuthToken(), + $bitrix24Account->getApplicationVersion(), + $bitrix24Account->getApplicationScope() ) ); - - $accounts = $this->repository->find(['id' => $uuidV7]); - - if ($accounts instanceof Bitrix24AccountInterface) { - // Если это один объект, количество будет 1 - $count = 1; - } else { - // Если ничего не найдено, количество будет 0 - $count = 0; - } - - $this->assertEquals(1, $count); - } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 5d6c113..25a5118 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -13,8 +13,6 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\Uninstall; -use Bitrix24\Lib\AggregateRoot; -use Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; use Bitrix24\Lib\Bitrix24Accounts; @@ -24,10 +22,7 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationUninstalledEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\SDK\Core\Credentials\AuthToken; -use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; -use Carbon\CarbonImmutable; use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; From 56eb727be60963ea2f06d6c8e13a8b1bdc263118 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Thu, 9 Jan 2025 23:29:50 +0300 Subject: [PATCH 106/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B4=D0=B0=D1=82=D0=B0=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B0=D0=B9=D0=B4=D0=B5=D1=80=20=D0=B2=20=D0=BE=D0=B4=D0=BD?= =?UTF-8?q?=D0=BE=D0=BC=20=D0=B8=D0=B7=20=D1=82=D0=B5=D1=81=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=BD=D0=B0=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=83.=20-=20=D0=92=D0=BD=D0=B5=D1=81=20=D0=B5=D1=89=D0=B5=20?= =?UTF-8?q?=D0=BD=D0=B5=D0=BA=D0=BE=D1=82=D0=BE=D1=80=D1=8B=D0=B5=20=D0=BC?= =?UTF-8?q?=D0=B5=D0=BB=D0=BA=D0=B8=D0=B5=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entity/Bitrix24Account.php | 10 +- .../UseCase/InstallStart/Command.php | 4 +- .../UseCase/RenewAuthToken/Command.php | 2 +- .../UseCase/Uninstall/Command.php | 4 +- .../UseCase/InstallStart/HandlerTest.php | 8 ++ .../UseCase/RenewAuthToken/HandlerTest.php | 3 +- .../UseCase/InstallFinish/CommandTest.php | 93 +++++++++---------- .../UseCase/Uninstall/CommandTest.php | 4 +- 8 files changed, 64 insertions(+), 64 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 8c84f92..f0dab56 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -195,14 +195,14 @@ public function applicationInstalled(string $applicationToken): void ); } - private function guardEmpty($applicationToken) + private function guardEmptyToken($applicationToken) { if ('' === $applicationToken) { throw new InvalidArgumentException('application token cannot be empty'); } } - private function guardTokenMismatch($applicationToken) + private function guardTokenMismatch($applicationToken): void { if ($this->applicationToken !== $applicationToken) { throw new InvalidArgumentException( @@ -217,7 +217,7 @@ private function guardTokenMismatch($applicationToken) } } - private function guardStatusIsActive() + private function guardApplicationIsActive(): void { if (Bitrix24AccountStatus::active !== $this->status) { throw new InvalidArgumentException( @@ -236,9 +236,9 @@ private function guardStatusIsActive() public function applicationUninstalled(string $applicationToken): void { - $this->guardEmpty($applicationToken); + $this->guardEmptyToken($applicationToken); $this->guardTokenMismatch($applicationToken); - $this->guardStatusIsActive(); + $this->guardApplicationIsActive(); $this->status = Bitrix24AccountStatus::deleted; $this->updatedAt = new CarbonImmutable(); $this->events[] = new Bitrix24AccountApplicationUninstalledEvent( diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index ff97cfd..a5bf6c4 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -27,8 +27,8 @@ public function __construct( private function validate(): void { - if (empty($this->uuid) || !Uuid::isValid($this->uuid->toString())) { - throw new InvalidArgumentException('Empty uuid or invalid UUID provided.'); + if (empty($this->uuid)) { + throw new InvalidArgumentException('Empty UUID provided.'); } if ($this->bitrix24UserId <= 0) { diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php index 63d2b6a..a401900 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php @@ -9,7 +9,7 @@ { public function __construct( public RenewedAuthToken $renewedAuthToken, - public ?int $bitrix24UserId = null, + public int $bitrix24UserId, ) { } } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php index 7134c12..8cb836b 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php @@ -20,8 +20,8 @@ public function __construct( private function validate(): void { - if (empty($this->applicationToken) || !Uuid::isValid($this->applicationToken)) { - throw new InvalidArgumentException('Empty application token or invalid application token.'); + if (empty($this->applicationToken)) { + throw new InvalidArgumentException('Empty application token application token.'); } } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 877cf5e..e3edb3d 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -210,4 +210,12 @@ public function testCreateExistingAccount(): void ) ); } + + #[Test] + public function testUpdateAppVersion(): void + { + + } + + } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 621d3fa..340913e 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -78,7 +78,8 @@ public function testRenewAuthTokenWithoutBitrix24UserId(): void 'https://server-endpoint.com', ApplicationStatus::subscription(), $bitrix24Account->getDomainUrl() - ) + ), + $bitrix24Account->getBitrix24UserId() ) ); $updated = $this->repository->getById($bitrix24Account->getId()); diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index 1b1bc2e..b4bbc1a 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -9,87 +9,78 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; use Symfony\Component\Uid\Uuid; +use Generator; #[CoversClass(Command::class)] class CommandTest extends TestCase { + #[Test] - #[TestDox('test finish installation for Command')] - public function testValidCommand(): void + #[DataProvider('dataForCommand')] + public function testValidCommand( + string $applicationToken, + string $memberId, + string $domainUrl, + int $bitrix24UserId, + ?string $expectedException, + ?string $expectedExceptionMessage, + ) { - $bitrix24Account = (new Bitrix24AccountBuilder()) - ->withStatus(Bitrix24AccountStatus::new) - ->build(); - $applicationToken = Uuid::v7()->toRfc4122(); + if ($expectedException !== null) { + $this->expectException($expectedException); + } - $command = new Command( + if ($expectedExceptionMessage !== null) { + $this->expectExceptionMessage($expectedExceptionMessage); + } + + new Command( $applicationToken, - $bitrix24Account->getMemberId(), - $bitrix24Account->getDomainUrl(), - $bitrix24Account->getBitrix24UserId() + $memberId, + $domainUrl, + $bitrix24UserId ); - $this->assertInstanceOf(Command::class, $command); + } - public function testEmptyApplicationToken(): void + public static function dataForCommand(): Generator { + $applicationToken = Uuid::v7()->toRfc4122(); $bitrix24Account = (new Bitrix24AccountBuilder()) ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Application token cannot be empty.'); - - new Command( + yield 'emptyApplicationToken' => [ '', $bitrix24Account->getMemberId(), $bitrix24Account->getDomainUrl(), - $bitrix24Account->getBitrix24UserId() - ); - } + $bitrix24Account->getBitrix24UserId(), + InvalidArgumentException::class, + 'Application token cannot be empty.' + ]; - - public function testEmptyMemberId(): void - { - $bitrix24Account = (new Bitrix24AccountBuilder()) - ->withStatus(Bitrix24AccountStatus::new) - ->build(); - - $applicationToken = Uuid::v7()->toRfc4122(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Member ID cannot be empty.'); - - new Command( + yield 'emptyMemberId' => [ $applicationToken, '', $bitrix24Account->getDomainUrl(), - $bitrix24Account->getBitrix24UserId() - ); - } + $bitrix24Account->getBitrix24UserId(), + InvalidArgumentException::class, + 'Member ID cannot be empty.' + ]; - public function testValidDomainUrl(): void - { - $bitrix24Account = (new Bitrix24AccountBuilder()) - ->withStatus(Bitrix24AccountStatus::new) - ->build(); - - $applicationToken = Uuid::v7()->toRfc4122(); - - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Domain URL is not valid.'); - - new Command( + yield 'validDomainUrl' => [ $applicationToken, $bitrix24Account->getMemberId(), '', - $bitrix24Account->getBitrix24UserId() - ); + $bitrix24Account->getBitrix24UserId(), + InvalidArgumentException::class, + 'Domain URL is not valid.' + ]; + } } \ No newline at end of file diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php index 48a4613..9ca39c4 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -17,8 +17,8 @@ public function testValidApplicationToken(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Empty application token or invalid application token.'); + $this->expectExceptionMessage('Empty application token application token.'); - new Command('123_test_string'); + new Command(''); } } \ No newline at end of file From a33d77f449e297f3c05ac74612e0e7c6e9f545e9 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 11 Jan 2025 15:29:52 +0300 Subject: [PATCH 107/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B3=D0=B5=D0=BD=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=20=D0=B4=D0=BB=D1=8F=20=D0=B2=D1=81=D0=B5=D1=85=20=D1=82?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/ChangeDomainUrl/CommandTest.php | 31 +++-- .../UseCase/InstallStart/CommandTest.php | 113 +++++++++++------- .../UseCase/Uninstall/CommandTest.php | 34 +++++- 3 files changed, 119 insertions(+), 59 deletions(-) diff --git a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php index f8543f5..3eae626 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php @@ -7,25 +7,42 @@ use Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl\Command; use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; - +use Generator; use Symfony\Component\Uid\Uuid; #[CoversClass(Command::class)] class CommandTest extends TestCase { - - public function testValidDomainUrl(): void + #[Test] + #[DataProvider('dataForCommand')] + public function testValidCommand( + string $oldDomainUrl, + string $newDomainUrl, + ?string $expectedException + ) { - $oldDomainUrl = 'https://'.Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; - $newDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; - $this->expectException(InvalidArgumentException::class); + if ($expectedException !== null) { + $this->expectException($expectedException); + } + new Command($oldDomainUrl, $newDomainUrl); + } - protected function setUp(): void + public static function dataForCommand(): Generator { + $oldDomainUrl = 'https://'.Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $newDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + + yield 'validDomainUrl' => [ + $oldDomainUrl, + $newDomainUrl, + InvalidArgumentException::class + ]; } } \ No newline at end of file diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php index 21079f3..dea6fa8 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php @@ -7,44 +7,65 @@ use Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallStart\Command; use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Core\Credentials\AuthToken; +use Bitrix24\SDK\Core\Credentials\Scope; use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use Symfony\Component\Uid\Uuid; +use Generator; #[CoversClass(Command::class)] class CommandTest extends TestCase { - public function testValidBitrix24UserId(): void + + #[Test] + #[DataProvider('dataForCommand')] + public function testValidCommand( + Uuid $uuid, + int $bitrix24UserId, + bool $isBitrix24UserAdmin, + string $memberId, + string $domainUrl, + AuthToken $authToken, + int $applicationVersion, + Scope $applicationScope, + ?string $expectedException, + ?string $expectedExceptionMessage, + ) { - $bitrix24Account = (new Bitrix24AccountBuilder()) - ->withStatus(Bitrix24AccountStatus::new) - ->build(); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Bitrix24 User ID must be a positive integer.'); + if ($expectedException !== null) { + $this->expectException($expectedException); + } + + if ($expectedExceptionMessage !== null) { + $this->expectExceptionMessage($expectedExceptionMessage); + } new Command( - $bitrix24Account->getId(), - 0, - $bitrix24Account->isBitrix24UserAdmin(), - $bitrix24Account->getMemberId(), - $bitrix24Account->getDomainUrl(), - $bitrix24Account->getAuthToken(), - $bitrix24Account->getApplicationVersion(), - $bitrix24Account->getApplicationScope() + $uuid, + $bitrix24UserId, + $isBitrix24UserAdmin, + $memberId, + $domainUrl, + $authToken, + $applicationVersion, + $applicationScope ); + } - public function testValidMemberId(): void + public static function dataForCommand(): Generator { + $applicationToken = Uuid::v7()->toRfc4122(); $bitrix24Account = (new Bitrix24AccountBuilder()) ->withStatus(Bitrix24AccountStatus::new) ->build(); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Member ID must be a non-empty string.'); - - new Command( + yield 'emptyMemberId' => [ $bitrix24Account->getId(), $bitrix24Account->getBitrix24UserId(), $bitrix24Account->isBitrix24UserAdmin(), @@ -52,20 +73,12 @@ public function testValidMemberId(): void $bitrix24Account->getDomainUrl(), $bitrix24Account->getAuthToken(), $bitrix24Account->getApplicationVersion(), - $bitrix24Account->getApplicationScope() - ); - } + $bitrix24Account->getApplicationScope(), + InvalidArgumentException::class, + 'Member ID must be a non-empty string.' + ]; - public function testValidDomainUrl(): void - { - $bitrix24Account = (new Bitrix24AccountBuilder()) - ->withStatus(Bitrix24AccountStatus::new) - ->build(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Domain URL is not valid.'); - - new Command( + yield 'validDomainUrl' => [ $bitrix24Account->getId(), $bitrix24Account->getBitrix24UserId(), $bitrix24Account->isBitrix24UserAdmin(), @@ -73,20 +86,25 @@ public function testValidDomainUrl(): void '', $bitrix24Account->getAuthToken(), $bitrix24Account->getApplicationVersion(), - $bitrix24Account->getApplicationScope() - ); - } - - public function testValidApplicationVersion(): void - { - $bitrix24Account = (new Bitrix24AccountBuilder()) - ->withStatus(Bitrix24AccountStatus::new) - ->build(); + $bitrix24Account->getApplicationScope(), + InvalidArgumentException::class, + 'Domain URL is not valid.' + ]; - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Application version must be a positive integer.'); + yield 'validBitrix24UserId' => [ + $bitrix24Account->getId(), + 0, + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + $bitrix24Account->getDomainUrl(), + $bitrix24Account->getAuthToken(), + $bitrix24Account->getApplicationVersion(), + $bitrix24Account->getApplicationScope(), + InvalidArgumentException::class, + 'Bitrix24 User ID must be a positive integer.' + ]; - new Command( + yield 'validApplicationToken' => [ $bitrix24Account->getId(), $bitrix24Account->getBitrix24UserId(), $bitrix24Account->isBitrix24UserAdmin(), @@ -94,7 +112,10 @@ public function testValidApplicationVersion(): void $bitrix24Account->getDomainUrl(), $bitrix24Account->getAuthToken(), 0, - $bitrix24Account->getApplicationScope() - ); + $bitrix24Account->getApplicationScope(), + InvalidArgumentException::class, + 'Application version must be a positive integer.' + ]; + } } \ No newline at end of file diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php index 9ca39c4..aa4bdfa 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -7,18 +7,40 @@ use Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall\Command; use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Symfony\Component\Uid\Uuid; - +use Generator; #[CoversClass(Command::class)] class CommandTest extends TestCase { - public function testValidApplicationToken(): void + #[Test] + #[DataProvider('dataForCommand')] + public function testValidCommand( + string $applicationToken, + ?string $expectedException, + ?string $expectedExceptionMessage, + ) { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Empty application token application token.'); + if ($expectedException !== null) { + $this->expectException($expectedException); + } + + if ($expectedExceptionMessage !== null) { + $this->expectExceptionMessage($expectedExceptionMessage); + } + + new Command($applicationToken); - new Command(''); + } + + public static function dataForCommand(): Generator + { + yield 'validApplicationToken' => [ + '', + InvalidArgumentException::class, + 'Empty application token application token.' + ]; } } \ No newline at end of file From 81a40a83740dcb987065cc6c94ba1b789f181793 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 11 Jan 2025 23:00:15 +0300 Subject: [PATCH 108/130] =?UTF-8?q?-=20=D1=8E=D0=B7=D0=B0=D0=BD=D1=83?= =?UTF-8?q?=D0=BB=20cs-fixer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 6 +- .../Entity/Bitrix24Account.php | 94 +++++++++---------- .../Doctrine/Bitrix24AccountRepository.php | 19 ++-- .../ReadModel/Bitrix24AccountFetcher.php | 28 +++--- .../UseCase/ChangeDomainUrl/Command.php | 7 +- .../UseCase/ChangeDomainUrl/Handler.php | 17 ++-- .../UseCase/InstallFinish/Command.php | 8 +- .../UseCase/InstallFinish/Handler.php | 20 ++-- .../UseCase/InstallStart/Command.php | 28 +++--- .../UseCase/InstallStart/Handler.php | 20 ++-- .../UseCase/RenewAuthToken/Command.php | 4 +- .../UseCase/RenewAuthToken/Handler.php | 17 ++-- .../UseCase/Uninstall/Command.php | 5 +- .../UseCase/Uninstall/Handler.php | 16 ++-- src/Services/Flusher.php | 7 +- 15 files changed, 143 insertions(+), 153 deletions(-) diff --git a/Makefile b/Makefile index 0bbd5b1..d61aebf 100644 --- a/Makefile +++ b/Makefile @@ -16,6 +16,10 @@ include $(ENV) -include $(ENV_LOCAL) + +coding-standards: vendor + vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php --diff --verbose + default: @echo "make needs target:" @egrep -e '^\S+' ./Makefile | grep -v default | sed -r 's/://' | sed -r 's/^/ - /' @@ -106,7 +110,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testUninstallWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testCreateExistingAccount' tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index f0dab56..597c68d 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -36,21 +36,20 @@ class Bitrix24Account extends AggregateRoot implements Bitrix24AccountInterface private ?string $comment = null; public function __construct( - private readonly Uuid $id, - private readonly int $bitrix24UserId, - private readonly bool $isBitrix24UserAdmin, + private readonly Uuid $id, + private readonly int $bitrix24UserId, + private readonly bool $isBitrix24UserAdmin, /** bitrix24 portal unique id */ - private readonly string $memberId, - private string $domainUrl, - private Bitrix24AccountStatus $status, - private AuthToken $authToken, + private readonly string $memberId, + private string $domainUrl, + private Bitrix24AccountStatus $status, + private AuthToken $authToken, private readonly CarbonImmutable $createdAt, - private CarbonImmutable $updatedAt, - private int $applicationVersion, - private Scope $applicationScope, - bool $isEmitBitrix24AccountCreatedEvent = false, - ) - { + private CarbonImmutable $updatedAt, + private int $applicationVersion, + private Scope $applicationScope, + bool $isEmitBitrix24AccountCreatedEvent = false, + ) { $this->addAccountCreatedEventIfNeeded($isEmitBitrix24AccountCreatedEvent); } @@ -195,47 +194,12 @@ public function applicationInstalled(string $applicationToken): void ); } - private function guardEmptyToken($applicationToken) - { - if ('' === $applicationToken) { - throw new InvalidArgumentException('application token cannot be empty'); - } - } - - private function guardTokenMismatch($applicationToken): void - { - if ($this->applicationToken !== $applicationToken) { - throw new InvalidArgumentException( - sprintf( - 'application token «%s» mismatch with application token «%s» for bitrix24 account %s for domain %s', - $applicationToken, - $this->applicationToken, - $this->id->toRfc4122(), - $this->domainUrl - ) - ); - } - } - - private function guardApplicationIsActive(): void - { - if (Bitrix24AccountStatus::active !== $this->status) { - throw new InvalidArgumentException( - sprintf( - 'for uninstall account must be in status «active», current status - «%s»', - $this->status->name - ) - ); - } - } - /** * @throws InvalidArgumentException */ #[\Override] public function applicationUninstalled(string $applicationToken): void { - $this->guardEmptyToken($applicationToken); $this->guardTokenMismatch($applicationToken); $this->guardApplicationIsActive(); @@ -345,6 +309,40 @@ public function getComment(): ?string return $this->comment; } + private function guardEmptyToken($applicationToken) + { + if ('' === $applicationToken) { + throw new InvalidArgumentException('application token cannot be empty'); + } + } + + private function guardTokenMismatch($applicationToken): void + { + if ($this->applicationToken !== $applicationToken) { + throw new InvalidArgumentException( + sprintf( + 'application token «%s» mismatch with application token «%s» for bitrix24 account %s for domain %s', + $applicationToken, + $this->applicationToken, + $this->id->toRfc4122(), + $this->domainUrl + ) + ); + } + } + + private function guardApplicationIsActive(): void + { + if (Bitrix24AccountStatus::active !== $this->status) { + throw new InvalidArgumentException( + sprintf( + 'for uninstall account must be in status «active», current status - «%s»', + $this->status->name + ) + ); + } + } + private function addAccountCreatedEventIfNeeded(bool $isEmitCreatedEvent): void { if ($isEmitCreatedEvent) { diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 2621722..804b299 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -11,7 +11,6 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; -use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; use Symfony\Component\Uid\Uuid; @@ -20,8 +19,7 @@ class Bitrix24AccountRepository extends EntityRepository implements Bitrix24Acco { public function __construct( EntityManagerInterface $entityManager - ) - { + ) { parent::__construct($entityManager, $entityManager->getClassMetadata(Bitrix24Account::class)); } @@ -33,7 +31,6 @@ public function __construct( #[\Override] public function getById(Uuid $uuid): Bitrix24AccountInterface { - $account = $this->getEntityManager()->getRepository(Bitrix24Account::class) ->createQueryBuilder('b24') ->where('b24.id = :id') @@ -41,8 +38,8 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface ->setParameter('id', $uuid) ->setParameter('status', Bitrix24AccountStatus::deleted) ->getQuery() - ->getOneOrNullResult(); - // $account = $this->getEntityManager()->getRepository(Bitrix24Account::class)->find($uuid); + ->getOneOrNullResult(); + if (null === $account) { throw new Bitrix24AccountNotFoundException( sprintf('bitrix24 account not found by id %s', $uuid->toRfc4122()) @@ -83,10 +80,10 @@ public function save(Bitrix24AccountInterface $bitrix24Account): void */ #[\Override] public function findByMemberId( - string $memberId, + string $memberId, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, - ?int $bitrix24UserId = null, - ?bool $isAdmin = null + ?int $bitrix24UserId = null, + ?bool $isAdmin = null ): array { if ('' === trim($memberId)) { @@ -198,9 +195,9 @@ public function findOneAdminByMemberId(string $memberId): ?Bitrix24AccountInterf */ #[\Override] public function findByDomain( - string $domainUrl, + string $domainUrl, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, - ?bool $isAdmin = null + ?bool $isAdmin = null ): array { if ('' === trim($domainUrl)) { diff --git a/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php b/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php index b2a51c5..73b4900 100644 --- a/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php +++ b/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php @@ -7,9 +7,9 @@ use Doctrine\ORM\EntityManagerInterface; use Knp\Component\Pager\Pagination\PaginationInterface; use Knp\Component\Pager\PaginatorInterface; + class Bitrix24AccountFetcher { - public function __construct( private readonly EntityManagerInterface $em, private readonly PaginatorInterface $paginator @@ -19,19 +19,19 @@ public function list( int $page, int $size ): PaginationInterface { - $qb = $this->em->createQueryBuilder() - ->select( - 'b24account.id as id', - 'b24account.status as status', - 'b24account.memberId as member_id', - 'b24account.domainUrl as domain_url', - 'b24account.applicationVersion as application_version', - 'b24account.createdAt as created_at_utc', - 'b24account.updatedAt as updated_at_utc', - ) - ->from('Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account', 'b24account') - ->orderBy('b24account.createdAt', 'DESC'); + $qb = $this->em->createQueryBuilder() + ->select( + 'b24account.id as id', + 'b24account.status as status', + 'b24account.memberId as member_id', + 'b24account.domainUrl as domain_url', + 'b24account.applicationVersion as application_version', + 'b24account.createdAt as created_at_utc', + 'b24account.updatedAt as updated_at_utc', + ) + ->from('Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account', 'b24account') + ->orderBy('b24account.createdAt', 'DESC'); - return $this->paginator->paginate($qb, $page, $size); + return $this->paginator->paginate($qb, $page, $size); } } diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index 6d9308a..e488548 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -4,7 +4,6 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl; -use InvalidArgumentException; readonly class Command { public function __construct( @@ -16,9 +15,7 @@ public function __construct( * @var non-empty-string $newDomainUrlHost */ public string $newDomainUrlHost - ) - { - + ) { $this->validateDomain($oldDomainUrlHost, 'oldDomainUrlHost'); $this->validateDomain($newDomainUrlHost, 'newDomainUrlHost'); } @@ -26,7 +23,7 @@ public function __construct( private function validateDomain(string $domain, string $parameterName): void { if (empty($domain) || !filter_var($domain, FILTER_VALIDATE_URL)) { - throw new InvalidArgumentException(sprintf('Invalid value for %s: %s', $parameterName, $domain)); + throw new \InvalidArgumentException(sprintf('Invalid value for %s: %s', $parameterName, $domain)); } } } diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index c1a0b12..a5a8137 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -9,7 +9,6 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Psr\Log\LoggerInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; readonly class Handler { @@ -26,20 +25,22 @@ public function handle(Command $command): void 'b24_domain_url_new' => $command->newDomainUrlHost, ]); - /** @var Bitrix24AccountInterface[]|AggregateRootEventsEmitterInterface[] $accounts */ + /** @var AggregateRootEventsEmitterInterface[]|Bitrix24AccountInterface[] $accounts */ $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomainUrlHost); foreach ($accounts as $account) { $account->changeDomainUrl($command->newDomainUrlHost); $this->bitrix24AccountRepository->save($account); } - //используется как оператор распаковки (splat operator) для передачи массива как отдельных аргументов: + // используется как оператор распаковки (splat operator) для передачи массива как отдельных аргументов: $this->flusher->flush(...$accounts); - $this->logger->info('Bitrix24Accounts.ChangeDomainUrl.Finish', - [ - 'b24_domain_url_old' => $command->oldDomainUrlHost, - 'b24_domain_url_new' => $command->newDomainUrlHost, - ]); + $this->logger->info( + 'Bitrix24Accounts.ChangeDomainUrl.Finish', + [ + 'b24_domain_url_old' => $command->oldDomainUrlHost, + 'b24_domain_url_new' => $command->newDomainUrlHost, + ] + ); } } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index f40ce9e..946532e 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -3,7 +3,6 @@ declare(strict_types=1); namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; -use InvalidArgumentException; readonly class Command { @@ -19,14 +18,13 @@ public function __construct( private function validate(): void { if (empty($this->applicationToken)) { - throw new InvalidArgumentException('Application token cannot be empty.'); + throw new \InvalidArgumentException('Application token cannot be empty.'); } - if (empty($this->memberId)) { - throw new InvalidArgumentException('Member ID cannot be empty.'); + throw new \InvalidArgumentException('Member ID cannot be empty.'); } if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { - throw new InvalidArgumentException('Domain URL is not valid.'); + throw new \InvalidArgumentException('Domain URL is not valid.'); } } } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 037188d..f78eab9 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -13,7 +13,6 @@ use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Psr\Log\LoggerInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; readonly class Handler { @@ -37,7 +36,7 @@ public function handle(Command $command): void 'b24_user_id' => $command->bitrix24UserId, ]); - /** @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $bitrix24Account */ + /** @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId, $command->bitrix24UserId); $bitrix24Account->applicationInstalled($command->applicationToken); @@ -45,14 +44,15 @@ public function handle(Command $command): void $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush($bitrix24Account); - - $this->logger->info('Bitrix24Accounts.InstallFinish.Finish', - [ - 'b24_domain_url' => $command->domainUrl, - 'b24_member_id' => $command->memberId, - 'b24_application_id' => $command->applicationToken, - 'b24_user_id' => $command->bitrix24UserId, - ]); + $this->logger->info( + 'Bitrix24Accounts.InstallFinish.Finish', + [ + 'b24_domain_url' => $command->domainUrl, + 'b24_member_id' => $command->memberId, + 'b24_application_id' => $command->applicationToken, + 'b24_user_id' => $command->bitrix24UserId, + ] + ); } private function getSingleAccountByMemberId(string $domainUrl, string $memberId, ?int $bitrix24UserId): Bitrix24AccountInterface diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index a5bf6c4..89ac909 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -7,44 +7,42 @@ use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Symfony\Component\Uid\Uuid; -use InvalidArgumentException; readonly class Command { public function __construct( - public Uuid $uuid, - public int $bitrix24UserId, - public bool $isBitrix24UserAdmin, - public string $memberId, - public string $domainUrl, + public Uuid $uuid, + public int $bitrix24UserId, + public bool $isBitrix24UserAdmin, + public string $memberId, + public string $domainUrl, public AuthToken $authToken, - public int $applicationVersion, - public Scope $applicationScope - ) - { + public int $applicationVersion, + public Scope $applicationScope + ) { $this->validate(); } private function validate(): void { if (empty($this->uuid)) { - throw new InvalidArgumentException('Empty UUID provided.'); + throw new \InvalidArgumentException('Empty UUID provided.'); } if ($this->bitrix24UserId <= 0) { - throw new InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); + throw new \InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); } if (!is_string($this->memberId) || empty($this->memberId)) { - throw new InvalidArgumentException('Member ID must be a non-empty string.'); + throw new \InvalidArgumentException('Member ID must be a non-empty string.'); } if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { - throw new InvalidArgumentException('Domain URL is not valid.'); + throw new \InvalidArgumentException('Domain URL is not valid.'); } if ($this->applicationVersion <= 0) { - throw new InvalidArgumentException('Application version must be a positive integer.'); + throw new \InvalidArgumentException('Application version must be a positive integer.'); } } } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index 981149b..3f8f1d6 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -11,17 +11,14 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Carbon\CarbonImmutable; use Psr\Log\LoggerInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; readonly class Handler { public function __construct( private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) - { - } + private Flusher $flusher, + private LoggerInterface $logger + ) {} public function handle(Command $command): void { @@ -52,14 +49,17 @@ public function handle(Command $command): void $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush($bitrix24Account); - $this->logger->info('Bitrix24Accounts.InstallStart.Finish', + $this->logger->info( + 'Bitrix24Accounts.InstallStart.Finish', [ 'id' => $command->uuid->toRfc4122(), 'domain_url' => $command->domainUrl, 'member_id' => $command->memberId, - ]); - }else{ - $this->logger->info('Bitrix24Accounts.InstallStart.AlreadyExists', + ] + ); + } else { + $this->logger->info( + 'Bitrix24Accounts.InstallStart.AlreadyExists', [ 'id' => $command->uuid->toRfc4122(), 'domain_url' => $command->domainUrl, diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php index a401900..e33957d 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Command.php @@ -5,11 +5,11 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\RenewAuthToken; use Bitrix24\SDK\Core\Response\DTO\RenewedAuthToken; + readonly class Command { public function __construct( public RenewedAuthToken $renewedAuthToken, public int $bitrix24UserId, - ) { - } + ) {} } diff --git a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php index 1afff9f..5670338 100644 --- a/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php +++ b/src/Bitrix24Accounts/UseCase/RenewAuthToken/Handler.php @@ -16,11 +16,9 @@ { public function __construct( private Bitrix24AccountRepositoryInterface $bitrix24AccountRepository, - private Flusher $flusher, - private LoggerInterface $logger - ) - { - } + private Flusher $flusher, + private LoggerInterface $logger + ) {} /** * @throws MultipleBitrix24AccountsFoundException @@ -33,26 +31,27 @@ public function handle(Command $command): void 'bitrix24_user_id' => $command->bitrix24UserId, ]); - /** @var Bitrix24AccountInterface|AggregateRootEventsEmitterInterface $bitrix24Account */ + /** @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ $bitrix24Account = $this->getSingleAccountByMemberId( $command->renewedAuthToken->domain, $command->renewedAuthToken->memberId, $command->bitrix24UserId ); - $bitrix24Account->renewAuthToken($command->renewedAuthToken); $this->bitrix24AccountRepository->save($bitrix24Account); $this->flusher->flush($bitrix24Account); - $this->logger->info('Bitrix24Accounts.RenewAuthToken.finish', + $this->logger->info( + 'Bitrix24Accounts.RenewAuthToken.finish', [ 'domain_url' => $command->renewedAuthToken->domain, 'member_id' => $command->renewedAuthToken->memberId, 'bitrix24_user_id' => $command->bitrix24UserId, - ]); + ] + ); } /** diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php index 8cb836b..71138f5 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php @@ -4,9 +4,6 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall; -use InvalidArgumentException; -use Symfony\Component\Uid\Uuid; - readonly class Command { public function __construct( @@ -21,7 +18,7 @@ public function __construct( private function validate(): void { if (empty($this->applicationToken)) { - throw new InvalidArgumentException('Empty application token application token.'); + throw new \InvalidArgumentException('Empty application token application token.'); } } } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index 4a64d89..f72a088 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -6,12 +6,10 @@ use Bitrix24\Lib\Services\Flusher; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Psr\Log\LoggerInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; readonly class Handler { @@ -30,7 +28,7 @@ public function handle(Command $command): void 'b24_application_token' => $command->applicationToken, ]); - /** @var Bitrix24AccountInterface[]|AggregateRootEventsEmitterInterface[] $accounts */ + /** @var AggregateRootEventsEmitterInterface[]|Bitrix24AccountInterface[] $accounts */ $accounts = $this->bitrix24AccountRepository->findByApplicationToken($command->applicationToken); $accountsCount = count($accounts); foreach ($accounts as $account) { @@ -39,10 +37,12 @@ public function handle(Command $command): void } $this->flusher->flush(...$accounts); - $this->logger->info('Bitrix24Accounts.Uninstall.Finish', - [ - 'accountsCount' => $accountsCount, - 'b24_application_token' => $command->applicationToken, - ]); + $this->logger->info( + 'Bitrix24Accounts.Uninstall.Finish', + [ + 'accountsCount' => $accountsCount, + 'b24_application_token' => $command->applicationToken, + ] + ); } } diff --git a/src/Services/Flusher.php b/src/Services/Flusher.php index 9b8b8ab..bd33cdd 100644 --- a/src/Services/Flusher.php +++ b/src/Services/Flusher.php @@ -4,16 +4,17 @@ namespace Bitrix24\Lib\Services; - -use Bitrix24\Lib\AggregateRoot; use Bitrix24\SDK\Application\Contracts\Events\AggregateRootEventsEmitterInterface; use Doctrine\ORM\EntityManagerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; + class Flusher { private $em; private $eventDispatcher; - public function __construct(EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher) { + + public function __construct(EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher) + { $this->em = $em; $this->eventDispatcher = $eventDispatcher; } From 3fb5766ac690c631a86c9752d96a6a659bded999 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 11 Jan 2025 23:15:14 +0300 Subject: [PATCH 109/130] =?UTF-8?q?-=20=D1=8E=D0=B7=D0=B0=D0=BD=D1=83?= =?UTF-8?q?=D0=BB=20cs-fixer=20=D0=B4=D0=BB=D1=8F=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/EntityManagerFactory.php | 20 +++----- .../Builders/Bitrix24AccountBuilder.php | 9 +++- .../Bitrix24AccountRepositoryTest.php | 37 +++++++------- .../UseCase/ChangeDomainUrl/HandlerTest.php | 31 ++++++----- .../UseCase/InstallFinish/HandlerTest.php | 51 ++++++++++--------- .../UseCase/InstallStart/HandlerTest.php | 17 ++----- .../UseCase/RenewAuthToken/HandlerTest.php | 4 +- .../UseCase/Uninstall/HandlerTest.php | 51 ++++++++++--------- .../UseCase/ChangeDomainUrl/CommandTest.php | 23 ++++----- .../UseCase/InstallFinish/CommandTest.php | 26 ++++------ .../UseCase/InstallStart/CommandTest.php | 38 +++++++------- .../UseCase/Uninstall/CommandTest.php | 25 +++++---- tests/bootstrap.php | 11 ++-- 13 files changed, 168 insertions(+), 175 deletions(-) diff --git a/tests/EntityManagerFactory.php b/tests/EntityManagerFactory.php index 3cf197c..e3935cf 100644 --- a/tests/EntityManagerFactory.php +++ b/tests/EntityManagerFactory.php @@ -6,19 +6,16 @@ use Bitrix24\SDK\Core\Exceptions\WrongConfigurationException; use Carbon\Doctrine\CarbonImmutableType; - +use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Exception; +use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Exception\ORMException; use Doctrine\ORM\OptimisticLockException; -use Monolog\Logger; -use Symfony\Bridge\Doctrine\Types\UuidType; -use Doctrine\DBAL\DriverManager; -use Doctrine\ORM\EntityManager; use Doctrine\ORM\ORMSetup; -use Doctrine\DBAL\Types\Type; -use Monolog\Handler\StreamHandler; -use Monolog\Level; +use Symfony\Bridge\Doctrine\Types\UuidType; + class EntityManagerFactory { /** @@ -27,14 +24,13 @@ class EntityManagerFactory * @throws ORMException * @throws Exception */ - private static ?EntityManager $entityManager = null; public static function get(): EntityManagerInterface { - if (!self::$entityManager instanceof \Doctrine\ORM\EntityManager) { + if (!self::$entityManager instanceof EntityManager) { $paths = [ - dirname(__DIR__) . '/config/xml' + dirname(__DIR__).'/config/xml', ]; $isDevMode = true; @@ -78,4 +74,4 @@ public static function get(): EntityManagerInterface return self::$entityManager; } -} \ No newline at end of file +} diff --git a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php index 813c644..89423e8 100644 --- a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php +++ b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php @@ -55,7 +55,7 @@ public function __construct() $this->bitrix24UserId = random_int(1, 1_000_000); $this->isBitrix24UserAdmin = true; $this->memberId = Uuid::v4()->toRfc4122(); - $this->domainUrl = 'https://'.Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $this->domainUrl = 'https://'.Uuid::v7()->toRfc4122().'-test.bitrix24.com'; $this->authToken = new AuthToken('old_1', 'old_2', 3600); $this->createdAt = CarbonImmutable::now(); $this->updatedAt = CarbonImmutable::now(); @@ -66,30 +66,35 @@ public function __construct() public function withMemberId(string $memberId): self { $this->memberId = $memberId; + return $this; } public function withDomainUrl(string $domainUrl): self { $this->domainUrl = $domainUrl; + return $this; } public function withApplicationScope(Scope $applicationScope): self { $this->applicationScope = $applicationScope; + return $this; } public function withApplicationToken(string $applicationToken): self { $this->applicationToken = $applicationToken; + return $this; } public function withStatus(Bitrix24AccountStatus $bitrix24AccountStatus): self { $this->status = $bitrix24AccountStatus; + return $this; } @@ -109,7 +114,7 @@ public function build(): AggregateRootEventsEmitterInterface&Bitrix24AccountInte $this->applicationScope ); - if (isset($this->applicationToken) && $this->status == Bitrix24AccountStatus::new) { + if (isset($this->applicationToken) && Bitrix24AccountStatus::new == $this->status) { $account->applicationInstalled($this->applicationToken); } diff --git a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php index 177ce15..4736e55 100644 --- a/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php +++ b/tests/Functional/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepositoryTest.php @@ -26,29 +26,30 @@ use Bitrix24\SDK\Tests\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterfaceTest; use Bitrix24\SDK\Tests\Application\Contracts\TestRepositoryFlusherInterface; use Carbon\CarbonImmutable; -use Override; use PHPUnit\Framework\Attributes\CoversClass; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Uid\Uuid; +/** + * @internal + */ #[CoversClass(Bitrix24AccountRepository::class)] class Bitrix24AccountRepositoryTest extends Bitrix24AccountRepositoryInterfaceTest { - #[Override] + #[\Override] protected function createBitrix24AccountImplementation( - Uuid $uuid, - int $bitrix24UserId, - bool $isBitrix24UserAdmin, - string $memberId, - string $domainUrl, + Uuid $uuid, + int $bitrix24UserId, + bool $isBitrix24UserAdmin, + string $memberId, + string $domainUrl, Bitrix24AccountStatus $bitrix24AccountStatus, - AuthToken $authToken, - CarbonImmutable $createdAt, - CarbonImmutable $updatedAt, - int $applicationVersion, - Scope $applicationScope - ): Bitrix24AccountInterface - { + AuthToken $authToken, + CarbonImmutable $createdAt, + CarbonImmutable $updatedAt, + int $applicationVersion, + Scope $applicationScope + ): Bitrix24AccountInterface { return new Bitrix24Account( $uuid, $bitrix24UserId, @@ -64,18 +65,20 @@ protected function createBitrix24AccountImplementation( ); } - #[Override] + #[\Override] protected function createBitrix24AccountRepositoryImplementation(): Bitrix24AccountRepositoryInterface { $entityManager = EntityManagerFactory::get(); + return new Bitrix24AccountRepository($entityManager); } - #[Override] + #[\Override] protected function createRepositoryFlusherImplementation(): TestRepositoryFlusherInterface { $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); + return new FlusherDecorator(new Flusher($entityManager, $eventDispatcher)); } -} \ No newline at end of file +} diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index 784aad2..c21d48f 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -26,9 +26,10 @@ use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; -use Symfony\Component\EventDispatcher\EventDispatcher; + /** * @internal */ @@ -50,7 +51,7 @@ protected function setUp(): void $eventDispatcher = new EventDispatcher(); $this->repository = new Bitrix24AccountRepository($entityManager); $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); - $this->flusher = new Flusher($entityManager,$this->eventDispatcher); + $this->flusher = new Flusher($entityManager, $this->eventDispatcher); $this->handler = new Bitrix24Accounts\UseCase\ChangeDomainUrl\Handler( $this->repository, $this->flusher, @@ -62,8 +63,8 @@ protected function setUp(): void #[TestDox('Test change domain url with happy path - one account')] public function testChangeDomainUrlWithHappyPath(): void { - $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; - $newDomainUrl = 'new-' . $oldDomainUrl; + $oldDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; + $newDomainUrl = 'new-'.$oldDomainUrl; $bitrix24Account = (new Bitrix24AccountBuilder()) ->withDomainUrl($oldDomainUrl) @@ -89,10 +90,11 @@ public function testChangeDomainUrlWithHappyPath(): void ) ); - $this->assertTrue(in_array( - Bitrix24AccountDomainUrlChangedEvent::class, - $this->eventDispatcher->getOrphanedEvents(), - ), + $this->assertTrue( + in_array( + Bitrix24AccountDomainUrlChangedEvent::class, + $this->eventDispatcher->getOrphanedEvents(), + ), sprintf( 'Event %s was expected to be in the list of orphan events, but it is missing', Bitrix24AccountDomainUrlChangedEvent::class @@ -104,8 +106,8 @@ public function testChangeDomainUrlWithHappyPath(): void #[TestDox('Test change domain url with happy path - many accounts')] public function testChangeDomainUrlWithHappyPathForManyAccounts(): void { - $oldDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; - $newDomainUrl = 'new-' . $oldDomainUrl; + $oldDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; + $newDomainUrl = 'new-'.$oldDomainUrl; $b24MemberId = Uuid::v7()->toRfc4122(); $bitrix24AccountA = (new Bitrix24AccountBuilder()) @@ -143,10 +145,11 @@ public function testChangeDomainUrlWithHappyPathForManyAccounts(): void ); } - $this->assertTrue(in_array( - Bitrix24AccountDomainUrlChangedEvent::class, - $this->eventDispatcher->getOrphanedEvents() - ), + $this->assertTrue( + in_array( + Bitrix24AccountDomainUrlChangedEvent::class, + $this->eventDispatcher->getOrphanedEvents() + ), sprintf( 'Event %s was expected to be in the list of orphan events, but it is missing', Bitrix24AccountDomainUrlChangedEvent::class diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index eccc111..0b1d67b 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -13,15 +13,14 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\InstallFinish; +use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; -use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountApplicationInstalledEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\Attributes\TestDox; @@ -32,6 +31,9 @@ use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; +/** + * @internal + */ #[CoversClass(Bitrix24Accounts\UseCase\InstallFinish\Handler::class)] class HandlerTest extends TestCase { @@ -43,6 +45,22 @@ class HandlerTest extends TestCase private TraceableEventDispatcher $eventDispatcher; + #[\Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager, $this->eventDispatcher); + + $this->handler = new Bitrix24Accounts\UseCase\InstallFinish\Handler( + $this->repository, + $this->flusher, + new NullLogger() + ); + } + #[Test] #[TestDox('test finish installation with happy path')] public function testFinishInstallationWithHappyPath(): void @@ -65,35 +83,22 @@ public function testFinishInstallationWithHappyPath(): void ); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertEquals(Bitrix24AccountStatus::active, $updated->getStatus(),'expected status is active'); + $this->assertEquals(Bitrix24AccountStatus::active, $updated->getStatus(), 'expected status is active'); $this->assertTrue( $updated->isApplicationTokenValid($applicationToken), - sprintf('failed application token «%s» validation for bitrix24 account with id «%s»', + sprintf( + 'failed application token «%s» validation for bitrix24 account with id «%s»', $applicationToken, $bitrix24Account->getId()->toString() - )); + ) + ); $this->assertTrue( in_array(Bitrix24AccountApplicationInstalledEvent::class, $this->eventDispatcher->getOrphanedEvents(), true), - sprintf('emited event «%s» for bitrix24 account wiht id «%s» not found', + sprintf( + 'emited event «%s» for bitrix24 account wiht id «%s» not found', Bitrix24AccountApplicationInstalledEvent::class, $bitrix24Account->getId()->toString() ) ); } - - #[Override] - protected function setUp(): void - { - $entityManager = EntityManagerFactory::get(); - $eventDispatcher = new EventDispatcher(); - $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$this->eventDispatcher); - - $this->handler = new Bitrix24Accounts\UseCase\InstallFinish\Handler( - $this->repository, - $this->flusher, - new NullLogger() - ); - } -} \ No newline at end of file +} diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index e3edb3d..fc8572e 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -22,7 +22,6 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Events\Bitrix24AccountCreatedEvent; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; -use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; use Bitrix24\SDK\Core\Exceptions\UnknownScopeCodeException; @@ -34,8 +33,7 @@ use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; -use Symfony\Component\Uid\Uuid; -use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountInterface; + /** * @internal */ @@ -56,7 +54,7 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $this->eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$this->eventDispatcher); + $this->flusher = new Flusher($entityManager, $this->eventDispatcher); $this->handler = new Bitrix24Accounts\UseCase\InstallStart\Handler( $this->repository, $this->flusher, @@ -153,7 +151,7 @@ public function testInstallStartHappyPath(): void 'Object not equals' ); - $this->assertEquals(Bitrix24AccountStatus::new,$bitrix24Account->getStatus()); + $this->assertEquals(Bitrix24AccountStatus::new, $bitrix24Account->getStatus()); $this->assertContains( Bitrix24AccountCreatedEvent::class, @@ -177,7 +175,6 @@ public function testCreateExistingAccount(): void ->withApplicationScope(new Scope(['crm'])) ->build(); - $this->handler->handle( new Bitrix24Accounts\UseCase\InstallStart\Command( $bitrix24Account->getId(), @@ -191,7 +188,6 @@ public function testCreateExistingAccount(): void ) ); - $this->expectException(Bitrix24AccountNotFoundException::class); $this->expectExceptionMessage( sprintf('bitrix24account with uuid "%s" already exists', $bitrix24Account->getId()) @@ -212,10 +208,5 @@ public function testCreateExistingAccount(): void } #[Test] - public function testUpdateAppVersion(): void - { - - } - - + public function testUpdateAppVersion(): void {} } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 340913e..257efde 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -28,8 +28,8 @@ use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; -use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Stopwatch\Stopwatch; /** * @internal @@ -52,7 +52,7 @@ protected function setUp(): void $eventDispatcher = new EventDispatcher(); $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager,$this->eventDispatcher); + $this->flusher = new Flusher($entityManager, $this->eventDispatcher); $this->handler = new Handler( $this->repository, $this->flusher, diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 25a5118..556af50 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -13,9 +13,9 @@ namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\Uninstall; +use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; use Bitrix24\Lib\Services\Flusher; -use Bitrix24\Lib\Bitrix24Accounts; use Bitrix24\Lib\Tests\EntityManagerFactory; use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; @@ -23,7 +23,6 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\Bitrix24AccountNotFoundException; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; -use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -33,6 +32,9 @@ use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; +/** + * @internal + */ #[CoversClass(Bitrix24Accounts\UseCase\Uninstall\Handler::class)] class HandlerTest extends TestCase { @@ -44,6 +46,22 @@ class HandlerTest extends TestCase private TraceableEventDispatcher $eventDispatcher; + #[\Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager, $this->eventDispatcher); + + $this->handler = new Bitrix24Accounts\UseCase\Uninstall\Handler( + $this->repository, + $this->flusher, + new NullLogger(), + ); + } + /** * @throws InvalidArgumentException * @throws Bitrix24AccountNotFoundException @@ -51,7 +69,6 @@ class HandlerTest extends TestCase #[Test] public function testUninstallWithHappyPath(): void { - $applicationToken = Uuid::v7()->toRfc4122(); $bitrix24Account = (new Bitrix24AccountBuilder()) @@ -67,31 +84,15 @@ public function testUninstallWithHappyPath(): void $this->expectException(Bitrix24AccountNotFoundException::class); $updated = $this->repository->getById($bitrix24Account->getId()); - $this->assertTrue(in_array( - Bitrix24AccountApplicationUninstalledEvent::class, - $this->eventDispatcher->getOrphanedEvents() - ), + $this->assertTrue( + in_array( + Bitrix24AccountApplicationUninstalledEvent::class, + $this->eventDispatcher->getOrphanedEvents() + ), sprintf( 'Event %s was expected to be in the list of orphan events, but it is missing', Bitrix24AccountApplicationUninstalledEvent::class ) ); } - - #[Override] - protected function setUp(): void - { - - $entityManager = EntityManagerFactory::get(); - $eventDispatcher = new EventDispatcher(); - $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); - $this->repository = new Bitrix24AccountRepository($entityManager); - $this->flusher = new Flusher($entityManager, $this->eventDispatcher); - - $this->handler = new Bitrix24Accounts\UseCase\Uninstall\Handler( - $this->repository, - $this->flusher, - new NullLogger(), - ); - } -} \ No newline at end of file +} diff --git a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php index 3eae626..6cd78db 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php @@ -5,14 +5,15 @@ namespace Bitrix24\Lib\Tests\Unit\Bitrix24Accounts\UseCase\ChangeDomainUrl; use Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl\Command; -use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Generator; use Symfony\Component\Uid\Uuid; +/** + * @internal + */ #[CoversClass(Command::class)] class CommandTest extends TestCase { @@ -22,27 +23,23 @@ public function testValidCommand( string $oldDomainUrl, string $newDomainUrl, ?string $expectedException - ) - { - - if ($expectedException !== null) { + ) { + if (null !== $expectedException) { $this->expectException($expectedException); } new Command($oldDomainUrl, $newDomainUrl); - } - public static function dataForCommand(): Generator + public static function dataForCommand(): \Generator { - - $oldDomainUrl = 'https://'.Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; - $newDomainUrl = Uuid::v7()->toRfc4122() . '-test.bitrix24.com'; + $oldDomainUrl = 'https://'.Uuid::v7()->toRfc4122().'-test.bitrix24.com'; + $newDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; yield 'validDomainUrl' => [ $oldDomainUrl, $newDomainUrl, - InvalidArgumentException::class + \InvalidArgumentException::class ]; } -} \ No newline at end of file +} diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index b4bbc1a..df1225d 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -7,18 +7,18 @@ use Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish\Command; use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; -use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Symfony\Component\Uid\Uuid; -use Generator; +/** + * @internal + */ #[CoversClass(Command::class)] class CommandTest extends TestCase { - #[Test] #[DataProvider('dataForCommand')] public function testValidCommand( @@ -28,14 +28,12 @@ public function testValidCommand( int $bitrix24UserId, ?string $expectedException, ?string $expectedExceptionMessage, - ) - { - - if ($expectedException !== null) { + ) { + if (null !== $expectedException) { $this->expectException($expectedException); } - if ($expectedExceptionMessage !== null) { + if (null !== $expectedExceptionMessage) { $this->expectExceptionMessage($expectedExceptionMessage); } @@ -45,10 +43,9 @@ public function testValidCommand( $domainUrl, $bitrix24UserId ); - } - public static function dataForCommand(): Generator + public static function dataForCommand(): \Generator { $applicationToken = Uuid::v7()->toRfc4122(); $bitrix24Account = (new Bitrix24AccountBuilder()) @@ -60,7 +57,7 @@ public static function dataForCommand(): Generator $bitrix24Account->getMemberId(), $bitrix24Account->getDomainUrl(), $bitrix24Account->getBitrix24UserId(), - InvalidArgumentException::class, + \InvalidArgumentException::class, 'Application token cannot be empty.' ]; @@ -69,7 +66,7 @@ public static function dataForCommand(): Generator '', $bitrix24Account->getDomainUrl(), $bitrix24Account->getBitrix24UserId(), - InvalidArgumentException::class, + \InvalidArgumentException::class, 'Member ID cannot be empty.' ]; @@ -78,9 +75,8 @@ public static function dataForCommand(): Generator $bitrix24Account->getMemberId(), '', $bitrix24Account->getBitrix24UserId(), - InvalidArgumentException::class, + \InvalidArgumentException::class, 'Domain URL is not valid.' ]; - } -} \ No newline at end of file +} diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php index dea6fa8..a66d531 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php @@ -9,39 +9,37 @@ use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; -use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Symfony\Component\Uid\Uuid; -use Generator; +/** + * @internal + */ #[CoversClass(Command::class)] class CommandTest extends TestCase { - #[Test] #[DataProvider('dataForCommand')] public function testValidCommand( Uuid $uuid, int $bitrix24UserId, - bool $isBitrix24UserAdmin, - string $memberId, - string $domainUrl, + bool $isBitrix24UserAdmin, + string $memberId, + string $domainUrl, AuthToken $authToken, - int $applicationVersion, - Scope $applicationScope, + int $applicationVersion, + Scope $applicationScope, ?string $expectedException, ?string $expectedExceptionMessage, - ) - { - - if ($expectedException !== null) { + ) { + if (null !== $expectedException) { $this->expectException($expectedException); } - if ($expectedExceptionMessage !== null) { + if (null !== $expectedExceptionMessage) { $this->expectExceptionMessage($expectedExceptionMessage); } @@ -55,10 +53,9 @@ public function testValidCommand( $applicationVersion, $applicationScope ); - } - public static function dataForCommand(): Generator + public static function dataForCommand(): \Generator { $applicationToken = Uuid::v7()->toRfc4122(); $bitrix24Account = (new Bitrix24AccountBuilder()) @@ -74,7 +71,7 @@ public static function dataForCommand(): Generator $bitrix24Account->getAuthToken(), $bitrix24Account->getApplicationVersion(), $bitrix24Account->getApplicationScope(), - InvalidArgumentException::class, + \InvalidArgumentException::class, 'Member ID must be a non-empty string.' ]; @@ -87,7 +84,7 @@ public static function dataForCommand(): Generator $bitrix24Account->getAuthToken(), $bitrix24Account->getApplicationVersion(), $bitrix24Account->getApplicationScope(), - InvalidArgumentException::class, + \InvalidArgumentException::class, 'Domain URL is not valid.' ]; @@ -100,7 +97,7 @@ public static function dataForCommand(): Generator $bitrix24Account->getAuthToken(), $bitrix24Account->getApplicationVersion(), $bitrix24Account->getApplicationScope(), - InvalidArgumentException::class, + \InvalidArgumentException::class, 'Bitrix24 User ID must be a positive integer.' ]; @@ -113,9 +110,8 @@ public static function dataForCommand(): Generator $bitrix24Account->getAuthToken(), 0, $bitrix24Account->getApplicationScope(), - InvalidArgumentException::class, + \InvalidArgumentException::class, 'Application version must be a positive integer.' ]; - } -} \ No newline at end of file +} diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php index aa4bdfa..36fac0f 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -5,12 +5,14 @@ namespace Bitrix24\Lib\Tests\Unit\Bitrix24Accounts\UseCase\Uninstall; use Bitrix24\Lib\Bitrix24Accounts\UseCase\Uninstall\Command; -use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Generator; + +/** + * @internal + */ #[CoversClass(Command::class)] class CommandTest extends TestCase { @@ -20,27 +22,24 @@ public function testValidCommand( string $applicationToken, ?string $expectedException, ?string $expectedExceptionMessage, - ) - { - - if ($expectedException !== null) { + ) { + if (null !== $expectedException) { $this->expectException($expectedException); } - if ($expectedExceptionMessage !== null) { + if (null !== $expectedExceptionMessage) { $this->expectExceptionMessage($expectedExceptionMessage); } - new Command($applicationToken); - + new Command($applicationToken); } - public static function dataForCommand(): Generator + public static function dataForCommand(): \Generator { yield 'validApplicationToken' => [ '', - InvalidArgumentException::class, - 'Empty application token application token.' + \InvalidArgumentException::class, + 'Empty application token application token.', ]; } -} \ No newline at end of file +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 9003ecd..2f9c358 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -14,8 +14,9 @@ use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Dotenv\Dotenv; -require_once dirname(__DIR__) . '/vendor/autoload.php'; -require_once dirname(__DIR__) . '/tests/EntityManagerFactory.php'; +require_once dirname(__DIR__).'/vendor/autoload.php'; + +require_once dirname(__DIR__).'/tests/EntityManagerFactory.php'; if (!class_exists(Dotenv::class)) { throw new LogicException('You need to add "symfony/dotenv" as Composer dependencies.'); @@ -23,11 +24,11 @@ $input = new ArgvInput(); if (null !== $env = $input->getParameterOption(['--env', '-e'], null, true)) { - putenv('APP_ENV=' . $_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = $env); + putenv('APP_ENV='.$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = $env); } if ($input->hasParameterOption('--no-debug', true)) { - putenv('APP_DEBUG=' . $_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0'); + putenv('APP_DEBUG='.$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0'); } -(new Dotenv())->loadEnv(dirname(__DIR__) . '/.env'); \ No newline at end of file +(new Dotenv())->loadEnv(dirname(__DIR__).'/.env'); From 9b5f78c8652cf7b047cd9535d3ae3eb7bdb91f41 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Fri, 17 Jan 2025 01:07:07 +0300 Subject: [PATCH 110/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=BB=D1=8F=20=D0=B4=D0=BE=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B0=20-=20=D0=9F=D1=80=D0=B5=D0=BE=D0=B1=D1=80=D0=B0=D0=B7?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D0=B4=D0=BE=D0=BC=D0=B5=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Doctrine/Bitrix24AccountRepository.php | 5 +- .../ReadModel/Bitrix24AccountFetcher.php | 37 ----------- .../UseCase/ChangeDomainUrl/Command.php | 26 +++++--- .../UseCase/ChangeDomainUrl/Handler.php | 12 ++-- .../UseCase/InstallFinish/Command.php | 29 ++++++++- .../UseCase/ChangeDomainUrl/CommandTest.php | 62 +++++++++++++++---- .../UseCase/InstallFinish/CommandTest.php | 2 +- 7 files changed, 104 insertions(+), 69 deletions(-) delete mode 100644 src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 804b299..9be8142 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -204,9 +204,8 @@ public function findByDomain( throw new InvalidArgumentException('domainUrl cannot be an empty string'); } - $criteria = [ - 'domainUrl' => $domainUrl, - ]; + $criteria = ['domainUrl' => $domainUrl]; + if ($bitrix24AccountStatus instanceof Bitrix24AccountStatus) { $criteria['status'] = $bitrix24AccountStatus->name; } diff --git a/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php b/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php deleted file mode 100644 index 73b4900..0000000 --- a/src/Bitrix24Accounts/ReadModel/Bitrix24AccountFetcher.php +++ /dev/null @@ -1,37 +0,0 @@ -em->createQueryBuilder() - ->select( - 'b24account.id as id', - 'b24account.status as status', - 'b24account.memberId as member_id', - 'b24account.domainUrl as domain_url', - 'b24account.applicationVersion as application_version', - 'b24account.createdAt as created_at_utc', - 'b24account.updatedAt as updated_at_utc', - ) - ->from('Bitrix24\Lib\Bitrix24Accounts\Entity\Bitrix24Account', 'b24account') - ->orderBy('b24account.createdAt', 'DESC'); - - return $this->paginator->paginate($qb, $page, $size); - } -} diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index e488548..a1b2419 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -8,21 +8,33 @@ { public function __construct( /** - * @var non-empty-string $oldDomainUrlHost + * @var non-empty-string $oldDomain */ - public string $oldDomainUrlHost, + public string $oldDomain, /** - * @var non-empty-string $newDomainUrlHost + * @var non-empty-string $newDomain */ - public string $newDomainUrlHost + public string $newDomain ) { - $this->validateDomain($oldDomainUrlHost, 'oldDomainUrlHost'); - $this->validateDomain($newDomainUrlHost, 'newDomainUrlHost'); + $this->validateDomain($oldDomain, 'oldDomainUrlHost'); + $this->validateDomain($newDomain, 'newDomainUrlHost'); } private function validateDomain(string $domain, string $parameterName): void { - if (empty($domain) || !filter_var($domain, FILTER_VALIDATE_URL)) { + // Регулярное выражение для проверки допустимых символов (латиница и кириллица) + $patternValidChars = "/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?logger->info('Bitrix24Accounts.ChangeDomainUrl.start', [ - 'b24_domain_url_old' => $command->oldDomainUrlHost, - 'b24_domain_url_new' => $command->newDomainUrlHost, + 'b24_domain_url_old' => $command->oldDomain, + 'b24_domain_url_new' => $command->newDomain, ]); /** @var AggregateRootEventsEmitterInterface[]|Bitrix24AccountInterface[] $accounts */ - $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomainUrlHost); + $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomain); foreach ($accounts as $account) { - $account->changeDomainUrl($command->newDomainUrlHost); + $account->changeDomainUrl($command->newDomain); $this->bitrix24AccountRepository->save($account); } @@ -38,8 +38,8 @@ public function handle(Command $command): void $this->logger->info( 'Bitrix24Accounts.ChangeDomainUrl.Finish', [ - 'b24_domain_url_old' => $command->oldDomainUrlHost, - 'b24_domain_url_new' => $command->newDomainUrlHost, + 'b24_domain_url_old' => $command->oldDomain, + 'b24_domain_url_new' => $command->newDomain, ] ); } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index 946532e..6b373a8 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -10,8 +10,9 @@ public function __construct( public string $applicationToken, public string $memberId, public string $domainUrl, - public ?int $bitrix24UserId, - ) { + public int $bitrix24UserId, + ) + { $this->validate(); } @@ -23,7 +24,29 @@ private function validate(): void if (empty($this->memberId)) { throw new \InvalidArgumentException('Member ID cannot be empty.'); } - if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { + + $this->validateDomain($this->domainUrl); + + if ($this->bitrix24UserId <= 0) { + throw new \InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); + } + } + + private function validateDomain(string $domain): void + { + // Регулярное выражение для проверки допустимых символов (латиница и кириллица) + $patternValidChars = "/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?expectException($expectedException); + + $exceptionCount = 0; + + foreach ($arr as $arrDomains) { + foreach ($arrDomains as $domainPair) { + try { + new Command($domainPair['oldDomain'], $domainPair['newDomain']); + } catch (\InvalidArgumentException $e) { + // Увеличиваем счетчик при каждом выбросе исключения + $exceptionCount++; + } + } + } + + // Проверяем, сколько исключений было выброшено + if ($expectedException !== null) { + $this->assertEquals(6, $exceptionCount, "Expected 6 invalid exception and received {$exceptionCount}"); + } else { + // Если ожидается отсутствие исключений, проверяем что их не было + $this->assertEquals(0, $exceptionCount, "No exceptions were expected but {$exceptionCount} were thrown."); } - new Command($oldDomainUrl, $newDomainUrl); } public static function dataForCommand(): \Generator { - $oldDomainUrl = 'https://'.Uuid::v7()->toRfc4122().'-test.bitrix24.com'; - $newDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; - yield 'validDomainUrl' => [ - $oldDomainUrl, - $newDomainUrl, - \InvalidArgumentException::class + // Примеры недопустимых доменов + $arrInvalidDomains = [ + ['oldDomain' => 'invalid_domain.com', 'newDomain' => 'valid.com'], // Неправильный формат (подчеркивание) + ['oldDomain' => '-invalid.com', 'newDomain' => 'valid.com'], // Домен не может начинаться с дефиса + ['oldDomain' => 'invalid-.com', 'newDomain' => 'valid.com'], // Домен не может заканчиваться на дефис + ['oldDomain' => '123.456.789.0', 'newDomain' => 'valid.com'], // Неправильный формат (IP-адрес) + ['oldDomain' => 'example..com', 'newDomain' => 'valid.com'], // Два подряд идущих точки + ['oldDomain' => 'example.c', 'newDomain' => 'valid.com'] // Слишком короткая доменная зона ]; + + // Примеры допустимых доменов + $arrValidDomains = [ + ['oldDomain' => 'example.com', 'newDomain' => 'example.org'], + ['oldDomain' => 'пример.рф', 'newDomain' => 'пример.рус'], + ['oldDomain' => 'test-site.org', 'newDomain' => 'test-site.ru'], + ['oldDomain' => 'valid-domain.co.uk', 'newDomain' => 'valid-domain.net'], + ['oldDomain' => 'subdomain.example.com', 'newDomain' => 'subdomain2.example.com'], + ['oldDomain' => 'тест.рус', 'newDomain' => 'тест2.рус'], // Пример с кириллицей + ]; + + yield 'invalidDomain' => [ + [$arrInvalidDomains], // Оборачиваем в массив для передачи в testValidCommand + \InvalidArgumentException::class + ]; + + yield 'validDomain' => [ + [$arrValidDomains], // Оборачиваем в массив для передачи в testValidCommand + null // Здесь исключение не ожидается + ]; } } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index df1225d..0c3c6df 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -70,7 +70,7 @@ public static function dataForCommand(): \Generator 'Member ID cannot be empty.' ]; - yield 'validDomainUrl' => [ + yield 'validDomain' => [ $applicationToken, $bitrix24Account->getMemberId(), '', From 0af10a04b0392a70d8d887828bc9c10d449186ce Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 18 Jan 2025 10:30:34 +0300 Subject: [PATCH 111/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=BB=D1=8F=20=D1=84=D1=83=D0=BA=D0=BD=D1=86?= =?UTF-8?q?=D0=B8=D0=BE=D0=BD=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D1=82?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=BE=D0=B2=20-=20=D0=94=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20?= =?UTF-8?q?=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/InstallStart/Command.php | 23 ++++++- .../Builders/Bitrix24AccountBuilder.php | 2 +- .../UseCase/InstallStart/HandlerTest.php | 2 + .../UseCase/ChangeDomainUrl/CommandTest.php | 68 +++++++------------ 4 files changed, 46 insertions(+), 49 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index 89ac909..9e62c5c 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -37,12 +37,29 @@ private function validate(): void throw new \InvalidArgumentException('Member ID must be a non-empty string.'); } - if (!filter_var($this->domainUrl, FILTER_VALIDATE_URL)) { - throw new \InvalidArgumentException('Domain URL is not valid.'); - } + $this->validateDomain($this->domainUrl); if ($this->applicationVersion <= 0) { throw new \InvalidArgumentException('Application version must be a positive integer.'); } } + + private function validateDomain(string $domain): void + { + // Регулярное выражение для проверки допустимых символов (латиница и кириллица) + $patternValidChars = "/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?bitrix24UserId = random_int(1, 1_000_000); $this->isBitrix24UserAdmin = true; $this->memberId = Uuid::v4()->toRfc4122(); - $this->domainUrl = 'https://'.Uuid::v7()->toRfc4122().'-test.bitrix24.com'; + $this->domainUrl = Uuid::v4()->toRfc4122().'-example.com'; $this->authToken = new AuthToken('old_1', 'old_2', 3600); $this->createdAt = CarbonImmutable::now(); $this->updatedAt = CarbonImmutable::now(); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index fc8572e..a0520a9 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -207,6 +207,8 @@ public function testCreateExistingAccount(): void ); } + + #[Test] public function testUpdateAppVersion(): void {} } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php index ebf2d52..7a95f9d 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php @@ -20,64 +20,42 @@ class CommandTest extends TestCase #[Test] #[DataProvider('dataForCommand')] public function testValidCommand( - array $arr, + string $oldDomain, + string $newDomain, ?string $expectedException - ) { - - $exceptionCount = 0; + ) + { - foreach ($arr as $arrDomains) { - foreach ($arrDomains as $domainPair) { - try { - new Command($domainPair['oldDomain'], $domainPair['newDomain']); - } catch (\InvalidArgumentException $e) { - // Увеличиваем счетчик при каждом выбросе исключения - $exceptionCount++; - } - } + if ($expectedException !== null) { + $this->expectException(\InvalidArgumentException::class); } - // Проверяем, сколько исключений было выброшено - if ($expectedException !== null) { - $this->assertEquals(6, $exceptionCount, "Expected 6 invalid exception and received {$exceptionCount}"); - } else { - // Если ожидается отсутствие исключений, проверяем что их не было - $this->assertEquals(0, $exceptionCount, "No exceptions were expected but {$exceptionCount} were thrown."); + $command = new Command($oldDomain, $newDomain); + + if ($expectedException == null) { + $this->assertInstanceOf(Command::class, $command); } } public static function dataForCommand(): \Generator { + $invalidOldDomain = 'invalid_domain.com'; + $invalidNewDomain = 'valid.com'; - // Примеры недопустимых доменов - $arrInvalidDomains = [ - ['oldDomain' => 'invalid_domain.com', 'newDomain' => 'valid.com'], // Неправильный формат (подчеркивание) - ['oldDomain' => '-invalid.com', 'newDomain' => 'valid.com'], // Домен не может начинаться с дефиса - ['oldDomain' => 'invalid-.com', 'newDomain' => 'valid.com'], // Домен не может заканчиваться на дефис - ['oldDomain' => '123.456.789.0', 'newDomain' => 'valid.com'], // Неправильный формат (IP-адрес) - ['oldDomain' => 'example..com', 'newDomain' => 'valid.com'], // Два подряд идущих точки - ['oldDomain' => 'example.c', 'newDomain' => 'valid.com'] // Слишком короткая доменная зона - ]; + $validOldDomain = 'example.com'; + $validNewDomain = 'example.org'; - // Примеры допустимых доменов - $arrValidDomains = [ - ['oldDomain' => 'example.com', 'newDomain' => 'example.org'], - ['oldDomain' => 'пример.рф', 'newDomain' => 'пример.рус'], - ['oldDomain' => 'test-site.org', 'newDomain' => 'test-site.ru'], - ['oldDomain' => 'valid-domain.co.uk', 'newDomain' => 'valid-domain.net'], - ['oldDomain' => 'subdomain.example.com', 'newDomain' => 'subdomain2.example.com'], - ['oldDomain' => 'тест.рус', 'newDomain' => 'тест2.рус'], // Пример с кириллицей + yield 'invalidDomain' => [ + $invalidOldDomain, + $invalidNewDomain, + \InvalidArgumentException::class ]; - yield 'invalidDomain' => [ - [$arrInvalidDomains], // Оборачиваем в массив для передачи в testValidCommand - \InvalidArgumentException::class - ]; - - yield 'validDomain' => [ - [$arrValidDomains], // Оборачиваем в массив для передачи в testValidCommand - null // Здесь исключение не ожидается - ]; + yield 'validDomain' => [ + $validOldDomain, + $validNewDomain, + null // Здесь исключение не ожидается + ]; } } From f109090d54201537bae7bc8cebded1f28b119012 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 18 Jan 2025 11:12:56 +0300 Subject: [PATCH 112/130] =?UTF-8?q?-=20=D0=9F=D1=8B=D1=82=D0=B0=D1=8E?= =?UTF-8?q?=D1=81=D1=8C=20=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D1=82=D1=8C=20?= =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=BE?= =?UTF-8?q?=D0=BD=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=20=D0=B2=20github=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 4 +++- .../UseCase/Uninstall/CommandTest.php | 16 +++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 9db731a..54aa72b 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -68,7 +68,9 @@ jobs: php bin/doctrine orm:schema-tool:create --dump-sql php bin/doctrine orm:schema-tool:update --dump-sql php bin/doctrine orm:info - php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox + php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox + # Запуск тестов с очисткой состояния между тестами + php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox --process-isolation - name: "is functional tests succeeded" if: ${{ success() }} diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php index 36fac0f..6415a13 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -9,6 +9,7 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use Symfony\Component\Uid\Uuid; /** * @internal @@ -31,12 +32,25 @@ public function testValidCommand( $this->expectExceptionMessage($expectedExceptionMessage); } - new Command($applicationToken); + $command = new Command($applicationToken); + + if ($expectedException == null) { + $this->assertInstanceOf(Command::class, $command); + } } public static function dataForCommand(): \Generator { + + $applicationToken = Uuid::v7()->toRfc4122(); + yield 'validApplicationToken' => [ + $applicationToken, + null, + null, + ]; + + yield 'emptyApplicationToken' => [ '', \InvalidArgumentException::class, 'Empty application token application token.', From 3a9b261d984016f30095b5e801d49038f7f5038d Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 18 Jan 2025 11:13:22 +0300 Subject: [PATCH 113/130] =?UTF-8?q?-=20=D0=A2=D0=B5=D1=81=D1=82=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D1=83=20?= =?UTF-8?q?=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=B8=20=D0=B4=D0=BE=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Bitrix24Accounts/DomainCheckerTest.php | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 tests/Unit/Bitrix24Accounts/DomainCheckerTest.php diff --git a/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php b/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php new file mode 100644 index 0000000..a606b56 --- /dev/null +++ b/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php @@ -0,0 +1,83 @@ +assertEquals(6, $exceptionCount, "Expected 6 invalid exception and received {$exceptionCount}"); + } else { + // Если ожидается отсутствие исключений, проверяем что их не было + $this->assertEquals(0, $exceptionCount, "No exceptions were expected but {$exceptionCount} were thrown."); + } + + } + + public static function dataForCommand(): \Generator + { + + // Примеры недопустимых доменов + $arrInvalidDomains = [ + ['oldDomain' => 'invalid_domain.com', 'newDomain' => 'valid.com'], // Неправильный формат (подчеркивание) + ['oldDomain' => '-invalid.com', 'newDomain' => 'valid.com'], // Домен не может начинаться с дефиса + ['oldDomain' => 'invalid-.com', 'newDomain' => 'valid.com'], // Домен не может заканчиваться на дефис + ['oldDomain' => '123.456.789.0', 'newDomain' => 'valid.com'], // Неправильный формат (IP-адрес) + ['oldDomain' => 'example..com', 'newDomain' => 'valid.com'], // Два подряд идущих точки + ['oldDomain' => 'example.c', 'newDomain' => 'valid.com'] // Слишком короткая доменная зона + ]; + + // Примеры допустимых доменов + $arrValidDomains = [ + ['oldDomain' => 'example.com', 'newDomain' => 'example.org'], + ['oldDomain' => 'пример.рф', 'newDomain' => 'пример.рус'], + ['oldDomain' => 'test-site.org', 'newDomain' => 'test-site.ru'], + ['oldDomain' => 'valid-domain.co.uk', 'newDomain' => 'valid-domain.net'], + ['oldDomain' => 'subdomain.example.com', 'newDomain' => 'subdomain2.example.com'], + ['oldDomain' => 'тест.рус', 'newDomain' => 'тест2.рус'], // Пример с кириллицей + ]; + + yield 'invalidDomain' => [ + [$arrInvalidDomains], // Оборачиваем в массив для передачи в testValidCommand + \InvalidArgumentException::class + ]; + + yield 'validDomain' => [ + [$arrValidDomains], // Оборачиваем в массив для передачи в testValidCommand + null // Здесь исключение не ожидается + ]; + } +} From 8d149d4a6d5c15f6924224aa626e41f5ae3ddfa4 Mon Sep 17 00:00:00 2001 From: KIRILL <61900565+KarlsonComplete@users.noreply.github.com> Date: Sat, 18 Jan 2025 11:23:16 +0300 Subject: [PATCH 114/130] Update tests-functional.yml --- .github/workflows/tests-functional.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 54aa72b..5aefdf0 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -68,7 +68,6 @@ jobs: php bin/doctrine orm:schema-tool:create --dump-sql php bin/doctrine orm:schema-tool:update --dump-sql php bin/doctrine orm:info - php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox # Запуск тестов с очисткой состояния между тестами php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox --process-isolation @@ -80,4 +79,4 @@ jobs: - name: "is functional tests failed" if: ${{ failure() }} run: | - echo '::error:: ❗️ functional tests failed (╯°益°)╯彡┻━┻' \ No newline at end of file + echo '::error:: ❗️ functional tests failed (╯°益°)╯彡┻━┻' From ecd22a675ea638d94f2158e51956248e4aa6ea01 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 18 Jan 2025 14:08:52 +0300 Subject: [PATCH 115/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BC=20github=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 5aefdf0..2f82c16 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -6,7 +6,7 @@ on: env: COMPOSER_FLAGS: "--ansi --no-interaction --no-progress" - DATABASE_HOST: localhost + DATABASE_HOST: bitrix24-php-lib-test-database DATABASE_USER: b24phpLibTest DATABASE_PASSWORD: b24phpLibTest DATABASE_NAME: b24phpLibTest @@ -38,7 +38,7 @@ jobs: POSTGRES_USER: b24phpLibTest POSTGRES_PASSWORD: b24phpLibTest POSTGRES_DB: b24phpLibTest - DATABASE_HOST: localhost + DATABASE_HOST: bitrix24-php-lib-test-database steps: - name: "Checkout code" From 9e04451faa4df1998f27eeb9dbceadb136489bbe Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 18 Jan 2025 14:18:02 +0300 Subject: [PATCH 116/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BC=20github=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 2f82c16..16ab696 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -6,7 +6,7 @@ on: env: COMPOSER_FLAGS: "--ansi --no-interaction --no-progress" - DATABASE_HOST: bitrix24-php-lib-test-database + DATABASE_HOST: localhost DATABASE_USER: b24phpLibTest DATABASE_PASSWORD: b24phpLibTest DATABASE_NAME: b24phpLibTest @@ -30,7 +30,7 @@ jobs: ports: - 5432:5432 options: >- - --health-cmd="pg_isready -U postgres" + --health-cmd="pg_isready -U b24phpLibTest" --health-interval=10s --health-timeout=5s --health-retries=5 @@ -38,7 +38,6 @@ jobs: POSTGRES_USER: b24phpLibTest POSTGRES_PASSWORD: b24phpLibTest POSTGRES_DB: b24phpLibTest - DATABASE_HOST: bitrix24-php-lib-test-database steps: - name: "Checkout code" From af668eaf402c435e45dd69253262c5f0186b2c08 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 18 Jan 2025 14:30:17 +0300 Subject: [PATCH 117/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BC=20github=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 16ab696..33c0f19 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -65,7 +65,6 @@ jobs: run: | php bin/doctrine orm:schema-tool:drop --force php bin/doctrine orm:schema-tool:create --dump-sql - php bin/doctrine orm:schema-tool:update --dump-sql php bin/doctrine orm:info # Запуск тестов с очисткой состояния между тестами php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox --process-isolation From c2bfeb6d5b958a954bf03fd1fd0d554d861d62b0 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 19 Jan 2025 00:06:11 +0300 Subject: [PATCH 118/130] =?UTF-8?q?-=20=D0=AE=D0=B7=D0=B0=D0=BD=D1=83?= =?UTF-8?q?=D0=BB=D0=B8=20=D1=80=D0=B5=D0=BA=D1=82=D0=BE=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Bitrix24Accounts/Entity/Bitrix24Account.php | 4 ++-- .../Doctrine/Bitrix24AccountRepository.php | 7 +------ .../UseCase/ChangeDomainUrl/Command.php | 6 +++--- .../UseCase/InstallFinish/Command.php | 11 ++++++----- .../UseCase/InstallStart/Command.php | 8 ++++---- src/Bitrix24Accounts/UseCase/Uninstall/Command.php | 2 +- src/Bitrix24Accounts/UseCase/Uninstall/Handler.php | 1 + src/Services/Flusher.php | 13 ++++--------- .../Builders/Bitrix24AccountBuilder.php | 8 ++++---- .../UseCase/InstallFinish/HandlerTest.php | 1 + .../UseCase/RenewAuthToken/HandlerTest.php | 1 + .../UseCase/Uninstall/HandlerTest.php | 3 ++- tests/Unit/Bitrix24Accounts/DomainCheckerTest.php | 12 ++++++------ .../UseCase/ChangeDomainUrl/CommandTest.php | 2 +- .../UseCase/InstallFinish/CommandTest.php | 2 +- .../UseCase/InstallStart/CommandTest.php | 3 +-- .../UseCase/Uninstall/CommandTest.php | 2 +- 17 files changed, 40 insertions(+), 46 deletions(-) diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index 597c68d..a269988 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -309,14 +309,14 @@ public function getComment(): ?string return $this->comment; } - private function guardEmptyToken($applicationToken) + private function guardEmptyToken(string $applicationToken): void { if ('' === $applicationToken) { throw new InvalidArgumentException('application token cannot be empty'); } } - private function guardTokenMismatch($applicationToken): void + private function guardTokenMismatch(string $applicationToken): void { if ($this->applicationToken !== $applicationToken) { throw new InvalidArgumentException( diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index 9be8142..f1b48be 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -59,12 +59,7 @@ public function existsById(Uuid $uuid): bool ->setParameter('status', Bitrix24AccountStatus::deleted) ->getQuery() ->getOneOrNullResult(); - - if ($account) { - return true; - } - - return false; + return (bool) $account; } #[\Override] diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index a1b2419..dc1c720 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -31,9 +31,9 @@ private function validateDomain(string $domain, string $parameterName): void // Проверка длины каждой метки (1-63 символа, включая кириллицу) $patternLengthEachLabel = "/^[A-Za-zА-Яа-яЁё0-9-]{1,63}(\.[A-Za-zА-Яа-яЁё0-9-]{1,63})*$/u"; if ( - !preg_match($patternValidChars, $domain) || - !preg_match($patternLengthCheck, $domain) || - !preg_match($patternLengthEachLabel, $domain)) { + in_array(preg_match($patternValidChars, $domain), [0, false], true) || + in_array(preg_match($patternLengthCheck, $domain), [0, false], true) || + in_array(preg_match($patternLengthEachLabel, $domain), [0, false], true)) { throw new \InvalidArgumentException(sprintf('Invalid value for %s: %s', $parameterName, $domain)); } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index 6b373a8..d3ae444 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -18,10 +18,11 @@ public function __construct( private function validate(): void { - if (empty($this->applicationToken)) { + if ($this->applicationToken === '' || $this->applicationToken === '0') { throw new \InvalidArgumentException('Application token cannot be empty.'); } - if (empty($this->memberId)) { + + if ($this->memberId === '' || $this->memberId === '0') { throw new \InvalidArgumentException('Member ID cannot be empty.'); } @@ -43,9 +44,9 @@ private function validateDomain(string $domain): void // Проверка длины каждой метки (1-63 символа, включая кириллицу) $patternLengthEachLabel = "/^[A-Za-zА-Яа-яЁё0-9-]{1,63}(\.[A-Za-zА-Яа-яЁё0-9-]{1,63})*$/u"; if ( - !preg_match($patternValidChars, $domain) || - !preg_match($patternLengthCheck, $domain) || - !preg_match($patternLengthEachLabel, $domain)) { + in_array(preg_match($patternValidChars, $domain), [0, false], true) || + in_array(preg_match($patternLengthCheck, $domain), [0, false], true) || + in_array(preg_match($patternLengthEachLabel, $domain), [0, false], true)) { throw new \InvalidArgumentException('Domain URL is not valid.'); } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index 9e62c5c..8c86e6d 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -33,7 +33,7 @@ private function validate(): void throw new \InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); } - if (!is_string($this->memberId) || empty($this->memberId)) { + if (!is_string($this->memberId) || ($this->memberId === '' || $this->memberId === '0')) { throw new \InvalidArgumentException('Member ID must be a non-empty string.'); } @@ -55,9 +55,9 @@ private function validateDomain(string $domain): void // Проверка длины каждой метки (1-63 символа, включая кириллицу) $patternLengthEachLabel = "/^[A-Za-zА-Яа-яЁё0-9-]{1,63}(\.[A-Za-zА-Яа-яЁё0-9-]{1,63})*$/u"; if ( - !preg_match($patternValidChars, $domain) || - !preg_match($patternLengthCheck, $domain) || - !preg_match($patternLengthEachLabel, $domain)) { + in_array(preg_match($patternValidChars, $domain), [0, false], true) || + in_array(preg_match($patternLengthCheck, $domain), [0, false], true) || + in_array(preg_match($patternLengthEachLabel, $domain), [0, false], true)) { throw new \InvalidArgumentException('Domain URL is not valid.'); } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php index 71138f5..c349bc1 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php @@ -17,7 +17,7 @@ public function __construct( private function validate(): void { - if (empty($this->applicationToken)) { + if ($this->applicationToken === '' || $this->applicationToken === '0') { throw new \InvalidArgumentException('Empty application token application token.'); } } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php index f72a088..516126b 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Handler.php @@ -35,6 +35,7 @@ public function handle(Command $command): void $account->applicationUninstalled($command->applicationToken); $this->bitrix24AccountRepository->save($account); } + $this->flusher->flush(...$accounts); $this->logger->info( diff --git a/src/Services/Flusher.php b/src/Services/Flusher.php index bd33cdd..c4c1a00 100644 --- a/src/Services/Flusher.php +++ b/src/Services/Flusher.php @@ -10,20 +10,15 @@ class Flusher { - private $em; - private $eventDispatcher; - - public function __construct(EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher) + public function __construct(private readonly EntityManagerInterface $em, private readonly EventDispatcherInterface $eventDispatcher) { - $this->em = $em; - $this->eventDispatcher = $eventDispatcher; } - public function flush(AggregateRootEventsEmitterInterface ...$roots): void + public function flush(AggregateRootEventsEmitterInterface ...$aggregateRootEventsEmitter): void { $this->em->flush(); - foreach ($roots as $root) { - $events = $root->emitEvents(); + foreach ($aggregateRootEventsEmitter as $aggregateRootEventEmitter) { + $events = $aggregateRootEventEmitter->emitEvents(); foreach ($events as $event) { $this->eventDispatcher->dispatch($event); } diff --git a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php index 1d01db2..a63331a 100644 --- a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php +++ b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php @@ -100,7 +100,7 @@ public function withStatus(Bitrix24AccountStatus $bitrix24AccountStatus): self public function build(): AggregateRootEventsEmitterInterface&Bitrix24AccountInterface { - $account = new Bitrix24Account( + $bitrix24Account = new Bitrix24Account( $this->id, $this->bitrix24UserId, $this->isBitrix24UserAdmin, @@ -114,10 +114,10 @@ public function build(): AggregateRootEventsEmitterInterface&Bitrix24AccountInte $this->applicationScope ); - if (isset($this->applicationToken) && Bitrix24AccountStatus::new == $this->status) { - $account->applicationInstalled($this->applicationToken); + if ($this->applicationToken !== null && Bitrix24AccountStatus::new == $this->status) { + $bitrix24Account->applicationInstalled($this->applicationToken); } - return $account; + return $bitrix24Account; } } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 0b1d67b..76d43c2 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -51,6 +51,7 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager, $this->eventDispatcher); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php index 257efde..31a5855 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/RenewAuthToken/HandlerTest.php @@ -51,6 +51,7 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager, $this->eventDispatcher); $this->handler = new Handler( diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 556af50..536a1a1 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -52,6 +52,7 @@ protected function setUp(): void $entityManager = EntityManagerFactory::get(); $eventDispatcher = new EventDispatcher(); $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + $this->repository = new Bitrix24AccountRepository($entityManager); $this->flusher = new Flusher($entityManager, $this->eventDispatcher); @@ -82,7 +83,7 @@ public function testUninstallWithHappyPath(): void $this->handler->handle(new Bitrix24Accounts\UseCase\Uninstall\Command($applicationToken)); $this->expectException(Bitrix24AccountNotFoundException::class); - $updated = $this->repository->getById($bitrix24Account->getId()); + $this->repository->getById($bitrix24Account->getId()); $this->assertTrue( in_array( diff --git a/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php b/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php index a606b56..123e0f4 100644 --- a/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php +++ b/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php @@ -22,15 +22,15 @@ class DomainCheckerTest extends TestCase public function testValidateDomain( array $arr, ?string $expectedException - ) { + ): void { $exceptionCount = 0; foreach ($arr as $arrDomains) { - foreach ($arrDomains as $domainPair) { + foreach ($arrDomains as $arrDomain) { try { - new Command($domainPair['oldDomain'], $domainPair['newDomain']); - } catch (\InvalidArgumentException $e) { + new Command($arrDomain['oldDomain'], $arrDomain['newDomain']); + } catch (\InvalidArgumentException) { // Увеличиваем счетчик при каждом выбросе исключения $exceptionCount++; } @@ -39,10 +39,10 @@ public function testValidateDomain( // Проверяем, сколько исключений было выброшено if ($expectedException !== null) { - $this->assertEquals(6, $exceptionCount, "Expected 6 invalid exception and received {$exceptionCount}"); + $this->assertEquals(6, $exceptionCount, 'Expected 6 invalid exception and received ' . $exceptionCount); } else { // Если ожидается отсутствие исключений, проверяем что их не было - $this->assertEquals(0, $exceptionCount, "No exceptions were expected but {$exceptionCount} were thrown."); + $this->assertEquals(0, $exceptionCount, sprintf('No exceptions were expected but %d were thrown.', $exceptionCount)); } } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php index 7a95f9d..bfd3e1d 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php @@ -23,7 +23,7 @@ public function testValidCommand( string $oldDomain, string $newDomain, ?string $expectedException - ) + ): void { if ($expectedException !== null) { diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index 0c3c6df..c11824b 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -28,7 +28,7 @@ public function testValidCommand( int $bitrix24UserId, ?string $expectedException, ?string $expectedExceptionMessage, - ) { + ): void { if (null !== $expectedException) { $this->expectException($expectedException); } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php index a66d531..c9f1a21 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php @@ -34,7 +34,7 @@ public function testValidCommand( Scope $applicationScope, ?string $expectedException, ?string $expectedExceptionMessage, - ) { + ): void { if (null !== $expectedException) { $this->expectException($expectedException); } @@ -57,7 +57,6 @@ public function testValidCommand( public static function dataForCommand(): \Generator { - $applicationToken = Uuid::v7()->toRfc4122(); $bitrix24Account = (new Bitrix24AccountBuilder()) ->withStatus(Bitrix24AccountStatus::new) ->build(); diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php index 6415a13..db55093 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -23,7 +23,7 @@ public function testValidCommand( string $applicationToken, ?string $expectedException, ?string $expectedExceptionMessage, - ) { + ): void { if (null !== $expectedException) { $this->expectException($expectedException); } From b27b0cb425d75a1e078a3430db93dff1a59e4a5e Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 19 Jan 2025 11:20:55 +0300 Subject: [PATCH 119/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=BB=D1=8F=20github=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 33c0f19..dd9e5af 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -26,7 +26,7 @@ jobs: operating-system: [ ubuntu-latest] services: bitrix24-php-lib-test-database: - image: postgres:16 + image: postgres:16-alpine ports: - 5432:5432 options: >- From 1e993a4606fc3fdd8a3da5365ca33417106eeaf3 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Fri, 31 Jan 2025 00:50:55 +0300 Subject: [PATCH 120/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=BB=D1=8F=20github=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 26 ++++++++++++++++---------- docker-compose.yaml | 2 +- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index dd9e5af..6926c6e 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -23,7 +23,7 @@ jobs: php-version: - "8.3" dependencies: [ highest ] - operating-system: [ ubuntu-latest] + operating-system: [ ubuntu-latest ] services: bitrix24-php-lib-test-database: image: postgres:16-alpine @@ -54,20 +54,26 @@ jobs: run: | composer update ${{ env.COMPOSER_FLAGS }} + # - name: "Install PostgreSQL client" + # run: | + # sudo apt-get update + # sudo apt-get install -y postgresql-client + - name: "Wait for PostgreSQL to be ready" run: | - until pg_isready -h localhost -p 5432 -U user; do - echo "Waiting for PostgreSQL to start..." - sleep 2 - done + until pg_isready -h localhost -p 5438 -U b24phpLibTest; do + echo "Waiting for PostgreSQL to start..." + sleep 2 + done - name: "Run functional tests" run: | - php bin/doctrine orm:schema-tool:drop --force - php bin/doctrine orm:schema-tool:create --dump-sql - php bin/doctrine orm:info - # Запуск тестов с очисткой состояния между тестами - php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox --process-isolation + php bin/doctrine orm:schema-tool:drop --force + php bin/doctrine orm:schema-tool:create --dump-sql + php bin/doctrine orm:schema-tool:update --force + php bin/doctrine orm:info + # Запуск тестов с очисткой состояния между тестами + php vendor/bin/phpunit --testsuite=functional_tests --display-warnings --testdox --process-isolation - name: "is functional tests succeeded" if: ${{ success() }} diff --git a/docker-compose.yaml b/docker-compose.yaml index fb520fb..fbdff87 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -22,7 +22,7 @@ services: PGDATA: "/var/lib/postgresql/data/pgdata" container_name: bitrix24-php-lib-test-database ports: - - '5432:5432' + - '5438:5432' volumes: - ./docker/init_database/:/docker-entrypoint-initdb.d - ./docker/db:/var/lib/postgresql/data From 0c1e899e25d8ca803f01fd4f98ae95ffa7ab3288 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Fri, 31 Jan 2025 00:58:55 +0300 Subject: [PATCH 121/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=BB=D1=8F=20github=20actions=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 6926c6e..4ec24de 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -54,10 +54,10 @@ jobs: run: | composer update ${{ env.COMPOSER_FLAGS }} - # - name: "Install PostgreSQL client" - # run: | - # sudo apt-get update - # sudo apt-get install -y postgresql-client + - name: "Install PostgreSQL client" + run: | + sudo apt-get update + sudo apt-get install -y postgresql-client - name: "Wait for PostgreSQL to be ready" run: | From 86ff56772dc2dc7efbc586f31f4204deb2ab49ee Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Fri, 31 Jan 2025 01:12:38 +0300 Subject: [PATCH 122/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=BB=D1=8F=20github=20actions=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/tests-functional.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests-functional.yml b/.github/workflows/tests-functional.yml index 4ec24de..b17a851 100644 --- a/.github/workflows/tests-functional.yml +++ b/.github/workflows/tests-functional.yml @@ -61,7 +61,7 @@ jobs: - name: "Wait for PostgreSQL to be ready" run: | - until pg_isready -h localhost -p 5438 -U b24phpLibTest; do + until pg_isready -h localhost -p 5432 -U b24phpLibTest; do echo "Waiting for PostgreSQL to start..." sleep 2 done From 2765344d228a2a190e10dc1e5de4951385ddb462 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 1 Feb 2025 14:03:33 +0300 Subject: [PATCH 123/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=BB=D1=8F=20=D1=82=D0=B5=D1=81=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=20-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D1=81s=20fixer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Doctrine/Bitrix24AccountRepository.php | 13 ++++++----- .../UseCase/ChangeDomainUrl/Command.php | 13 +++++------ .../UseCase/InstallFinish/Command.php | 22 +++++++++---------- .../UseCase/InstallStart/Command.php | 15 ++++++------- .../UseCase/Uninstall/Command.php | 2 +- src/Services/Flusher.php | 4 +--- .../UseCase/ChangeDomainUrl/HandlerTest.php | 8 +++---- .../UseCase/InstallFinish/HandlerTest.php | 4 ++-- .../UseCase/InstallStart/HandlerTest.php | 4 ++-- .../UseCase/Uninstall/HandlerTest.php | 2 +- 10 files changed, 41 insertions(+), 46 deletions(-) diff --git a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php index f1b48be..5fb37ad 100644 --- a/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php +++ b/src/Bitrix24Accounts/Infrastructure/Doctrine/Bitrix24AccountRepository.php @@ -38,7 +38,8 @@ public function getById(Uuid $uuid): Bitrix24AccountInterface ->setParameter('id', $uuid) ->setParameter('status', Bitrix24AccountStatus::deleted) ->getQuery() - ->getOneOrNullResult(); + ->getOneOrNullResult() + ; if (null === $account) { throw new Bitrix24AccountNotFoundException( @@ -58,7 +59,9 @@ public function existsById(Uuid $uuid): bool ->setParameter('id', $uuid) ->setParameter('status', Bitrix24AccountStatus::deleted) ->getQuery() - ->getOneOrNullResult(); + ->getOneOrNullResult() + ; + return (bool) $account; } @@ -79,8 +82,7 @@ public function findByMemberId( ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?int $bitrix24UserId = null, ?bool $isAdmin = null - ): array - { + ): array { if ('' === trim($memberId)) { throw new InvalidArgumentException('memberId cannot be empty'); } @@ -193,8 +195,7 @@ public function findByDomain( string $domainUrl, ?Bitrix24AccountStatus $bitrix24AccountStatus = null, ?bool $isAdmin = null - ): array - { + ): array { if ('' === trim($domainUrl)) { throw new InvalidArgumentException('domainUrl cannot be an empty string'); } diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index dc1c720..907bebb 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -23,18 +23,17 @@ public function __construct( private function validateDomain(string $domain, string $parameterName): void { // Регулярное выражение для проверки допустимых символов (латиница и кириллица) - $patternValidChars = "/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?validate(); } private function validate(): void { - if ($this->applicationToken === '' || $this->applicationToken === '0') { + if ('' === $this->applicationToken || '0' === $this->applicationToken) { throw new \InvalidArgumentException('Application token cannot be empty.'); } - if ($this->memberId === '' || $this->memberId === '0') { + if ('' === $this->memberId || '0' === $this->memberId) { throw new \InvalidArgumentException('Member ID cannot be empty.'); } @@ -36,18 +35,17 @@ private function validate(): void private function validateDomain(string $domain): void { // Регулярное выражение для проверки допустимых символов (латиница и кириллица) - $patternValidChars = "/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?memberId) || ($this->memberId === '' || $this->memberId === '0')) { + if (!is_string($this->memberId) || ('' === $this->memberId || '0' === $this->memberId)) { throw new \InvalidArgumentException('Member ID must be a non-empty string.'); } @@ -47,18 +47,17 @@ private function validate(): void private function validateDomain(string $domain): void { // Регулярное выражение для проверки допустимых символов (латиница и кириллица) - $patternValidChars = "/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?applicationToken === '' || $this->applicationToken === '0') { + if ('' === $this->applicationToken || '0' === $this->applicationToken) { throw new \InvalidArgumentException('Empty application token application token.'); } } diff --git a/src/Services/Flusher.php b/src/Services/Flusher.php index c4c1a00..240ff74 100644 --- a/src/Services/Flusher.php +++ b/src/Services/Flusher.php @@ -10,9 +10,7 @@ class Flusher { - public function __construct(private readonly EntityManagerInterface $em, private readonly EventDispatcherInterface $eventDispatcher) - { - } + public function __construct(private readonly EntityManagerInterface $em, private readonly EventDispatcherInterface $eventDispatcher) {} public function flush(AggregateRootEventsEmitterInterface ...$aggregateRootEventsEmitter): void { diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index c21d48f..36a21f2 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -60,8 +60,8 @@ protected function setUp(): void } #[Test] - #[TestDox('Test change domain url with happy path - one account')] - public function testChangeDomainUrlWithHappyPath(): void + #[TestDox('Test change domain url for one account')] + public function testChangeDomainUrlForAccount(): void { $oldDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; $newDomainUrl = 'new-'.$oldDomainUrl; @@ -103,8 +103,8 @@ public function testChangeDomainUrlWithHappyPath(): void } #[Test] - #[TestDox('Test change domain url with happy path - many accounts')] - public function testChangeDomainUrlWithHappyPathForManyAccounts(): void + #[TestDox('Test change domain url for many accounts')] + public function testChangeDomainUrlForManyAccounts(): void { $oldDomainUrl = Uuid::v7()->toRfc4122().'-test.bitrix24.com'; $newDomainUrl = 'new-'.$oldDomainUrl; diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 76d43c2..04a8e05 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -63,8 +63,8 @@ protected function setUp(): void } #[Test] - #[TestDox('test finish installation with happy path')] - public function testFinishInstallationWithHappyPath(): void + #[TestDox('test finish installation application')] + public function testFinishInstallationApplication(): void { $bitrix24Account = (new Bitrix24AccountBuilder()) ->withStatus(Bitrix24AccountStatus::new) diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index a0520a9..aecab34 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -69,7 +69,7 @@ protected function setUp(): void * @throws UnknownScopeCodeException */ #[Test] - public function testInstallStartHappyPath(): void + public function testInstallNewApplication(): void { $bitrix24AccountBuilder = (new Bitrix24AccountBuilder()) ->withApplicationScope(new Scope(['crm'])) @@ -169,7 +169,7 @@ public function testInstallStartHappyPath(): void * @throws UnknownScopeCodeException */ #[Test] - public function testCreateExistingAccount(): void + public function testInstallExistingAccount(): void { $bitrix24Account = (new Bitrix24AccountBuilder()) ->withApplicationScope(new Scope(['crm'])) diff --git a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php index 536a1a1..a902791 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/Uninstall/HandlerTest.php @@ -68,7 +68,7 @@ protected function setUp(): void * @throws Bitrix24AccountNotFoundException */ #[Test] - public function testUninstallWithHappyPath(): void + public function testUninstallApplication(): void { $applicationToken = Uuid::v7()->toRfc4122(); From c7a4d8b6b27f31d6df7fb678e2c58bb7c9857eca Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 1 Feb 2025 14:07:36 +0300 Subject: [PATCH 124/130] =?UTF-8?q?-=20=D0=9F=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=BB=D1=8F=20=D1=81s=20fixer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php | 4 ++-- src/Bitrix24Accounts/UseCase/InstallFinish/Command.php | 4 ++-- src/Bitrix24Accounts/UseCase/InstallStart/Command.php | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index 907bebb..0304d13 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -23,13 +23,13 @@ public function __construct( private function validateDomain(string $domain, string $parameterName): void { // Регулярное выражение для проверки допустимых символов (латиница и кириллица) - $patternValidChars = '/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(? Date: Thu, 6 Feb 2025 23:21:21 +0300 Subject: [PATCH 125/130] =?UTF-8?q?-=20=D0=9F=D0=B5=D1=80=D0=B5=D0=BD?= =?UTF-8?q?=D0=B5=D1=81=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D1=8E=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D1=83?= =?UTF-8?q?=20=D0=B4=D0=BE=D0=BC=D0=B5=D0=BD=D0=B0=20=D0=B2=20=D0=BE=D1=82?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=20-=20=D0=92=20=D1=82=D0=B5=D1=81=D1=82=D0=B0=D1=85=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=20=D1=81=D0=BE?= =?UTF-8?q?=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=BA=D0=BE=D0=BC=D0=B0?= =?UTF-8?q?=D0=BD=D0=B4=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 8 +- .../UseCase/ChangeDomainUrl/Command.php | 36 ++------ .../UseCase/InstallFinish/Command.php | 26 ++---- .../UseCase/InstallFinish/Handler.php | 6 +- .../UseCase/InstallStart/Command.php | 25 +----- .../UseCase/InstallStart/Handler.php | 8 +- .../UseCase/ChangeDomainUrl/HandlerTest.php | 9 +- .../UseCase/InstallFinish/HandlerTest.php | 3 +- .../UseCase/InstallStart/HandlerTest.php | 8 +- .../Bitrix24Accounts/DomainCheckerTest.php | 83 ------------------- .../UseCase/ChangeDomainUrl/CommandTest.php | 64 +++++++++----- .../UseCase/InstallFinish/CommandTest.php | 22 +++-- .../UseCase/InstallStart/CommandTest.php | 30 ++++--- .../UseCase/Uninstall/CommandTest.php | 5 +- 14 files changed, 118 insertions(+), 215 deletions(-) delete mode 100644 tests/Unit/Bitrix24Accounts/DomainCheckerTest.php diff --git a/Makefile b/Makefile index d61aebf..5927f0a 100644 --- a/Makefile +++ b/Makefile @@ -16,6 +16,8 @@ include $(ENV) -include $(ENV_LOCAL) +start-rector: vendor + vendor/bin/rector process tests --config=rector.php coding-standards: vendor vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php --diff --verbose @@ -46,6 +48,10 @@ init: @echo "run application…" docker-compose up -d + +clear: + docker-compose run --rm php-cli composer clear-cache + up: @echo "run application…" docker-compose up --build -d @@ -110,7 +116,7 @@ test-run-functional: debug-print-env # Запустить один функциональный тест с дебагером run-one-functional-test: debug-print-env - docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testCreateExistingAccount' tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php + docker-compose run --rm php-cli php -dxdebug.start_with_request=yes vendor/bin/phpunit --filter 'testChangeDomainUrlWithHappyPath' tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php schema-drop: docker-compose run --rm php-cli php bin/doctrine orm:schema-tool:drop --force diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index 0304d13..4ce4d4d 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -4,37 +4,17 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; + readonly class Command { + public string $oldDomain; + public string $newDomain; public function __construct( - /** - * @var non-empty-string $oldDomain - */ - public string $oldDomain, - /** - * @var non-empty-string $newDomain - */ - public string $newDomain + Domain $oldDomain, + Domain $newDomain ) { - $this->validateDomain($oldDomain, 'oldDomainUrlHost'); - $this->validateDomain($newDomain, 'newDomainUrlHost'); - } - - private function validateDomain(string $domain, string $parameterName): void - { - // Регулярное выражение для проверки допустимых символов (латиница и кириллица) - $patternValidChars = '/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?oldDomain = $oldDomain->getValue(); + $this->newDomain = $newDomain->getValue(); } } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index 339d739..ffe1f89 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -4,15 +4,19 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; readonly class Command { + public string $domain; + public function __construct( public string $applicationToken, public string $memberId, - public string $domainUrl, + Domain $domainUrl, public int $bitrix24UserId, ) { $this->validate(); + $this->domain = $domainUrl->getValue(); } private function validate(): void @@ -25,28 +29,8 @@ private function validate(): void throw new \InvalidArgumentException('Member ID cannot be empty.'); } - $this->validateDomain($this->domainUrl); - if ($this->bitrix24UserId <= 0) { throw new \InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); } } - - private function validateDomain(string $domain): void - { - // Регулярное выражение для проверки допустимых символов (латиница и кириллица) - $patternValidChars = '/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?logger->info('Bitrix24Accounts.InstallFinish.start', [ - 'b24_domain_url' => $command->domainUrl, + 'b24_domain_url' => $command->domain, 'b24_member_id' => $command->memberId, 'b24_application_id' => $command->applicationToken, 'b24_user_id' => $command->bitrix24UserId, ]); /** @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ - $bitrix24Account = $this->getSingleAccountByMemberId($command->domainUrl, $command->memberId, $command->bitrix24UserId); + $bitrix24Account = $this->getSingleAccountByMemberId($command->domain, $command->memberId, $command->bitrix24UserId); $bitrix24Account->applicationInstalled($command->applicationToken); @@ -47,7 +47,7 @@ public function handle(Command $command): void $this->logger->info( 'Bitrix24Accounts.InstallFinish.Finish', [ - 'b24_domain_url' => $command->domainUrl, + 'b24_domain_url' => $command->domain, 'b24_member_id' => $command->memberId, 'b24_application_id' => $command->applicationToken, 'b24_user_id' => $command->bitrix24UserId, diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index e9e8636..0bab8f0 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -7,20 +7,23 @@ use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Symfony\Component\Uid\Uuid; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; readonly class Command { + public string $domain; public function __construct( public Uuid $uuid, public int $bitrix24UserId, public bool $isBitrix24UserAdmin, public string $memberId, - public string $domainUrl, + Domain $domainUrl, public AuthToken $authToken, public int $applicationVersion, public Scope $applicationScope ) { $this->validate(); + $this->domain = $domainUrl->getValue(); } private function validate(): void @@ -37,28 +40,8 @@ private function validate(): void throw new \InvalidArgumentException('Member ID must be a non-empty string.'); } - $this->validateDomain($this->domainUrl); - if ($this->applicationVersion <= 0) { throw new \InvalidArgumentException('Application version must be a positive integer.'); } } - - private function validateDomain(string $domain): void - { - // Регулярное выражение для проверки допустимых символов (латиница и кириллица) - $patternValidChars = '/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?logger->info('Bitrix24Accounts.InstallStart.start', [ 'id' => $command->uuid->toRfc4122(), - 'domain_url' => $command->domainUrl, + 'domain' => $command->domain, 'member_id' => $command->memberId, ]); @@ -33,7 +33,7 @@ public function handle(Command $command): void $command->bitrix24UserId, $command->isBitrix24UserAdmin, $command->memberId, - $command->domainUrl, + $command->domain, Bitrix24AccountStatus::new, $command->authToken, new CarbonImmutable(), @@ -53,7 +53,7 @@ public function handle(Command $command): void 'Bitrix24Accounts.InstallStart.Finish', [ 'id' => $command->uuid->toRfc4122(), - 'domain_url' => $command->domainUrl, + 'domain_url' => $command->domain, 'member_id' => $command->memberId, ] ); @@ -62,7 +62,7 @@ public function handle(Command $command): void 'Bitrix24Accounts.InstallStart.AlreadyExists', [ 'id' => $command->uuid->toRfc4122(), - 'domain_url' => $command->domainUrl, + 'domain' => $command->domain, 'member_id' => $command->memberId, ] ); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php index 36a21f2..01e2d5a 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/ChangeDomainUrl/HandlerTest.php @@ -29,6 +29,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; /** * @internal @@ -74,8 +75,8 @@ public function testChangeDomainUrlForAccount(): void $this->handler->handle( new Bitrix24Accounts\UseCase\ChangeDomainUrl\Command( - $oldDomainUrl, - $newDomainUrl + new Domain($oldDomainUrl), + new Domain($newDomainUrl) ) ); @@ -126,8 +127,8 @@ public function testChangeDomainUrlForManyAccounts(): void $this->handler->handle( new Bitrix24Accounts\UseCase\ChangeDomainUrl\Command( - $oldDomainUrl, - $newDomainUrl + new Domain($oldDomainUrl), + new Domain($newDomainUrl) ) ); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php index 04a8e05..f0d1ac0 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallFinish/HandlerTest.php @@ -30,6 +30,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\Uid\Uuid; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; /** * @internal @@ -78,7 +79,7 @@ public function testFinishInstallationApplication(): void new Bitrix24Accounts\UseCase\InstallFinish\Command( $applicationToken, $bitrix24Account->getMemberId(), - $bitrix24Account->getDomainUrl(), + new Domain($bitrix24Account->getDomainUrl()), $bitrix24Account->getBitrix24UserId() ) ); diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index aecab34..8fe33ba 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -33,6 +33,7 @@ use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Stopwatch\Stopwatch; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; /** * @internal @@ -65,7 +66,6 @@ protected function setUp(): void /** * @throws InvalidArgumentException * @throws Bitrix24AccountNotFoundException - * @throws RandomException * @throws UnknownScopeCodeException */ #[Test] @@ -81,7 +81,7 @@ public function testInstallNewApplication(): void $bitrix24AccountBuilder->getBitrix24UserId(), $bitrix24AccountBuilder->isBitrix24UserAdmin(), $bitrix24AccountBuilder->getMemberId(), - $bitrix24AccountBuilder->getDomainUrl(), + new Domain($bitrix24AccountBuilder->getDomainUrl()), $bitrix24AccountBuilder->getAuthToken(), $bitrix24AccountBuilder->getApplicationVersion(), $bitrix24AccountBuilder->getApplicationScope() @@ -181,7 +181,7 @@ public function testInstallExistingAccount(): void $bitrix24Account->getBitrix24UserId(), $bitrix24Account->isBitrix24UserAdmin(), $bitrix24Account->getMemberId(), - $bitrix24Account->getDomainUrl(), + new Domain($bitrix24Account->getDomainUrl()), $bitrix24Account->getAuthToken(), $bitrix24Account->getApplicationVersion(), $bitrix24Account->getApplicationScope() @@ -199,7 +199,7 @@ public function testInstallExistingAccount(): void $bitrix24Account->getBitrix24UserId(), $bitrix24Account->isBitrix24UserAdmin(), $bitrix24Account->getMemberId(), - $bitrix24Account->getDomainUrl(), + new Domain($bitrix24Account->getDomainUrl()), $bitrix24Account->getAuthToken(), $bitrix24Account->getApplicationVersion(), $bitrix24Account->getApplicationScope() diff --git a/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php b/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php deleted file mode 100644 index 123e0f4..0000000 --- a/tests/Unit/Bitrix24Accounts/DomainCheckerTest.php +++ /dev/null @@ -1,83 +0,0 @@ -assertEquals(6, $exceptionCount, 'Expected 6 invalid exception and received ' . $exceptionCount); - } else { - // Если ожидается отсутствие исключений, проверяем что их не было - $this->assertEquals(0, $exceptionCount, sprintf('No exceptions were expected but %d were thrown.', $exceptionCount)); - } - - } - - public static function dataForCommand(): \Generator - { - - // Примеры недопустимых доменов - $arrInvalidDomains = [ - ['oldDomain' => 'invalid_domain.com', 'newDomain' => 'valid.com'], // Неправильный формат (подчеркивание) - ['oldDomain' => '-invalid.com', 'newDomain' => 'valid.com'], // Домен не может начинаться с дефиса - ['oldDomain' => 'invalid-.com', 'newDomain' => 'valid.com'], // Домен не может заканчиваться на дефис - ['oldDomain' => '123.456.789.0', 'newDomain' => 'valid.com'], // Неправильный формат (IP-адрес) - ['oldDomain' => 'example..com', 'newDomain' => 'valid.com'], // Два подряд идущих точки - ['oldDomain' => 'example.c', 'newDomain' => 'valid.com'] // Слишком короткая доменная зона - ]; - - // Примеры допустимых доменов - $arrValidDomains = [ - ['oldDomain' => 'example.com', 'newDomain' => 'example.org'], - ['oldDomain' => 'пример.рф', 'newDomain' => 'пример.рус'], - ['oldDomain' => 'test-site.org', 'newDomain' => 'test-site.ru'], - ['oldDomain' => 'valid-domain.co.uk', 'newDomain' => 'valid-domain.net'], - ['oldDomain' => 'subdomain.example.com', 'newDomain' => 'subdomain2.example.com'], - ['oldDomain' => 'тест.рус', 'newDomain' => 'тест2.рус'], // Пример с кириллицей - ]; - - yield 'invalidDomain' => [ - [$arrInvalidDomains], // Оборачиваем в массив для передачи в testValidCommand - \InvalidArgumentException::class - ]; - - yield 'validDomain' => [ - [$arrValidDomains], // Оборачиваем в массив для передачи в testValidCommand - null // Здесь исключение не ожидается - ]; - } -} diff --git a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php index bfd3e1d..2f4bfe4 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php @@ -5,6 +5,7 @@ namespace Bitrix24\Lib\Tests\Unit\Bitrix24Accounts\UseCase\ChangeDomainUrl; use Bitrix24\Lib\Bitrix24Accounts\UseCase\ChangeDomainUrl\Command; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; @@ -18,43 +19,64 @@ class CommandTest extends TestCase { #[Test] - #[DataProvider('dataForCommand')] - public function testValidCommand( - string $oldDomain, - string $newDomain, + #[DataProvider('dataForValidateDomain')] + public function testValidateDomain( + array $arrDomains, ?string $expectedException - ): void - { + ): void { - if ($expectedException !== null) { - $this->expectException(\InvalidArgumentException::class); + $exceptionCount = 0; + foreach ($arrDomains as $arrDomain) { + try { + $oldDomain = new Domain($arrDomain['oldDomain']); + $newDomain = new Domain($arrDomain['newDomain']); + new Command($oldDomain, $newDomain); + } catch (\InvalidArgumentException) { + // Увеличиваем счетчик при каждом выбросе исключения + $exceptionCount++; + } } - $command = new Command($oldDomain, $newDomain); - - if ($expectedException == null) { - $this->assertInstanceOf(Command::class, $command); + // Проверяем, сколько исключений было выброшено + if ($expectedException !== null) { + $this->assertEquals(6, $exceptionCount, 'Expected 6 invalid exception and received ' . $exceptionCount); + } else { + // Если ожидается отсутствие исключений, проверяем что их не было + $this->assertEquals(0, $exceptionCount, sprintf('No exceptions were expected but %d were thrown.', $exceptionCount)); } } - public static function dataForCommand(): \Generator + public static function dataForValidateDomain(): \Generator { - $invalidOldDomain = 'invalid_domain.com'; - $invalidNewDomain = 'valid.com'; - $validOldDomain = 'example.com'; - $validNewDomain = 'example.org'; + // Примеры недопустимых доменов + $arrInvalidDomains = [ + ['oldDomain' => 'invalid_domain.com', 'newDomain' => 'valid.com'], // Неправильный формат (подчеркивание) + ['oldDomain' => '-invalid.com', 'newDomain' => 'valid.com'], // Домен не может начинаться с дефиса + ['oldDomain' => 'invalid-.com', 'newDomain' => 'valid.com'], // Домен не может заканчиваться на дефис + ['oldDomain' => '123.456.789.0', 'newDomain' => 'valid.com'], // Неправильный формат (IP-адрес) + ['oldDomain' => 'example..com', 'newDomain' => 'valid.com'], // Два подряд идущих точки + ['oldDomain' => 'example.c', 'newDomain' => 'valid.com'] // Слишком короткая доменная зона + ]; + + // Примеры допустимых доменов + $arrValidDomains = [ + ['oldDomain' => 'example.com', 'newDomain' => 'example.org'], + ['oldDomain' => 'пример.рф', 'newDomain' => 'пример.рус'], + ['oldDomain' => 'test-site.org', 'newDomain' => 'test-site.ru'], + ['oldDomain' => 'valid-domain.co.uk', 'newDomain' => 'valid-domain.net'], + ['oldDomain' => 'subdomain.example.com', 'newDomain' => 'subdomain2.example.com'], + ['oldDomain' => 'тест.рус', 'newDomain' => 'тест2.рус'], // Пример с кириллицей + ]; yield 'invalidDomain' => [ - $invalidOldDomain, - $invalidNewDomain, + $arrInvalidDomains, // Оборачиваем в массив для передачи в testValidCommand \InvalidArgumentException::class ]; yield 'validDomain' => [ - $validOldDomain, - $validNewDomain, + $arrValidDomains, // Оборачиваем в массив для передачи в testValidCommand null // Здесь исключение не ожидается ]; } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index c11824b..dd7d259 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -12,6 +12,8 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Symfony\Component\Uid\Uuid; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; + /** * @internal @@ -22,13 +24,14 @@ class CommandTest extends TestCase #[Test] #[DataProvider('dataForCommand')] public function testValidCommand( - string $applicationToken, - string $memberId, - string $domainUrl, - int $bitrix24UserId, + string $applicationToken, + string $memberId, + string $domainUrl, + int $bitrix24UserId, ?string $expectedException, ?string $expectedExceptionMessage, - ): void { + ): void + { if (null !== $expectedException) { $this->expectException($expectedException); } @@ -37,12 +40,15 @@ public function testValidCommand( $this->expectExceptionMessage($expectedExceptionMessage); } - new Command( + $domainObject = new Domain($domainUrl); + + $command = new Command( $applicationToken, $memberId, - $domainUrl, + $domainObject, $bitrix24UserId ); + } public static function dataForCommand(): \Generator @@ -76,7 +82,7 @@ public static function dataForCommand(): \Generator '', $bitrix24Account->getBitrix24UserId(), \InvalidArgumentException::class, - 'Domain URL is not valid.' + sprintf('Invalid domain: %s', '') ]; } } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php index c9f1a21..3369550 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallStart/CommandTest.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Symfony\Component\Uid\Uuid; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; + /** * @internal @@ -24,17 +26,18 @@ class CommandTest extends TestCase #[Test] #[DataProvider('dataForCommand')] public function testValidCommand( - Uuid $uuid, - int $bitrix24UserId, - bool $isBitrix24UserAdmin, - string $memberId, - string $domainUrl, + Uuid $uuid, + int $bitrix24UserId, + bool $isBitrix24UserAdmin, + string $memberId, + string $domainUrl, AuthToken $authToken, - int $applicationVersion, - Scope $applicationScope, - ?string $expectedException, - ?string $expectedExceptionMessage, - ): void { + int $applicationVersion, + Scope $applicationScope, + ?string $expectedException, + ?string $expectedExceptionMessage, + ): void + { if (null !== $expectedException) { $this->expectException($expectedException); } @@ -43,16 +46,19 @@ public function testValidCommand( $this->expectExceptionMessage($expectedExceptionMessage); } + $domain = new Domain($domainUrl); + new Command( $uuid, $bitrix24UserId, $isBitrix24UserAdmin, $memberId, - $domainUrl, + $domain, $authToken, $applicationVersion, $applicationScope ); + } public static function dataForCommand(): \Generator @@ -84,7 +90,7 @@ public static function dataForCommand(): \Generator $bitrix24Account->getApplicationVersion(), $bitrix24Account->getApplicationScope(), \InvalidArgumentException::class, - 'Domain URL is not valid.' + sprintf('Invalid domain: %s', '') ]; yield 'validBitrix24UserId' => [ diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php index db55093..a037d1c 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -41,11 +41,8 @@ public function testValidCommand( public static function dataForCommand(): \Generator { - - $applicationToken = Uuid::v7()->toRfc4122(); - yield 'validApplicationToken' => [ - $applicationToken, + Uuid::v7()->toRfc4122(), null, null, ]; From 48173d7bdf443576c631fac8225d2fb69f02b931 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 8 Feb 2025 14:08:44 +0300 Subject: [PATCH 126/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/InstallFinish/Command.php | 2 +- .../UseCase/InstallStart/Command.php | 5 +- .../UseCase/Uninstall/Command.php | 4 +- .../Builders/Bitrix24AccountBuilder.php | 2 +- .../UseCase/ChangeDomainUrl/CommandTest.php | 67 ++++++++++++++----- .../UseCase/Uninstall/CommandTest.php | 30 +++++---- 6 files changed, 73 insertions(+), 37 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index ffe1f89..d0a75a9 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -21,7 +21,7 @@ public function __construct( private function validate(): void { - if ('' === $this->applicationToken || '0' === $this->applicationToken) { + if ('' === $this->applicationToken) { throw new \InvalidArgumentException('Application token cannot be empty.'); } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index 0bab8f0..26526f7 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -28,15 +28,12 @@ public function __construct( private function validate(): void { - if (empty($this->uuid)) { - throw new \InvalidArgumentException('Empty UUID provided.'); - } if ($this->bitrix24UserId <= 0) { throw new \InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); } - if (!is_string($this->memberId) || ('' === $this->memberId || '0' === $this->memberId)) { + if ('' === $this->memberId) { throw new \InvalidArgumentException('Member ID must be a non-empty string.'); } diff --git a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php index a4a52e1..5a92c6a 100644 --- a/src/Bitrix24Accounts/UseCase/Uninstall/Command.php +++ b/src/Bitrix24Accounts/UseCase/Uninstall/Command.php @@ -17,8 +17,8 @@ public function __construct( private function validate(): void { - if ('' === $this->applicationToken || '0' === $this->applicationToken) { - throw new \InvalidArgumentException('Empty application token application token.'); + if ('' === $this->applicationToken) { + throw new \InvalidArgumentException('Application token must be a non-empty string.'); } } } diff --git a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php index a63331a..bff547e 100644 --- a/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php +++ b/tests/Functional/Bitrix24Accounts/Builders/Bitrix24AccountBuilder.php @@ -98,7 +98,7 @@ public function withStatus(Bitrix24AccountStatus $bitrix24AccountStatus): self return $this; } - public function build(): AggregateRootEventsEmitterInterface&Bitrix24AccountInterface + public function build(): Bitrix24Account { $bitrix24Account = new Bitrix24Account( $this->id, diff --git a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php index 2f4bfe4..23b1435 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php @@ -19,7 +19,7 @@ class CommandTest extends TestCase { #[Test] - #[DataProvider('dataForValidateDomain')] + #[DataProvider('dataForValidateInvalidDomain')] public function testValidateDomain( array $arrDomains, ?string $expectedException @@ -47,18 +47,37 @@ public function testValidateDomain( } - public static function dataForValidateDomain(): \Generator - { + #[Test] + #[DataProvider('dataForValidateValidDomain')] + public function testValidateInvalidDomain( + array $arrDomains, + ?string $expectedException + ): void { - // Примеры недопустимых доменов - $arrInvalidDomains = [ - ['oldDomain' => 'invalid_domain.com', 'newDomain' => 'valid.com'], // Неправильный формат (подчеркивание) - ['oldDomain' => '-invalid.com', 'newDomain' => 'valid.com'], // Домен не может начинаться с дефиса - ['oldDomain' => 'invalid-.com', 'newDomain' => 'valid.com'], // Домен не может заканчиваться на дефис - ['oldDomain' => '123.456.789.0', 'newDomain' => 'valid.com'], // Неправильный формат (IP-адрес) - ['oldDomain' => 'example..com', 'newDomain' => 'valid.com'], // Два подряд идущих точки - ['oldDomain' => 'example.c', 'newDomain' => 'valid.com'] // Слишком короткая доменная зона - ]; + $exceptionCount = 0; + foreach ($arrDomains as $arrDomain) { + try { + $oldDomain = new Domain($arrDomain['oldDomain']); + $newDomain = new Domain($arrDomain['newDomain']); + new Command($oldDomain, $newDomain); + } catch (\InvalidArgumentException) { + // Увеличиваем счетчик при каждом выбросе исключения + $exceptionCount++; + } + } + + // Проверяем, сколько исключений было выброшено + if ($expectedException !== null) { + $this->assertEquals(6, $exceptionCount, 'Expected 6 invalid exception and received ' . $exceptionCount); + } else { + // Если ожидается отсутствие исключений, проверяем что их не было + $this->assertEquals(0, $exceptionCount, sprintf('No exceptions were expected but %d were thrown.', $exceptionCount)); + } + + } + + public static function dataForValidateValidDomain(): \Generator + { // Примеры допустимых доменов $arrValidDomains = [ @@ -70,14 +89,28 @@ public static function dataForValidateDomain(): \Generator ['oldDomain' => 'тест.рус', 'newDomain' => 'тест2.рус'], // Пример с кириллицей ]; - yield 'invalidDomain' => [ - $arrInvalidDomains, // Оборачиваем в массив для передачи в testValidCommand - \InvalidArgumentException::class - ]; - yield 'validDomain' => [ $arrValidDomains, // Оборачиваем в массив для передачи в testValidCommand null // Здесь исключение не ожидается ]; } + + public static function dataForValidateInvalidDomain(): \Generator + { + + // Примеры недопустимых доменов + $arrInvalidDomains = [ + ['oldDomain' => 'invalid_domain.com', 'newDomain' => 'valid.com'], // Неправильный формат (подчеркивание) + ['oldDomain' => '-invalid.com', 'newDomain' => 'valid.com'], // Домен не может начинаться с дефиса + ['oldDomain' => 'invalid-.com', 'newDomain' => 'valid.com'], // Домен не может заканчиваться на дефис + ['oldDomain' => '123.456.789.0', 'newDomain' => 'valid.com'], // Неправильный формат (IP-адрес) + ['oldDomain' => 'example..com', 'newDomain' => 'valid.com'], // Два подряд идущих точки + ['oldDomain' => 'example.c', 'newDomain' => 'valid.com'] // Слишком короткая доменная зона + ]; + + yield 'invalidDomain' => [ + $arrInvalidDomains, // Оборачиваем в массив для передачи в testValidCommand + \InvalidArgumentException::class + ]; + } } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php index a037d1c..817dbb0 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -18,8 +18,17 @@ class CommandTest extends TestCase { #[Test] - #[DataProvider('dataForCommand')] - public function testValidCommand( + #[DataProvider('dataForCommandValidToken')] + public function testValidTokenForCommand( + string $applicationToken, + ): void { + $command = new Command($applicationToken); + $this->assertInstanceOf(Command::class, $command); + } + + #[Test] + #[DataProvider('dataForCommandEmptyToken')] + public function testEmptyTokenForCommand( string $applicationToken, ?string $expectedException, ?string $expectedExceptionMessage, @@ -32,25 +41,22 @@ public function testValidCommand( $this->expectExceptionMessage($expectedExceptionMessage); } - $command = new Command($applicationToken); - - if ($expectedException == null) { - $this->assertInstanceOf(Command::class, $command); - } + new Command($applicationToken); } - public static function dataForCommand(): \Generator + public static function dataForCommandValidToken(): \Generator { yield 'validApplicationToken' => [ - Uuid::v7()->toRfc4122(), - null, - null, + Uuid::v7()->toRfc4122() ]; + } + public static function dataForCommandEmptyToken(): \Generator + { yield 'emptyApplicationToken' => [ '', \InvalidArgumentException::class, - 'Empty application token application token.', + 'Application token must be a non-empty string.', ]; } } From d7542887b96065221f9d9f1a09ae53385298a8ac Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 9 Feb 2025 11:48:29 +0300 Subject: [PATCH 127/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8C=20=D0=B0=D0=BA=D0=BA=D0=B0=D1=83=D0=BD=D1=82=D0=B0=20,?= =?UTF-8?q?=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=BF=D0=B0?= =?UTF-8?q?=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80=D1=8B=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D0=B0=20updateApplicationVers?= =?UTF-8?q?ion=20-=20=D0=AE=D0=B7=D0=B0=D0=BD=D1=83=D0=BB=20cs-fixer=20-?= =?UTF-8?q?=20=D0=AE=D0=B7=D0=B0=D0=BD=D1=83=D0=BB=20=D1=80=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=D0=BE=D1=80=20-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8C=20Domain?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entity/Bitrix24Account.php | 2 +- .../UseCase/ChangeDomainUrl/Command.php | 2 + .../UseCase/InstallFinish/Command.php | 5 ++- .../UseCase/InstallStart/Command.php | 8 ++-- src/Bitrix24Accounts/ValueObjects/Domain.php | 39 +++++++++++++++++++ .../UseCase/InstallFinish/CommandTest.php | 6 +-- 6 files changed, 52 insertions(+), 10 deletions(-) create mode 100644 src/Bitrix24Accounts/ValueObjects/Domain.php diff --git a/src/Bitrix24Accounts/Entity/Bitrix24Account.php b/src/Bitrix24Accounts/Entity/Bitrix24Account.php index a269988..616f75d 100644 --- a/src/Bitrix24Accounts/Entity/Bitrix24Account.php +++ b/src/Bitrix24Accounts/Entity/Bitrix24Account.php @@ -233,7 +233,7 @@ public function getUpdatedAt(): CarbonImmutable * @throws InvalidArgumentException */ #[\Override] - public function updateApplicationVersion(int $version, ?Scope $newScope): void + public function updateApplicationVersion(AuthToken $authToken, int $b24UserId, int $version, ?Scope $newScope): void { if (Bitrix24AccountStatus::active !== $this->status) { throw new InvalidArgumentException( diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index 4ce4d4d..e93ce70 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -9,7 +9,9 @@ readonly class Command { public string $oldDomain; + public string $newDomain; + public function __construct( Domain $oldDomain, Domain $newDomain diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index d0a75a9..2ab9f21 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -5,6 +5,7 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallFinish; use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; + readonly class Command { public string $domain; @@ -12,11 +13,11 @@ public function __construct( public string $applicationToken, public string $memberId, - Domain $domainUrl, + Domain $domain, public int $bitrix24UserId, ) { $this->validate(); - $this->domain = $domainUrl->getValue(); + $this->domain = $domain->getValue(); } private function validate(): void diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index 26526f7..3b95869 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -4,31 +4,31 @@ namespace Bitrix24\Lib\Bitrix24Accounts\UseCase\InstallStart; +use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; use Bitrix24\SDK\Core\Credentials\AuthToken; use Bitrix24\SDK\Core\Credentials\Scope; use Symfony\Component\Uid\Uuid; -use Bitrix24\Lib\Bitrix24Accounts\ValueObjects\Domain; readonly class Command { public string $domain; + public function __construct( public Uuid $uuid, public int $bitrix24UserId, public bool $isBitrix24UserAdmin, public string $memberId, - Domain $domainUrl, + Domain $domain, public AuthToken $authToken, public int $applicationVersion, public Scope $applicationScope ) { $this->validate(); - $this->domain = $domainUrl->getValue(); + $this->domain = $domain->getValue(); } private function validate(): void { - if ($this->bitrix24UserId <= 0) { throw new \InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); } diff --git a/src/Bitrix24Accounts/ValueObjects/Domain.php b/src/Bitrix24Accounts/ValueObjects/Domain.php new file mode 100644 index 0000000..f958a5a --- /dev/null +++ b/src/Bitrix24Accounts/ValueObjects/Domain.php @@ -0,0 +1,39 @@ +validate($domain); + $this->value = $domain; + } + + public function getValue(): string + { + return $this->value; + } + + private function validate(string $domain): void + { + // Регулярное выражение для проверки допустимых символов (латиница и кириллица) + $patternValidChars = '/^((?!-)[A-Za-zА-Яа-яЁё0-9-]{1,63}(?expectExceptionMessage($expectedExceptionMessage); } - $domainObject = new Domain($domainUrl); + $domain = new Domain($domainUrl); - $command = new Command( + new Command( $applicationToken, $memberId, - $domainObject, + $domain, $bitrix24UserId ); From 556720d328d885037ed6568d419e7aeb18739077 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Mon, 10 Feb 2025 23:15:59 +0300 Subject: [PATCH 128/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D0=B4=D0=BE=D0=BC=D0=B5=D0=BD=20-=20?= =?UTF-8?q?=D0=9F=D0=BE=D1=84=D0=B8=D0=BA=D1=81=D0=B8=D0=BB=20=D1=8E=D0=BD?= =?UTF-8?q?=D0=B8=D1=82=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D0=B8=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BC=D0=B5=D0=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/ChangeDomainUrl/Command.php | 8 +- .../UseCase/InstallFinish/Command.php | 7 +- .../UseCase/InstallStart/Command.php | 4 +- src/Bitrix24Accounts/ValueObjects/Domain.php | 7 +- .../UseCase/ChangeDomainUrl/CommandTest.php | 142 +++++++++++------- .../UseCase/InstallFinish/CommandTest.php | 7 +- .../UseCase/Uninstall/CommandTest.php | 2 +- 7 files changed, 99 insertions(+), 78 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index e93ce70..2dcc847 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -8,15 +8,15 @@ readonly class Command { - public string $oldDomain; + public Domain $oldDomain; - public string $newDomain; + public Domain $newDomain; public function __construct( Domain $oldDomain, Domain $newDomain ) { - $this->oldDomain = $oldDomain->getValue(); - $this->newDomain = $newDomain->getValue(); + $this->oldDomain = $oldDomain; + $this->newDomain = $newDomain; } } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index 2ab9f21..1e253b3 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -8,7 +8,7 @@ readonly class Command { - public string $domain; + public Domain $domain; public function __construct( public string $applicationToken, @@ -16,8 +16,9 @@ public function __construct( Domain $domain, public int $bitrix24UserId, ) { + $this->domain = $domain; $this->validate(); - $this->domain = $domain->getValue(); + } private function validate(): void @@ -26,7 +27,7 @@ private function validate(): void throw new \InvalidArgumentException('Application token cannot be empty.'); } - if ('' === $this->memberId || '0' === $this->memberId) { + if ('' === $this->memberId) { throw new \InvalidArgumentException('Member ID cannot be empty.'); } diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index 3b95869..936169e 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -11,7 +11,7 @@ readonly class Command { - public string $domain; + public Domain $domain; public function __construct( public Uuid $uuid, @@ -24,7 +24,7 @@ public function __construct( public Scope $applicationScope ) { $this->validate(); - $this->domain = $domain->getValue(); + $this->domain = $domain; } private function validate(): void diff --git a/src/Bitrix24Accounts/ValueObjects/Domain.php b/src/Bitrix24Accounts/ValueObjects/Domain.php index f958a5a..a399ee7 100644 --- a/src/Bitrix24Accounts/ValueObjects/Domain.php +++ b/src/Bitrix24Accounts/ValueObjects/Domain.php @@ -6,7 +6,7 @@ readonly class Domain { - private string $value; + public string $value; public function __construct(string $domain) { @@ -14,11 +14,6 @@ public function __construct(string $domain) $this->value = $domain; } - public function getValue(): string - { - return $this->value; - } - private function validate(string $domain): void { // Регулярное выражение для проверки допустимых символов (латиница и кириллица) diff --git a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php index 23b1435..bb3646f 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/ChangeDomainUrl/CommandTest.php @@ -19,98 +19,124 @@ class CommandTest extends TestCase { #[Test] - #[DataProvider('dataForValidateInvalidDomain')] + #[DataProvider('dataForValidateValidDomain')] public function testValidateDomain( - array $arrDomains, - ?string $expectedException + string $oldDomain, + string $newDomain, ): void { - - $exceptionCount = 0; - foreach ($arrDomains as $arrDomain) { - try { - $oldDomain = new Domain($arrDomain['oldDomain']); - $newDomain = new Domain($arrDomain['newDomain']); - new Command($oldDomain, $newDomain); - } catch (\InvalidArgumentException) { - // Увеличиваем счетчик при каждом выбросе исключения - $exceptionCount++; - } - } - - // Проверяем, сколько исключений было выброшено - if ($expectedException !== null) { - $this->assertEquals(6, $exceptionCount, 'Expected 6 invalid exception and received ' . $exceptionCount); - } else { - // Если ожидается отсутствие исключений, проверяем что их не было - $this->assertEquals(0, $exceptionCount, sprintf('No exceptions were expected but %d were thrown.', $exceptionCount)); - } - + new Domain($oldDomain); + new Domain($newDomain); + $this->assertTrue(true); } #[Test] - #[DataProvider('dataForValidateValidDomain')] + #[DataProvider('dataForValidateInvalidDomain')] public function testValidateInvalidDomain( - array $arrDomains, - ?string $expectedException + string $oldDomain, + string $newDomain, + ?string $expectedException, + ?string $expectedExceptionMessage ): void { - $exceptionCount = 0; - foreach ($arrDomains as $arrDomain) { - try { - $oldDomain = new Domain($arrDomain['oldDomain']); - $newDomain = new Domain($arrDomain['newDomain']); - new Command($oldDomain, $newDomain); - } catch (\InvalidArgumentException) { - // Увеличиваем счетчик при каждом выбросе исключения - $exceptionCount++; - } + if ($expectedException !== null) { + $this->expectException($expectedException); } - // Проверяем, сколько исключений было выброшено - if ($expectedException !== null) { - $this->assertEquals(6, $exceptionCount, 'Expected 6 invalid exception and received ' . $exceptionCount); - } else { - // Если ожидается отсутствие исключений, проверяем что их не было - $this->assertEquals(0, $exceptionCount, sprintf('No exceptions were expected but %d were thrown.', $exceptionCount)); + if ($expectedExceptionMessage !== null) { + $this->expectExceptionMessage($expectedExceptionMessage); } + new Domain($oldDomain); + new Domain($newDomain); + } public static function dataForValidateValidDomain(): \Generator { // Примеры допустимых доменов - $arrValidDomains = [ + /*$arrValidDomains = [ ['oldDomain' => 'example.com', 'newDomain' => 'example.org'], ['oldDomain' => 'пример.рф', 'newDomain' => 'пример.рус'], ['oldDomain' => 'test-site.org', 'newDomain' => 'test-site.ru'], ['oldDomain' => 'valid-domain.co.uk', 'newDomain' => 'valid-domain.net'], ['oldDomain' => 'subdomain.example.com', 'newDomain' => 'subdomain2.example.com'], ['oldDomain' => 'тест.рус', 'newDomain' => 'тест2.рус'], // Пример с кириллицей + ];*/ + + yield 'validDomain1' => [ + 'example.com', + 'example.org', ]; - yield 'validDomain' => [ - $arrValidDomains, // Оборачиваем в массив для передачи в testValidCommand - null // Здесь исключение не ожидается + yield 'validDomain2' => [ + 'пример.рф', + 'пример.рус', + ]; + + yield 'validDomain3' => [ + 'test-site.org', + 'test-site.ru', + ]; + + yield 'validDomain4' => [ + 'valid-domain.co.uk', + 'valid-domain.net', + ]; + + yield 'validDomain5' => [ + 'subdomain.example.com', + 'subdomain2.example.com', + ]; + + yield 'validDomain6' => [ + 'тест.рус', + 'тест2.рус', ]; } public static function dataForValidateInvalidDomain(): \Generator { + yield 'invalidDomain1' => [ + 'invalid_domain.com', // Неправильный формат (подчеркивание) + 'valid.com', + \InvalidArgumentException::class, + sprintf('Invalid domain: %s', 'invalid_domain.com') + ]; + + yield 'invalidDomain2' => [ + '-invalid.com', // Домен не может начинаться с дефиса + 'valid.com', + \InvalidArgumentException::class, + sprintf('Invalid domain: %s', '-invalid.com') + ]; + + yield 'invalidDomain3' => [ + 'invalid-.com', // Домен не может заканчиваться на дефис + 'valid.com', + \InvalidArgumentException::class, + sprintf('Invalid domain: %s', 'invalid-.com') + ]; + + yield 'invalidDomain4' => [ + '123.456.789.0', // Неправильный формат (IP-адрес) + 'valid.com', + \InvalidArgumentException::class, + sprintf('Invalid domain: %s', '123.456.789.0') + ]; - // Примеры недопустимых доменов - $arrInvalidDomains = [ - ['oldDomain' => 'invalid_domain.com', 'newDomain' => 'valid.com'], // Неправильный формат (подчеркивание) - ['oldDomain' => '-invalid.com', 'newDomain' => 'valid.com'], // Домен не может начинаться с дефиса - ['oldDomain' => 'invalid-.com', 'newDomain' => 'valid.com'], // Домен не может заканчиваться на дефис - ['oldDomain' => '123.456.789.0', 'newDomain' => 'valid.com'], // Неправильный формат (IP-адрес) - ['oldDomain' => 'example..com', 'newDomain' => 'valid.com'], // Два подряд идущих точки - ['oldDomain' => 'example.c', 'newDomain' => 'valid.com'] // Слишком короткая доменная зона + yield 'invalidDomain5' => [ + 'example..com', // Два подряд идущих точки + 'valid.com', + \InvalidArgumentException::class, + sprintf('Invalid domain: %s', 'example..com') ]; - yield 'invalidDomain' => [ - $arrInvalidDomains, // Оборачиваем в массив для передачи в testValidCommand - \InvalidArgumentException::class + yield 'invalidDomain6' => [ + 'example.c', // Слишком короткая доменная зона + 'valid.com', + \InvalidArgumentException::class, + sprintf('Invalid domain: %s', 'example.c') ]; } } diff --git a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php index 71d250f..44559ef 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/InstallFinish/CommandTest.php @@ -32,6 +32,7 @@ public function testValidCommand( ?string $expectedExceptionMessage, ): void { + if (null !== $expectedException) { $this->expectException($expectedException); } @@ -41,14 +42,12 @@ public function testValidCommand( } $domain = new Domain($domainUrl); - - new Command( + new Command( $applicationToken, $memberId, $domain, $bitrix24UserId ); - } public static function dataForCommand(): \Generator @@ -76,7 +75,7 @@ public static function dataForCommand(): \Generator 'Member ID cannot be empty.' ]; - yield 'validDomain' => [ + yield 'invalidDomain' => [ $applicationToken, $bitrix24Account->getMemberId(), '', diff --git a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php index 817dbb0..257a99d 100644 --- a/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php +++ b/tests/Unit/Bitrix24Accounts/UseCase/Uninstall/CommandTest.php @@ -23,7 +23,7 @@ public function testValidTokenForCommand( string $applicationToken, ): void { $command = new Command($applicationToken); - $this->assertInstanceOf(Command::class, $command); + $this->assertEquals($applicationToken,$command->applicationToken); } #[Test] From c80df26044d3583fac8380bda2ae721b806806b6 Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sat, 15 Feb 2025 23:49:58 +0300 Subject: [PATCH 129/130] =?UTF-8?q?-=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D0=B4=D0=BE=D0=BC=D0=B5=D0=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/ChangeDomainUrl/Command.php | 12 +----------- .../UseCase/ChangeDomainUrl/Handler.php | 8 ++++---- .../UseCase/InstallFinish/Command.php | 6 +----- .../UseCase/InstallFinish/Handler.php | 2 +- .../UseCase/InstallStart/Command.php | 5 +---- .../UseCase/InstallStart/Handler.php | 2 +- 6 files changed, 9 insertions(+), 26 deletions(-) diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php index 2dcc847..0d640a8 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Command.php @@ -8,15 +8,5 @@ readonly class Command { - public Domain $oldDomain; - - public Domain $newDomain; - - public function __construct( - Domain $oldDomain, - Domain $newDomain - ) { - $this->oldDomain = $oldDomain; - $this->newDomain = $newDomain; - } + public function __construct(public Domain $oldDomain, public Domain $newDomain) {} } diff --git a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php index d6322ed..5896f9e 100644 --- a/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php +++ b/src/Bitrix24Accounts/UseCase/ChangeDomainUrl/Handler.php @@ -21,14 +21,14 @@ public function __construct( public function handle(Command $command): void { $this->logger->info('Bitrix24Accounts.ChangeDomainUrl.start', [ - 'b24_domain_url_old' => $command->oldDomain, - 'b24_domain_url_new' => $command->newDomain, + 'b24_domain_url_old' => $command->oldDomain->value, + 'b24_domain_url_new' => $command->newDomain->value, ]); /** @var AggregateRootEventsEmitterInterface[]|Bitrix24AccountInterface[] $accounts */ - $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomain); + $accounts = $this->bitrix24AccountRepository->findByDomain($command->oldDomain->value); foreach ($accounts as $account) { - $account->changeDomainUrl($command->newDomain); + $account->changeDomainUrl($command->newDomain->value); $this->bitrix24AccountRepository->save($account); } diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php index 1e253b3..979b0e1 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Command.php @@ -8,17 +8,13 @@ readonly class Command { - public Domain $domain; - public function __construct( public string $applicationToken, public string $memberId, - Domain $domain, + public Domain $domain, public int $bitrix24UserId, ) { - $this->domain = $domain; $this->validate(); - } private function validate(): void diff --git a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php index 1a763b3..e5b805d 100644 --- a/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallFinish/Handler.php @@ -37,7 +37,7 @@ public function handle(Command $command): void ]); /** @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ - $bitrix24Account = $this->getSingleAccountByMemberId($command->domain, $command->memberId, $command->bitrix24UserId); + $bitrix24Account = $this->getSingleAccountByMemberId($command->domain->value, $command->memberId, $command->bitrix24UserId); $bitrix24Account->applicationInstalled($command->applicationToken); diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php index 936169e..a63c792 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Command.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Command.php @@ -11,20 +11,17 @@ readonly class Command { - public Domain $domain; - public function __construct( public Uuid $uuid, public int $bitrix24UserId, public bool $isBitrix24UserAdmin, public string $memberId, - Domain $domain, + public Domain $domain, public AuthToken $authToken, public int $applicationVersion, public Scope $applicationScope ) { $this->validate(); - $this->domain = $domain; } private function validate(): void diff --git a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php index 078d78b..01e7ee0 100644 --- a/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php +++ b/src/Bitrix24Accounts/UseCase/InstallStart/Handler.php @@ -33,7 +33,7 @@ public function handle(Command $command): void $command->bitrix24UserId, $command->isBitrix24UserAdmin, $command->memberId, - $command->domain, + $command->domain->value, Bitrix24AccountStatus::new, $command->authToken, new CarbonImmutable(), From 024e6912d2c14c127a80791c9e9d5ee31125c78d Mon Sep 17 00:00:00 2001 From: KarlsonComplete Date: Sun, 16 Feb 2025 13:52:55 +0300 Subject: [PATCH 130/130] =?UTF-8?q?-=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20useCase=20=D0=BD=D0=B0=20=D0=BE=D0=B1=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D1=81=D0=B8=D0=B8=20=D0=B8=20=D0=BD=D0=B0=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D0=B0=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UseCase/UpdateVersion/Command.php | 39 +++++ .../UseCase/UpdateVersion/Handler.php | 92 ++++++++++ .../UseCase/InstallStart/HandlerTest.php | 5 - .../UseCase/UpdateVersion/HandlerTest.php | 157 ++++++++++++++++++ 4 files changed, 288 insertions(+), 5 deletions(-) create mode 100644 src/Bitrix24Accounts/UseCase/UpdateVersion/Command.php create mode 100644 src/Bitrix24Accounts/UseCase/UpdateVersion/Handler.php create mode 100644 tests/Functional/Bitrix24Accounts/UseCase/UpdateVersion/HandlerTest.php diff --git a/src/Bitrix24Accounts/UseCase/UpdateVersion/Command.php b/src/Bitrix24Accounts/UseCase/UpdateVersion/Command.php new file mode 100644 index 0000000..ed6c4f0 --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/UpdateVersion/Command.php @@ -0,0 +1,39 @@ +validate(); + } + + private function validate(): void + { + if ($this->bitrix24UserId <= 0) { + throw new \InvalidArgumentException('Bitrix24 User ID must be a positive integer.'); + } + + if ('' === $this->memberId) { + throw new \InvalidArgumentException('Member ID must be a non-empty string.'); + } + + if ($this->newApplicationVersion <= 0) { + throw new \InvalidArgumentException('Application version must be a positive integer.'); + } + } +} diff --git a/src/Bitrix24Accounts/UseCase/UpdateVersion/Handler.php b/src/Bitrix24Accounts/UseCase/UpdateVersion/Handler.php new file mode 100644 index 0000000..997e500 --- /dev/null +++ b/src/Bitrix24Accounts/UseCase/UpdateVersion/Handler.php @@ -0,0 +1,92 @@ +logger->info('Bitrix24Accounts.UpdateVersion.start', [ + 'uuid' => $command->uuid, + 'bitrix24_user_id' => $command->bitrix24UserId, + 'is_bitrix24UserAdmin' => $command->isBitrix24UserAdmin, + 'member_id' => $command->memberId, + 'auth_token' => $command->authToken, + 'new_application_version' => $command->newApplicationVersion, + 'new_application_scope' => $command->newApplicationScope, + ]); + + $accounts = $this->bitrix24AccountRepository->findByMemberId( + $command->memberId, + Bitrix24AccountStatus::active, + $command->bitrix24UserId, + ); + + if ([] !== $accounts) { + /** @var AggregateRootEventsEmitterInterface|Bitrix24AccountInterface $bitrix24Account */ + $bitrix24Account = $accounts[0]; + $bitrix24Account->updateApplicationVersion( + $command->authToken, + $command->bitrix24UserId, + $command->newApplicationVersion, + $command->newApplicationScope, + ); + + $this->bitrix24AccountRepository->save($bitrix24Account); + $this->flusher->flush($bitrix24Account); + + $this->logger->info('Bitrix24Accounts.UpdateVersion.finish', [ + 'uuid' => $command->uuid, + 'bitrix24_user_id' => $command->bitrix24UserId, + 'is_bitrix24UserAdmin' => $command->isBitrix24UserAdmin, + 'member_id' => $command->memberId, + 'auth_token' => $command->authToken, + 'new_application_version' => $command->newApplicationVersion, + 'new_application_scope' => $command->newApplicationScope, + ]); + } else { + $this->logger->info( + 'Bitrix24Accounts.UpdateVersion.NotFoundAccount', + [ + 'uuid' => $command->uuid, + 'bitrix24_user_id' => $command->bitrix24UserId, + 'is_bitrix24UserAdmin' => $command->isBitrix24UserAdmin, + 'member_id' => $command->memberId, + 'auth_token' => $command->authToken, + 'new_application_version' => $command->newApplicationVersion, + 'new_application_scope' => $command->newApplicationScope, + ] + ); + + throw new MultipleBitrix24AccountsFoundException( + sprintf( + 'bitrix24account not found by memberId %s, status %s and bitrix24UserId %s ', + $command->memberId, + 'active', + $command->bitrix24UserId + ) + ); + } + } +} diff --git a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php index 8fe33ba..0090188 100644 --- a/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php +++ b/tests/Functional/Bitrix24Accounts/UseCase/InstallStart/HandlerTest.php @@ -206,9 +206,4 @@ public function testInstallExistingAccount(): void ) ); } - - - - #[Test] - public function testUpdateAppVersion(): void {} } diff --git a/tests/Functional/Bitrix24Accounts/UseCase/UpdateVersion/HandlerTest.php b/tests/Functional/Bitrix24Accounts/UseCase/UpdateVersion/HandlerTest.php new file mode 100644 index 0000000..8147815 --- /dev/null +++ b/tests/Functional/Bitrix24Accounts/UseCase/UpdateVersion/HandlerTest.php @@ -0,0 +1,157 @@ + + * + * For the full copyright and license information, please view the MIT-LICENSE.txt + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\UseCase\UpdateVersion; + +use Bitrix24\Lib\Bitrix24Accounts; +use Bitrix24\Lib\Bitrix24Accounts\Infrastructure\Doctrine\Bitrix24AccountRepository; +use Bitrix24\Lib\Services\Flusher; +use Bitrix24\Lib\Tests\EntityManagerFactory; +use Bitrix24\Lib\Tests\Functional\Bitrix24Accounts\Builders\Bitrix24AccountBuilder; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Entity\Bitrix24AccountStatus; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Exceptions\MultipleBitrix24AccountsFoundException; +use Bitrix24\SDK\Application\Contracts\Bitrix24Accounts\Repository\Bitrix24AccountRepositoryInterface; +use Bitrix24\SDK\Core\Credentials\Scope; +use Bitrix24\SDK\Core\Exceptions\InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Log\NullLogger; +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\Uid\Uuid; + +/** + * @internal + */ +#[CoversClass(Bitrix24Accounts\UseCase\UpdateVersion\Handler::class)] +class HandlerTest extends TestCase +{ + private Bitrix24Accounts\UseCase\UpdateVersion\Handler $handler; + + private Flusher $flusher; + + private Bitrix24AccountRepositoryInterface $repository; + + private TraceableEventDispatcher $eventDispatcher; + + #[\Override] + protected function setUp(): void + { + $entityManager = EntityManagerFactory::get(); + $eventDispatcher = new EventDispatcher(); + $this->eventDispatcher = new TraceableEventDispatcher($eventDispatcher, new Stopwatch()); + + $this->repository = new Bitrix24AccountRepository($entityManager); + $this->flusher = new Flusher($entityManager, $this->eventDispatcher); + $this->handler = new Bitrix24Accounts\UseCase\UpdateVersion\Handler( + $this->repository, + $this->flusher, + new NullLogger(),); + + } + + #[Test] + public function testSuccessUpdateVersion(): void + { + $applicationToken = Uuid::v7()->toRfc4122(); + + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::active) + ->withApplicationToken($applicationToken) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->handler->handle(new Bitrix24Accounts\UseCase\UpdateVersion\Command( + $bitrix24Account->getId(), + $bitrix24Account->getBitrix24UserId(), + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + $bitrix24Account->getAuthToken(), + 2, + new Scope(['crm','log']) + )); + + $updated = $this->repository->getById($bitrix24Account->getId()); + + $this->assertEquals(2,$updated->getApplicationVersion(), 'expected application version is 2'); + $this->assertEquals(new Scope(['crm','log']),$updated->getApplicationScope(), 'application Scope is not equal'); + } + + #[Test] + public function testNotFoundBitrix24AccountForUpdateVersion(): void + { + $applicationToken = Uuid::v7()->toRfc4122(); + + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::active) + ->withApplicationToken($applicationToken) + ->build(); + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + $this->expectException(MultipleBitrix24AccountsFoundException::class); + $this->expectExceptionMessage(sprintf('bitrix24account not found by memberId %s, status %s and bitrix24UserId %s ', + $bitrix24Account->getMemberId(), + 'active', + 3558) + ); + + $this->handler->handle(new Bitrix24Accounts\UseCase\UpdateVersion\Command( + $bitrix24Account->getId(), + 3558, + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + $bitrix24Account->getAuthToken(), + 2, + new Scope(['crm','log']) + )); + } + + #[Test] + public function testNotValidVersionForUpdateVersion(): void + { + $bitrix24Account = (new Bitrix24AccountBuilder()) + ->withStatus(Bitrix24AccountStatus::active) + ->build(); + + + $this->repository->save($bitrix24Account); + $this->flusher->flush(); + + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + sprintf( + 'you cannot downgrade application version or set some version, current version «%s», but you try to upgrade to «%s»', + $bitrix24Account->getApplicationVersion(), + '1' + ) + ); + + $this->handler->handle(new Bitrix24Accounts\UseCase\UpdateVersion\Command( + $bitrix24Account->getId(), + $bitrix24Account->getBitrix24UserId(), + $bitrix24Account->isBitrix24UserAdmin(), + $bitrix24Account->getMemberId(), + $bitrix24Account->getAuthToken(), + 1, + new Scope(['crm','log']) + )); + } +}