diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index faa073c6..afb0bee8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -14,23 +14,38 @@ jobs: tests: runs-on: ubuntu-latest - name: "PHP ${{ matrix.php }}, Symfony ${{ matrix.symfony }}, Sylius ${{ matrix.sylius }}, MySQL ${{ matrix.mysql }}" + name: "Sylius ${{ matrix.sylius }}, PHP ${{ matrix.php }}, Symfony ${{ matrix.symfony }}, MySQL ${{ matrix.mysql }}, State Machine Adapter ${{ matrix.state_machine_adapter }}" strategy: fail-fast: false matrix: - php: ["8.0", "8.1"] - node: ["16.x"] - mysql: ["5.7", "8.0"] - symfony: ["^5.4", "^6.0"] - sylius: ["~1.12.0"] + php: ["8.1", "8.2"] + node: ["20.x"] + mysql: ["8.0"] + symfony: ["^5.4.21", "^6.4"] + sylius: ["~1.12.0", "~1.13.x-dev"] + state_machine_adapter: ["winzou_state_machine", "symfony_workflow"] + + include: + - php: "8.3" + node: "20.x" + mysql: "8.0" + symfony: "^6.4" + sylius: "~1.13.x-dev" + state_machine_adapter: "symfony_workflow" + + exclude: + - sylius: "~1.12.0" + state_machine_adapter: "symfony_workflow" + env: APP_ENV: test DATABASE_URL: "mysql://root:root@127.0.0.1/sylius?serverVersion=${{ matrix.mysql }}" + TEST_SYLIUS_STATE_MACHINE_ADAPTER: "${{ matrix.state_machine_adapter }}" steps: - - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Setup PHP @@ -43,7 +58,7 @@ jobs: - name: Setup Node - uses: actions/setup-node@v1 + uses: actions/setup-node@v4 with: node-version: "${{ matrix.node }}" @@ -69,11 +84,11 @@ jobs: - name: Get Composer cache directory id: composer-cache - run: echo "::set-output name=dir::$(composer config cache-files-dir)" + run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT - name: Cache Composer - uses: actions/cache@v2 + uses: actions/cache@v4 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-php-${{ matrix.php }}-composer-${{ hashFiles('**/composer.json **/composer.lock') }} @@ -85,7 +100,7 @@ jobs: if: matrix.symfony != '' run: | composer global config --no-plugins allow-plugins.symfony/flex true - composer global require --no-progress --no-scripts --no-plugins "symfony/flex:1.18.5" + composer global require --no-progress --no-scripts --no-plugins "symfony/flex:^2.4" composer config --no-plugins allow-plugins.symfony/thanks true composer config extra.symfony.require "${{ matrix.symfony }}" @@ -101,11 +116,11 @@ jobs: - name: Get Yarn cache directory id: yarn-cache - run: echo "::set-output name=dir::$(yarn cache dir)" + run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT - name: Cache Yarn - uses: actions/cache@v2 + uses: actions/cache@v4 with: path: ${{ steps.yarn-cache.outputs.dir }} key: ${{ runner.os }}-node-${{ matrix.node }}-yarn-${{ hashFiles('**/package.json **/yarn.lock') }} @@ -147,12 +162,21 @@ jobs: name: Load fixtures in test application run: (cd tests/Application && bin/console sylius:fixtures:load -n) + - + name: Run security check + run: symfony security:check + + - + name: Run ECS + run: vendor/bin/ecs check + - name: Validate composer.json run: composer validate --ansi --strict - name: Run analysis + if: ${{ matrix.sylius != '1.13.x-dev' }} run: composer analyse - diff --git a/CONFLICTS.md b/CONFLICTS.md new file mode 100644 index 00000000..06d5f13a --- /dev/null +++ b/CONFLICTS.md @@ -0,0 +1,10 @@ +# CONFLICTS + +This document explains why certain conflicts were added to `composer.json` and +references related issues. + +- `behat/mink-selenium2-driver:>=1.7.0`: + + This version adds strict type to the `Behat\Mink\Driver\Selenium2Driver::visit($url)` method + which causes a fatal error because the method signature is no longer compatible with the parent class: + `PHP Fatal error: Declaration of Behat\Mink\Driver\Selenium2Driver::visit(string $url) must be compatible with Behat\Mink\Driver\CoreDriver::visit($url) in /home/runner/work/Sylius-Standard/Sylius-Standard/vendor/behat/mink-selenium2-driver/src/Selenium2Driver.php on line 401` diff --git a/README.md b/README.md index fe5385fd..1a3cdc60 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

- +


diff --git a/UPGRADE.md b/UPGRADE.md index 4aa87617..9dfd6fc6 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,3 +1,79 @@ +### UPGRADE FROM 1.5.1 to 1.6 + +1. Support for Sylius 1.13 has been added, it is now the recommended Sylius version to use. + +1. Support for PHP 8.0 has been dropped. + +1. The following constructor signatures have been changed: + + `Sylius\PayPalPlugin\Client\PayPalClient`: + ```diff + use Psr\Http\Client\ClientInterface; + use GuzzleHttp\ClientInterface as GuzzleClientInterface; + use Psr\Http\Message\RequestFactoryInterface; + use Psr\Http\Message\StreamFactoryInterface; + + public function __construct( + - private readonly GuzzleClientInterface $client, + + private readonly GuzzleClientInterface|ClientInterface $client, + private readonly LoggerInterface $logger, + private readonly UuidProviderInterface $uuidProvider, + private readonly PayPalConfigurationProviderInterface $payPalConfigurationProvider, + private readonly ChannelContextInterface $channelContext, + private readonly string $baseUrl, + private int $requestTrialsLimit, + private readonly bool $loggingLevelIncreased = false, + + private readonly ?RequestFactoryInterface $requestFactory = null, + + private readonly ?StreamFactoryInterface $streamFactory = null, + ) + ``` + + `Sylius\PayPalPlugin\Api\GeneralApi`: + ```diff + use Psr\Http\Client\ClientInterface; + use GuzzleHttp\ClientInterface as GuzzleClientInterface; + use Psr\Http\Message\RequestFactoryInterface; + + public function __construct( + - private readonly GuzzleClientInterface $client, + + private readonly GuzzleClientInterface|ClientInterface $client, + + private readonly ?RequestFactoryInterface $requestFactory = null, + ) + ``` + + `Sylius\PayPalPlugin\Api\WebhookApi`: + ```diff + use Psr\Http\Client\ClientInterface; + use GuzzleHttp\ClientInterface as GuzzleClientInterface; + use Psr\Http\Message\RequestFactoryInterface; + use Psr\Http\Message\StreamFactoryInterface; + + public function __construct( + - private readonly GuzzleClientInterface $client, + + private readonly GuzzleClientInterface|ClientInterface $client, + private readonly string $baseUrl, + + private readonly ?RequestFactoryInterface $requestFactory = null, + + private readonly ?StreamFactoryInterface $streamFactory = null, + ) + ``` + + `Sylius\PayPalPlugin\Onboarding\Processor\BasicOnboardingProcessor`: + ```diff + use Psr\Http\Client\ClientInterface; + use GuzzleHttp\ClientInterface as GuzzleClientInterface; + use Psr\Http\Message\RequestFactoryInterface; + + public function __construct( + - private readonly GuzzleClientInterface $client, + + private readonly GuzzleClientInterface|ClientInterface $client, + private readonly SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + private readonly string $url, + + private readonly ?RequestFactoryInterface $requestFactory = null, + ) + ``` + +1. Added doctrine migration for PostgreSQL. For more information, please refer to the [Sylius 1.13 UPGRADE.md](https://github.com/Sylius/Sylius/blob/1.13/UPGRADE-1.13.md) + ### UPGRADE FROM 1.3.0 to 1.3.1 1. `sylius_paypal_plugin_pay_with_paypal_form` route now operates on both payment ID and order token. URl then changed from diff --git a/composer.json b/composer.json index 23237a66..098857e4 100644 --- a/composer.json +++ b/composer.json @@ -5,13 +5,17 @@ "description": "PayPal plugin for Sylius.", "license": "MIT", "require": { - "php": "^8.0", + "php": "^8.1", "doctrine/doctrine-migrations-bundle": "^3.0", + "php-http/discovery": "^1.17", "phpseclib/phpseclib": "^2.0", - "polishsymfonycommunity/symfony-mocker-container": "^1.0", + "psr/http-client": "^1.0", + "psr/http-client-implementation": "~1.0", + "psr/http-factory-implementation": "~1.0", "sylius-labs/doctrine-migrations-extra-bundle": "^0.1.4 || ^0.2", - "sylius/sylius": "~1.12.0", - "symfony/mailer": "^5.4 || ^6.0" + "sylius/state-machine-abstraction": "~1.13.x-dev", + "sylius/sylius": "~1.12.0 || ~1.13.x-dev", + "symfony/mailer": "^5.4.21 || ^6.4" }, "require-dev": { "behat/behat": "^3.6.1", @@ -27,20 +31,22 @@ "friends-of-behat/symfony-extension": "^2.1", "friends-of-behat/variadic-extension": "^1.3", "lchrusciel/api-test-case": "^5.1", + "nyholm/psr7": "^1.8", "phpspec/phpspec": "^7.0", "phpstan/phpstan": "^1.6", "phpstan/phpstan-doctrine": "1.3.37", "phpstan/phpstan-webmozart-assert": "^1.1", "phpunit/phpunit": "^8.5", + "polishsymfonycommunity/symfony-mocker-container": "^1.0", "sylius-labs/coding-standard": "^4.0", "sylius/sylius-rector": "^1.0", - "symfony/browser-kit": "^5.4 || ^6.0", - "symfony/debug-bundle": "^5.4 || ^6.0", - "symfony/dotenv": "^5.4 || ^6.0", - "symfony/intl": "^5.4 || ^6.0", - "symfony/web-profiler-bundle": "^5.4 || ^6.0", - "symfony/webpack-encore-bundle": "^1.15", - "vimeo/psalm": "4.27.0" + "symfony/browser-kit": "^5.4.21 || ^6.4", + "symfony/debug-bundle": "^5.4.21 || ^6.4", + "symfony/dotenv": "^5.4.21 || ^6.4", + "symfony/http-client": "^5.4.21 || ^6.4", + "symfony/intl": "^5.4.21 || ^6.4", + "symfony/web-profiler-bundle": "^5.4.21 || ^6.4", + "symfony/webpack-encore-bundle": "^1.15" }, "autoload": { "psr-4": { @@ -51,13 +57,17 @@ "autoload-dev": { "classmap": ["tests/Application/Kernel.php"] }, + "conflict": { + "behat/mink-selenium2-driver": ">=1.7.0" + }, "config": { "sort-packages": true, "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": false, "ocramius/package-versions": false, "symfony/flex": true, - "symfony/thanks": false + "symfony/thanks": false, + "php-http/discovery": true } }, "extra": { @@ -68,8 +78,7 @@ "scripts": { "analyse": [ "@composer validate --strict", - "vendor/bin/phpstan.phar analyse", - "vendor/bin/psalm" + "vendor/bin/phpstan.phar analyse" ], "fix": [ "vendor/bin/ecs check src/ spec/ --fix" diff --git a/ecs.php b/ecs.php index 40c669c9..45d4d42d 100644 --- a/ecs.php +++ b/ecs.php @@ -1,13 +1,24 @@ paths([ + 'src', + 'spec', + 'tests/Behat', + 'tests/Functional', + 'tests/Service', + 'tests/Unit', + ]); + $config->import('vendor/sylius-labs/coding-standard/ecs.php'); + $config->ruleWithConfiguration(PhpdocSeparationFixer::class, ['groups' => [['ORM\\*'], ['Given', 'When', 'Then']]]); $config->skip([ VisibilityRequiredFixer::class => ['*Spec.php'], diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 9b4bc47f..8d51856e 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -17,6 +17,7 @@ parameters: - 'src/DependencyInjection/Configuration.php' - 'src/DependencyInjection/SyliusPayPalExtension.php' - 'src/Command/CompletePaidPaymentsCommand.php' + - 'src/Migrations/**.php' # Test dependencies - 'tests/Application/app/**.php' diff --git a/psalm.xml b/psalm.xml deleted file mode 100644 index 5b990dc2..00000000 --- a/psalm.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spec/Api/CacheAuthorizeClientApiSpec.php b/spec/Api/CacheAuthorizeClientApiSpec.php index 9ef7fb4d..2d71607c 100644 --- a/spec/Api/CacheAuthorizeClientApiSpec.php +++ b/spec/Api/CacheAuthorizeClientApiSpec.php @@ -30,13 +30,13 @@ function let( ObjectManager $payPalCredentialsManager, ObjectRepository $payPalCredentialsRepository, AuthorizeClientApiInterface $authorizeClientApi, - UuidProviderInterface $uuidProvider + UuidProviderInterface $uuidProvider, ): void { $this->beConstructedWith( $payPalCredentialsManager, $payPalCredentialsRepository, $authorizeClientApi, - $uuidProvider + $uuidProvider, ); } @@ -48,7 +48,7 @@ function it_implements_cache_authorize_client_api_interface(): void function it_returns_cached_access_token_if_it_is_not_expired( ObjectRepository $payPalCredentialsRepository, PayPalCredentialsInterface $payPalCredentials, - PaymentMethodInterface $paymentMethod + PaymentMethodInterface $paymentMethod, ): void { $payPalCredentialsRepository->findOneBy(['paymentMethod' => $paymentMethod])->willReturn($payPalCredentials); @@ -64,7 +64,7 @@ function it_gets_access_token_from_api_caches_and_returns_it( AuthorizeClientApiInterface $authorizeClientApi, PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, - UuidProviderInterface $uuidProvider + UuidProviderInterface $uuidProvider, ): void { $payPalCredentialsRepository->findOneBy(['paymentMethod' => $paymentMethod])->willReturn(null); @@ -98,7 +98,7 @@ function it_returns_expired_token_and_ask_for_a_new_one( PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, PayPalCredentialsInterface $payPalCredentials, - UuidProviderInterface $uuidProvider + UuidProviderInterface $uuidProvider, ): void { $payPalCredentialsRepository->findOneBy(['paymentMethod' => $paymentMethod])->willReturn($payPalCredentials); $payPalCredentials->isExpired()->willReturn(true); diff --git a/spec/Api/CompleteOrderApiSpec.php b/spec/Api/CompleteOrderApiSpec.php index aa686f88..543f659d 100644 --- a/spec/Api/CompleteOrderApiSpec.php +++ b/spec/Api/CompleteOrderApiSpec.php @@ -34,7 +34,7 @@ function it_implements_complete_order_api_interface(): void function it_completes_pay_pal_order_with_given_id( PayPalClientInterface $client, PaymentInterface $payment, - OrderInterface $order + OrderInterface $order, ): void { $payment->getOrder()->willReturn($order); $payment->getAmount()->willReturn(10000); diff --git a/spec/Api/CreateOrderApiSpec.php b/spec/Api/CreateOrderApiSpec.php index 4474ba67..3e98da12 100644 --- a/spec/Api/CreateOrderApiSpec.php +++ b/spec/Api/CreateOrderApiSpec.php @@ -30,7 +30,7 @@ final class CreateOrderApiSpec extends ObjectBehavior function let( PayPalClientInterface $client, PaymentReferenceNumberProviderInterface $paymentReferenceNumberProvider, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ): void { $this->beConstructedWith($client, $paymentReferenceNumberProvider, $payPalItemDataProvider); } @@ -47,7 +47,7 @@ function it_creates_pay_pal_order_based_on_given_payment( OrderInterface $order, PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ): void { $payment->getOrder()->willReturn($order); $payment->getAmount()->willReturn(10000); @@ -83,7 +83,7 @@ function it_creates_pay_pal_order_based_on_given_payment( $paymentReferenceNumberProvider->provide($payment)->willReturn('REFERENCE-NUMBER'); $gatewayConfig->getConfig()->willReturn( - ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'] + ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'], ); $client->post( @@ -102,7 +102,7 @@ function it_creates_pay_pal_order_based_on_given_payment( $data['purchase_units'][0]['items'][0]['unit_amount']['value'] === '90.00' && $data['purchase_units'][0]['items'][0]['unit_amount']['currency_code'] === 'PLN' ; - }) + }), )->willReturn(['status' => 'CREATED', 'id' => 123]); $this->create('TOKEN', $payment, 'REFERENCE_ID')->shouldReturn(['status' => 'CREATED', 'id' => 123]); @@ -116,7 +116,7 @@ function it_creates_pay_pal_order_with_shipping_address_based_on_given_payment( PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, AddressInterface $shippingAddress, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ): void { $payment->getOrder()->willReturn($order); $payment->getAmount()->willReturn(10000); @@ -158,7 +158,7 @@ function it_creates_pay_pal_order_with_shipping_address_based_on_given_payment( $paymentReferenceNumberProvider->provide($payment)->willReturn('REFERENCE-NUMBER'); $gatewayConfig->getConfig()->willReturn( - ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'] + ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'], ); $client->post( @@ -180,7 +180,7 @@ function it_creates_pay_pal_order_with_shipping_address_based_on_given_payment( $data['purchase_units'][0]['items'][0]['unit_amount']['value'] === '90.00' && $data['purchase_units'][0]['items'][0]['unit_amount']['currency_code'] === 'PLN' ; - }) + }), )->willReturn(['status' => 'CREATED', 'id' => 123]); $this->create('TOKEN', $payment, 'REFERENCE_ID')->shouldReturn(['status' => 'CREATED', 'id' => 123]); @@ -194,7 +194,7 @@ function it_creates_pay_pal_order_with_more_than_one_product( GatewayConfigInterface $gatewayConfig, AddressInterface $shippingAddress, PaymentReferenceNumberProviderInterface $paymentReferenceNumberProvider, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ): void { $payment->getOrder()->willReturn($order); $payment->getAmount()->willReturn(20000); @@ -246,7 +246,7 @@ function it_creates_pay_pal_order_with_more_than_one_product( $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn( - ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'] + ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'], ); $paymentReferenceNumberProvider->provide($payment)->willReturn('REFERENCE-NUMBER'); @@ -273,7 +273,7 @@ function it_creates_pay_pal_order_with_more_than_one_product( $data['purchase_units'][0]['items'][1]['unit_amount']['value'] === '40.00' && $data['purchase_units'][0]['items'][1]['unit_amount']['currency_code'] === 'PLN' ; - }) + }), )->willReturn(['status' => 'CREATED', 'id' => 123]); $this->create('TOKEN', $payment, 'REFERENCE_ID')->shouldReturn(['status' => 'CREATED', 'id' => 123]); @@ -287,7 +287,7 @@ function it_creates_pay_pal_order_with_non_neutral_tax_and_changed_quantity( GatewayConfigInterface $gatewayConfig, AddressInterface $shippingAddress, PaymentReferenceNumberProviderInterface $paymentReferenceNumberProvider, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ): void { $payment->getOrder()->willReturn($order); $payment->getAmount()->willReturn(13000); @@ -339,7 +339,7 @@ function it_creates_pay_pal_order_with_non_neutral_tax_and_changed_quantity( $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn( - ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'] + ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'], ); $paymentReferenceNumberProvider->provide($payment)->willReturn('REFERENCE-NUMBER'); @@ -370,7 +370,7 @@ function it_creates_pay_pal_order_with_non_neutral_tax_and_changed_quantity( $data['purchase_units'][0]['items'][1]['tax']['value'] === '10.00' && $data['purchase_units'][0]['items'][1]['tax']['currency_code'] === 'PLN' ; - }) + }), )->willReturn(['status' => 'CREATED', 'id' => 123]); $this->create('TOKEN', $payment, 'REFERENCE_ID')->shouldReturn(['status' => 'CREATED', 'id' => 123]); @@ -384,7 +384,7 @@ function it_creates_pay_pal_order_with_more_than_one_product_with_different_tax_ GatewayConfigInterface $gatewayConfig, AddressInterface $shippingAddress, PaymentReferenceNumberProviderInterface $paymentReferenceNumberProvider, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ): void { $payment->getOrder()->willReturn($order); $payment->getAmount()->willReturn(20400); @@ -448,7 +448,7 @@ function it_creates_pay_pal_order_with_more_than_one_product_with_different_tax_ $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn( - ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'] + ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'], ); $paymentReferenceNumberProvider->provide($payment)->willReturn('REFERENCE-NUMBER'); @@ -485,7 +485,7 @@ function it_creates_pay_pal_order_with_more_than_one_product_with_different_tax_ $data['purchase_units'][0]['items'][2]['tax']['value'] === '1.00' && $data['purchase_units'][0]['items'][2]['tax']['currency_code'] === 'PLN' ; - }) + }), )->willReturn(['status' => 'CREATED', 'id' => 123]); $this->create('TOKEN', $payment, 'REFERENCE_ID')->shouldReturn(['status' => 'CREATED', 'id' => 123]); @@ -499,7 +499,7 @@ function it_allows_to_create_digital_order( GatewayConfigInterface $gatewayConfig, AddressInterface $shippingAddress, PaymentReferenceNumberProviderInterface $paymentReferenceNumberProvider, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ): void { $payment->getOrder()->willReturn($order); $payment->getAmount()->willReturn(20000); @@ -533,7 +533,7 @@ function it_allows_to_create_digital_order( $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn( - ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'] + ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'], ); $order->setShippingAddress(Argument::any())->shouldNotBeCalled(); @@ -550,7 +550,7 @@ function it_allows_to_create_digital_order( $data['purchase_units'][0]['amount']['currency_code'] === 'PLN' && $data['application_context']['shipping_preference'] === 'NO_SHIPPING' ; - }) + }), )->willReturn(['status' => 'CREATED', 'id' => 123]); $this->create('TOKEN', $payment, 'REFERENCE_ID')->shouldReturn(['status' => 'CREATED', 'id' => 123]); @@ -563,7 +563,7 @@ function it_creates_pay_pal_order_with_promotion( OrderInterface $order, PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ): void { $payment->getOrder()->willReturn($order); $payment->getAmount()->willReturn(2999); @@ -599,7 +599,7 @@ function it_creates_pay_pal_order_with_promotion( $paymentReferenceNumberProvider->provide($payment)->willReturn('REFERENCE-NUMBER'); $gatewayConfig->getConfig()->willReturn( - ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'] + ['merchant_id' => 'merchant-id', 'sylius_merchant_id' => 'sylius-merchant-id'], ); $client->post( @@ -621,8 +621,8 @@ function it_creates_pay_pal_order_with_promotion( $data['purchase_units'][0]['items'][0]['quantity'] === 1 && $data['purchase_units'][0]['items'][0]['unit_amount']['value'] === '25.00' && $data['purchase_units'][0]['items'][0]['unit_amount']['currency_code'] === 'PLN' - ; - }) + ; + }), )->willReturn(['status' => 'CREATED', 'id' => 123]); $this->create('TOKEN', $payment, 'REFERENCE_ID')->shouldReturn(['status' => 'CREATED', 'id' => 123]); diff --git a/spec/Api/GenericApiSpec.php b/spec/Api/GenericApiSpec.php index e4002914..105039ca 100644 --- a/spec/Api/GenericApiSpec.php +++ b/spec/Api/GenericApiSpec.php @@ -13,17 +13,20 @@ namespace spec\Sylius\PayPalPlugin\Api; -use GuzzleHttp\ClientInterface; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; use PhpSpec\ObjectBehavior; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use Sylius\PayPalPlugin\Api\GenericApiInterface; final class GenericApiSpec extends ObjectBehavior { - function let(ClientInterface $client): void + function let(ClientInterface $client, RequestFactoryInterface $requestFactory): void { - $this->beConstructedWith($client); + $this->beConstructedWith($client, $requestFactory); } function it_implements_generic_api_interface(): void @@ -33,9 +36,31 @@ function it_implements_generic_api_interface(): void function it_calls_api_by_url( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, + ResponseInterface $response, + StreamInterface $body, + ): void { + $requestFactory->createRequest('GET', 'http://url.com/')->willReturn($request); + + $request->withHeader('Authorization', 'Bearer TOKEN')->willReturn($request); + $request->withHeader('Content-Type', 'application/json')->willReturn($request); + $request->withHeader('Accept', 'application/json')->willReturn($request); + + $client->sendRequest($request)->willReturn($response); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{ "parameter": "VALUE" }'); + + $this->get('TOKEN', 'http://url.com/')->shouldReturn(['parameter' => 'VALUE']); + } + + function it_calls_api_by_url_using_guzzle_client( + GuzzleClientInterface $client, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { + $this->beConstructedWith($client); + $client->request('GET', 'http://url.com/', [ 'headers' => [ 'Authorization' => 'Bearer TOKEN', @@ -43,7 +68,6 @@ function it_calls_api_by_url( 'Accept' => 'application/json', ], ])->willReturn($response); - $response->getBody()->willReturn($body); $body->getContents()->willReturn('{ "parameter": "VALUE" }'); diff --git a/spec/Api/RefundPaymentApiSpec.php b/spec/Api/RefundPaymentApiSpec.php index fe476144..cc7e2581 100644 --- a/spec/Api/RefundPaymentApiSpec.php +++ b/spec/Api/RefundPaymentApiSpec.php @@ -36,7 +36,7 @@ function it_refunds_pay_pal_payment_with_given_id(PayPalClientInterface $client) 'v2/payments/captures/123123/refund', 'TOKEN', ['amount' => ['value' => '10.99', 'currency_code' => 'USD'], 'invoice_number' => '123-11-11-2010'], - ['PayPal-Auth-Assertion' => 'PAY-PAL-AUTH-ASSERTION'] + ['PayPal-Auth-Assertion' => 'PAY-PAL-AUTH-ASSERTION'], ) ->willReturn(['status' => 'COMPLETED', 'id' => '123123']) ; diff --git a/spec/Api/UpdateOrderApiSpec.php b/spec/Api/UpdateOrderApiSpec.php index c4fb767d..3a99725f 100644 --- a/spec/Api/UpdateOrderApiSpec.php +++ b/spec/Api/UpdateOrderApiSpec.php @@ -28,7 +28,7 @@ final class UpdateOrderApiSpec extends ObjectBehavior function let( PayPalClientInterface $client, PaymentReferenceNumberProviderInterface $paymentReferenceNumberProvider, - PayPalItemDataProviderInterface $payPalItemsDataProvider + PayPalItemDataProviderInterface $payPalItemsDataProvider, ): void { $this->beConstructedWith($client, $paymentReferenceNumberProvider, $payPalItemsDataProvider); } @@ -44,7 +44,7 @@ function it_updates_pay_pal_order_with_given_new_total( PayPalItemDataProviderInterface $payPalItemsDataProvider, PaymentInterface $payment, OrderInterface $order, - AddressInterface $shippingAddress + AddressInterface $shippingAddress, ): void { $payment->getOrder()->willReturn($order); $order->getShippingAddress()->willReturn($shippingAddress); @@ -92,7 +92,7 @@ function it_updates_pay_pal_order_with_given_new_total( $data[0]['value']['shipping']['address']['country_code'] === 'US' && $data[0]['value']['items'] === ['data'] ; - }) + }), )->shouldBeCalled(); $this->update('TOKEN', 'ORDER-ID', $payment, 'REFERENCE-ID', 'MERCHANT-ID'); @@ -104,7 +104,7 @@ function it_updates_digital_order( PayPalItemDataProviderInterface $payPalItemsDataProvider, PaymentInterface $payment, OrderInterface $order, - AddressInterface $shippingAddress + AddressInterface $shippingAddress, ): void { $payment->getOrder()->willReturn($order); $order->getShippingAddress()->willReturn($shippingAddress); @@ -141,7 +141,7 @@ function it_updates_digital_order( $data[0]['value']['payee']['merchant_id'] === 'MERCHANT-ID' && $data[0]['value']['items'] === ['data'] ; - }) + }), )->shouldBeCalled(); $this->update('TOKEN', 'ORDER-ID', $payment, 'REFERENCE-ID', 'MERCHANT-ID'); diff --git a/spec/Api/WebhookApiSpec.php b/spec/Api/WebhookApiSpec.php index bb6165e5..15d12876 100644 --- a/spec/Api/WebhookApiSpec.php +++ b/spec/Api/WebhookApiSpec.php @@ -4,23 +4,56 @@ namespace spec\Sylius\PayPalPlugin\Api; -use GuzzleHttp\ClientInterface; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; use PhpSpec\ObjectBehavior; +use Prophecy\Argument; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; final class WebhookApiSpec extends ObjectBehavior { - function let(ClientInterface $client): void - { - $this->beConstructedWith($client, 'http://base-url.com/'); + function let( + ClientInterface $client, + RequestFactoryInterface $requestFactory, + StreamFactoryInterface $streamFactory, + StreamInterface $stream, + RequestInterface $request, + ): void { + $this->beConstructedWith($client, 'http://base-url.com/', $requestFactory, $streamFactory); + $request->withHeader(Argument::any(), Argument::any())->willReturn($request); + $request->withBody(Argument::any())->willReturn($request); + $streamFactory->createStream(Argument::any())->willReturn($stream); } function it_registers_webhook( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { + $requestFactory + ->createRequest('POST', 'http://base-url.com/v1/notifications/webhooks') + ->willReturn($request); + $client->sendRequest($request)->willReturn($response); + + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{ "status": "CREATED" }'); + + $this->register('TOKEN', 'https://webhook.com')->shouldReturn(['status' => 'CREATED']); + } + + function it_registers_webhook_using_guzzle_client( + GuzzleClientInterface $client, + ResponseInterface $response, + StreamInterface $body, + ): void { + $this->beConstructedWith($client, 'http://base-url.com/'); + $client->request( 'POST', 'http://base-url.com/v1/notifications/webhooks', @@ -36,7 +69,7 @@ function it_registers_webhook( ['name' => 'PAYMENT.CAPTURE.REFUNDED'], ], ], - ] + ], )->willReturn($response); $response->getBody()->willReturn($body); $body->getContents()->willReturn('{ "status": "CREATED" }'); @@ -46,9 +79,28 @@ function it_registers_webhook( function it_registers_webhook_without_https( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, + ResponseInterface $response, + StreamInterface $body, + ): void { + $requestFactory->createRequest('POST', 'http://base-url.com/v1/notifications/webhooks') + ->willReturn($request); + $client->sendRequest($request)->willReturn($response); + + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{ "status": "CREATED" }'); + + $this->register('TOKEN', 'http://webhook.com')->shouldReturn(['status' => 'CREATED']); + } + + function it_registers_webhook_without_https_using_guzzle_client( + GuzzleClientInterface $client, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { + $this->beConstructedWith($client, 'http://base-url.com/'); + $client->request( 'POST', 'http://base-url.com/v1/notifications/webhooks', @@ -64,7 +116,7 @@ function it_registers_webhook_without_https( ['name' => 'PAYMENT.CAPTURE.REFUNDED'], ], ], - ] + ], )->willReturn($response); $response->getBody()->willReturn($body); $body->getContents()->willReturn('{ "status": "CREATED" }'); diff --git a/spec/ApiPlatform/PayPalPaymentSpec.php b/spec/ApiPlatform/PayPalPaymentSpec.php index 6aaf6ce7..4e3fef27 100644 --- a/spec/ApiPlatform/PayPalPaymentSpec.php +++ b/spec/ApiPlatform/PayPalPaymentSpec.php @@ -31,7 +31,7 @@ function let(RouterInterface $router, AvailableCountriesProviderInterface $avail function it_supports_paypal_payment_method( PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -46,7 +46,7 @@ function it_provides_proper_paypal_configuration( OrderInterface $order, GatewayConfigInterface $gatewayConfig, AvailableCountriesProviderInterface $availableCountriesProvider, - RouterInterface $router + RouterInterface $router, ): void { $payment->getMethod()->willReturn($paymentMethod); @@ -55,7 +55,7 @@ function it_provides_proper_paypal_configuration( [ 'client_id' => 'CLIENT-ID', 'partner_attribution_id' => 'PARTNER-ATTRIBUTION-ID', - ] + ], ); $payment->getOrder()->willReturn($order); @@ -70,25 +70,25 @@ function it_provides_proper_paypal_configuration( $router->generate( 'sylius_paypal_plugin_complete_paypal_order', ['token' => 'TOKEN'], - UrlGeneratorInterface::ABSOLUTE_URL + UrlGeneratorInterface::ABSOLUTE_URL, )->willReturn('https://path-to-complete/TOKEN'); $router->generate( 'sylius_paypal_plugin_create_paypal_order', ['token' => 'TOKEN'], - UrlGeneratorInterface::ABSOLUTE_URL + UrlGeneratorInterface::ABSOLUTE_URL, )->willReturn('https://path-to-create/TOKEN'); $router->generate( 'sylius_paypal_plugin_cancel_payment', [], - UrlGeneratorInterface::ABSOLUTE_URL + UrlGeneratorInterface::ABSOLUTE_URL, )->willReturn('https://path-to-cancel'); $router->generate( 'sylius_paypal_plugin_payment_error', [], - UrlGeneratorInterface::ABSOLUTE_URL + UrlGeneratorInterface::ABSOLUTE_URL, )->willReturn('https://path-to-error'); $this->provideConfiguration($payment)->shouldReturn( @@ -104,7 +104,7 @@ function it_provides_proper_paypal_configuration( 'orderToken' => 'TOKEN', 'errorPayPalPaymentUrl' => 'https://path-to-error', 'available_countries' => ['PL', 'US'], - ] + ], ); } } diff --git a/spec/Client/PayPalClientSpec.php b/spec/Client/PayPalClientSpec.php index 64f3e1df..1efd41b0 100644 --- a/spec/Client/PayPalClientSpec.php +++ b/spec/Client/PayPalClientSpec.php @@ -13,11 +13,16 @@ namespace spec\Sylius\PayPalPlugin\Client; -use GuzzleHttp\ClientInterface; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; use PhpSpec\ObjectBehavior; +use Prophecy\Argument; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Psr\Log\LoggerInterface; use Sylius\Component\Channel\Context\ChannelContextInterface; @@ -36,9 +41,16 @@ function let( UuidProviderInterface $uuidProvider, PayPalConfigurationProviderInterface $payPalConfigurationProvider, ChannelContextInterface $channelContext, - ChannelInterface $channel + ChannelInterface $channel, + RequestFactoryInterface $requestFactory, + StreamFactoryInterface $streamFactory, + RequestInterface $request, + StreamInterface $stream, ): void { $channelContext->getChannel()->willReturn($channel); + $streamFactory->createStream(Argument::any())->willReturn($stream); + $request->withHeader(Argument::any(), Argument::any())->willReturn($request); + $request->withBody(Argument::any())->willReturn($request); $this->beConstructedWith( $client, @@ -47,7 +59,10 @@ function let( $payPalConfigurationProvider, $channelContext, 'https://test-api.paypal.com/', - 5 + 5, + false, + $requestFactory, + $streamFactory, ); } @@ -58,16 +73,49 @@ function it_implements_pay_pal_client_interface(): void function it_returns_auth_token_for_given_client_data( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { + $requestFactory->createRequest('POST', 'https://test-api.paypal.com/v1/oauth2/token')->willReturn($request); + $request->withHeader(Argument::any(), Argument::any())->willReturn($request); + $request->withBody(Argument::any())->willReturn($request); + $client->sendRequest($request)->willReturn($response); + $response->getStatusCode()->willReturn(200); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{"access_token": "TOKEN"}'); + + $this->authorize('CLIENT_ID', 'CLIENT_SECRET')->shouldReturn(['access_token' => 'TOKEN']); + } + + function it_returns_auth_token_for_given_client_data_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + ResponseInterface $response, + StreamInterface $body, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + $client->request( 'POST', 'https://test-api.paypal.com/v1/oauth2/token', [ 'auth' => ['CLIENT_ID', 'CLIENT_SECRET'], 'form_params' => ['grant_type' => 'client_credentials'], - ] + ], )->willReturn($response); $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($body); @@ -78,15 +126,47 @@ function it_returns_auth_token_for_given_client_data( function it_throws_an_exception_if_client_could_not_be_authorized( ClientInterface $client, - ResponseInterface $response + RequestFactoryInterface $requestFactory, + RequestInterface $request, + ResponseInterface $response, + ): void { + $requestFactory->createRequest('POST', 'https://test-api.paypal.com/v1/oauth2/token')->willReturn($request); + $client->sendRequest($request)->willReturn($response); + + $response->getStatusCode()->willReturn(401); + + $this + ->shouldThrow(PayPalAuthorizationException::class) + ->during('authorize', ['CLIENT_ID', 'CLIENT_SECRET']) + ; + } + + function it_throws_an_exception_if_client_could_not_be_authorized_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + ResponseInterface $response, ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + $client->request( 'POST', 'https://test-api.paypal.com/v1/oauth2/token', [ 'auth' => ['CLIENT_ID', 'CLIENT_SECRET'], 'form_params' => ['grant_type' => 'client_credentials'], - ] + ], )->willReturn($response); $response->getStatusCode()->willReturn(401); @@ -98,13 +178,48 @@ function it_throws_an_exception_if_client_could_not_be_authorized( function it_calls_get_request_on_paypal_api( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, PayPalConfigurationProviderInterface $payPalConfigurationProvider, ChannelInterface $channel, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $requestFactory->createRequest('GET', 'https://test-api.paypal.com/v2/get-request/')->willReturn($request); + $client->sendRequest($request)->willReturn($response); + + $response->getStatusCode()->willReturn(200); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{"status": "OK", "id": "123123"}'); + + $this->get('v2/get-request/', 'TOKEN')->shouldReturn(['status' => 'OK', 'id' => '123123']); + } + + function it_calls_get_request_on_paypal_api_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + ChannelInterface $channel, + ResponseInterface $response, + StreamInterface $body, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $client->request( 'GET', 'https://test-api.paypal.com/v2/get-request/', @@ -115,7 +230,7 @@ function it_calls_get_request_on_paypal_api( 'Accept' => 'application/json', 'PayPal-Partner-Attribution-Id' => 'TRACKING-ID', ], - ] + ], )->willReturn($response); $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($body); @@ -126,13 +241,16 @@ function it_calls_get_request_on_paypal_api( function it_logs_all_requests_if_logging_level_is_increased( ClientInterface $client, + RequestFactoryInterface $requestFactory, + StreamFactoryInterface $streamFactory, + RequestInterface $request, LoggerInterface $logger, UuidProviderInterface $uuidProvider, PayPalConfigurationProviderInterface $payPalConfigurationProvider, ChannelContextInterface $channelContext, ChannelInterface $channel, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { $this->beConstructedWith( $client, @@ -142,7 +260,48 @@ function it_logs_all_requests_if_logging_level_is_increased( $channelContext, 'https://test-api.paypal.com/', 5, - true + true, + $requestFactory, + $streamFactory, + ); + + $channelContext->getChannel()->willReturn($channel); + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + + $requestFactory->createRequest('GET', 'https://test-api.paypal.com/v2/get-request/')->willReturn($request); + $client->sendRequest($request)->willReturn($response); + + $response->getStatusCode()->willReturn(200); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{"status": "OK", "id": "123123"}'); + + $logger + ->debug('GET request to "https://test-api.paypal.com/v2/get-request/" called successfully') + ->shouldBeCalled() + ; + + $this->get('v2/get-request/', 'TOKEN')->shouldReturn(['status' => 'OK', 'id' => '123123']); + } + + function it_logs_all_requests_if_logging_level_is_increased_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + ChannelInterface $channel, + ResponseInterface $response, + StreamInterface $body, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + true, ); $channelContext->getChannel()->willReturn($channel); @@ -158,8 +317,9 @@ function it_logs_all_requests_if_logging_level_is_increased( 'Accept' => 'application/json', 'PayPal-Partner-Attribution-Id' => 'TRACKING-ID', ], - ] + ], )->willReturn($response); + $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($body); $body->getContents()->willReturn('{"status": "OK", "id": "123123"}'); @@ -174,15 +334,57 @@ function it_logs_all_requests_if_logging_level_is_increased( function it_logs_debug_id_from_failed_get_request( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, LoggerInterface $logger, PayPalConfigurationProviderInterface $payPalConfigurationProvider, ChannelInterface $channel, RequestException $exception, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $requestFactory->createRequest('GET', 'https://test-api.paypal.com/v2/get-request/')->willReturn($request); + $client->sendRequest($request)->willThrow($exception->getWrappedObject()); + + $exception->getResponse()->willReturn($response); + $response->getBody()->willReturn($body); + $response->getStatusCode()->willReturn(400); + $body->getContents()->willReturn('{"status": "FAILED", "debug_id": "123123"}'); + + $logger + ->error('GET request to "https://test-api.paypal.com/v2/get-request/" failed with debug ID 123123') + ->shouldBeCalled() + ; + + $this->get('v2/get-request/', 'TOKEN')->shouldReturn(['status' => 'FAILED', 'debug_id' => '123123']); + } + + function it_logs_debug_id_from_failed_get_request_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + ChannelInterface $channel, + RequestException $exception, + ResponseInterface $response, + StreamInterface $body, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $client->request( 'GET', 'https://test-api.paypal.com/v2/get-request/', @@ -193,7 +395,7 @@ function it_logs_debug_id_from_failed_get_request( 'Accept' => 'application/json', 'PayPal-Partner-Attribution-Id' => 'TRACKING-ID', ], - ] + ], )->willThrow($exception->getWrappedObject()); $exception->getResponse()->willReturn($response); @@ -211,15 +413,54 @@ function it_logs_debug_id_from_failed_get_request( function it_calls_post_request_on_paypal_api( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, ResponseInterface $response, StreamInterface $body, UuidProviderInterface $uuidProvider, PayPalConfigurationProviderInterface $payPalConfigurationProvider, - ChannelInterface $channel + ChannelInterface $channel, ): void { $uuidProvider->provide()->willReturn('REQUEST-ID'); $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $requestFactory->createRequest('POST', 'https://test-api.paypal.com/v2/post-request/')->willReturn($request); + $client->sendRequest($request)->willReturn($response); + + $response->getStatusCode()->willReturn(200); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{"status": "OK", "id": "123123"}'); + + $this + ->post('v2/post-request/', 'TOKEN', ['parameter' => 'value', 'another_parameter' => 'another_value']) + ->shouldReturn(['status' => 'OK', 'id' => '123123']) + ; + } + + function it_calls_post_request_on_paypal_api_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + ResponseInterface $response, + StreamInterface $body, + ChannelInterface $channel, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + + $uuidProvider->provide()->willReturn('REQUEST-ID'); + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $client->request( 'POST', 'https://test-api.paypal.com/v2/post-request/', @@ -232,8 +473,9 @@ function it_calls_post_request_on_paypal_api( 'PayPal-Request-Id' => 'REQUEST-ID', ], 'json' => ['parameter' => 'value', 'another_parameter' => 'another_value'], - ] + ], )->willReturn($response); + $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($body); $body->getContents()->willReturn('{"status": "OK", "id": "123123"}'); @@ -246,15 +488,58 @@ function it_calls_post_request_on_paypal_api( function it_calls_post_request_on_paypal_api_with_extra_headers( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, ResponseInterface $response, + StreamFactoryInterface $streamFactory, StreamInterface $body, UuidProviderInterface $uuidProvider, PayPalConfigurationProviderInterface $payPalConfigurationProvider, - ChannelInterface $channel + ChannelInterface $channel, ): void { $uuidProvider->provide()->willReturn('REQUEST-ID'); $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $requestFactory->createRequest('POST', 'https://test-api.paypal.com/v2/post-request/')->willReturn($request); + $client->sendRequest($request)->willReturn($response); + + $response->getStatusCode()->willReturn(200); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{"status": "OK", "id": "123123"}'); + + $this + ->post('v2/post-request/', 'TOKEN', ['parameter' => 'value', 'another_parameter' => 'another_value'], ['CUSTOM_HEADER' => 'header']) + ->shouldReturn(['status' => 'OK', 'id' => '123123']) + ; + + $request->withHeader('CUSTOM_HEADER', 'header')->shouldBeCalled(); + $streamFactory->createStream(json_encode(['parameter' => 'value', 'another_parameter' => 'another_value']))->shouldBeCalled(); + } + + function it_calls_post_request_on_paypal_api_with_extra_headers_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + ResponseInterface $response, + StreamInterface $body, + ChannelInterface $channel, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + + $uuidProvider->provide()->willReturn('REQUEST-ID'); + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $client->request( 'POST', 'https://test-api.paypal.com/v2/post-request/', @@ -268,8 +553,9 @@ function it_calls_post_request_on_paypal_api_with_extra_headers( 'CUSTOM_HEADER' => 'header', ], 'json' => ['parameter' => 'value', 'another_parameter' => 'another_value'], - ] + ], )->willReturn($response); + $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($body); $body->getContents()->willReturn('{"status": "OK", "id": "123123"}'); @@ -282,17 +568,63 @@ function it_calls_post_request_on_paypal_api_with_extra_headers( function it_logs_debug_id_from_failed_post_request( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, LoggerInterface $logger, RequestException $exception, ResponseInterface $response, StreamInterface $body, UuidProviderInterface $uuidProvider, PayPalConfigurationProviderInterface $payPalConfigurationProvider, - ChannelInterface $channel + ChannelInterface $channel, ): void { $uuidProvider->provide()->willReturn('REQUEST-ID'); $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $requestFactory->createRequest('POST', 'https://test-api.paypal.com/v2/post-request/')->willReturn($request); + $client->sendRequest($request)->willThrow($exception->getWrappedObject()); + + $exception->getResponse()->willReturn($response); + $response->getBody()->willReturn($body); + $response->getStatusCode()->willReturn(400); + $body->getContents()->willReturn('{"status": "FAILED", "debug_id": "123123"}'); + + $logger + ->error('POST request to "https://test-api.paypal.com/v2/post-request/" failed with debug ID 123123') + ->shouldBeCalled() + ; + + $this + ->post('v2/post-request/', 'TOKEN', ['parameter' => 'value', 'another_parameter' => 'another_value']) + ->shouldReturn(['status' => 'FAILED', 'debug_id' => '123123']) + ; + } + + function it_logs_debug_id_from_failed_post_request_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + RequestException $exception, + ResponseInterface $response, + StreamInterface $body, + ChannelInterface $channel, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + + $uuidProvider->provide()->willReturn('REQUEST-ID'); + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $client->request( 'POST', 'https://test-api.paypal.com/v2/post-request/', @@ -305,7 +637,7 @@ function it_logs_debug_id_from_failed_post_request( 'PayPal-Request-Id' => 'REQUEST-ID', ], 'json' => ['parameter' => 'value', 'another_parameter' => 'another_value'], - ] + ], )->willThrow($exception->getWrappedObject()); $exception->getResponse()->willReturn($response); @@ -326,13 +658,48 @@ function it_logs_debug_id_from_failed_post_request( function it_calls_patch_request_on_paypal_api( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, ResponseInterface $response, StreamInterface $body, PayPalConfigurationProviderInterface $payPalConfigurationProvider, - ChannelInterface $channel + ChannelInterface $channel, ): void { $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $requestFactory->createRequest('PATCH', 'https://test-api.paypal.com/v2/patch-request/123123')->willReturn($request); + $client->sendRequest($request)->willReturn($response); + $response->getStatusCode()->willReturn(200); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{"status": "OK", "id": "123123"}'); + + $this + ->patch('v2/patch-request/123123', 'TOKEN', ['parameter' => 'value', 'another_parameter' => 'another_value']) + ->shouldReturn(['status' => 'OK', 'id' => '123123']) + ; + } + + function it_calls_patch_request_on_paypal_api_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + ResponseInterface $response, + StreamInterface $body, + ChannelInterface $channel, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); $client->request( 'PATCH', 'https://test-api.paypal.com/v2/patch-request/123123', @@ -344,7 +711,7 @@ function it_calls_patch_request_on_paypal_api( 'PayPal-Partner-Attribution-Id' => 'TRACKING-ID', ], 'json' => ['parameter' => 'value', 'another_parameter' => 'another_value'], - ] + ], )->willReturn($response); $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($body); @@ -358,15 +725,60 @@ function it_calls_patch_request_on_paypal_api( function it_logs_debug_id_from_failed_patch_request( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, LoggerInterface $logger, RequestException $exception, ResponseInterface $response, StreamInterface $body, PayPalConfigurationProviderInterface $payPalConfigurationProvider, - ChannelInterface $channel + ChannelInterface $channel, ): void { $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $requestFactory->createRequest('PATCH', 'https://test-api.paypal.com/v2/patch-request/123123')->willReturn($request); + $client->sendRequest($request)->willThrow($exception->getWrappedObject()); + + $exception->getResponse()->willReturn($response); + $response->getBody()->willReturn($body); + $response->getStatusCode()->willReturn(400); + $body->getContents()->willReturn('{"status": "FAILED", "debug_id": "123123"}'); + + $logger + ->error('PATCH request to "https://test-api.paypal.com/v2/patch-request/123123" failed with debug ID 123123') + ->shouldBeCalled() + ; + + $this + ->patch('v2/patch-request/123123', 'TOKEN', ['parameter' => 'value', 'another_parameter' => 'another_value']) + ->shouldReturn(['status' => 'FAILED', 'debug_id' => '123123']) + ; + } + + function it_logs_debug_id_from_failed_patch_request_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelContextInterface $channelContext, + RequestException $exception, + ResponseInterface $response, + StreamInterface $body, + ChannelInterface $channel, + ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + $client->request( 'PATCH', 'https://test-api.paypal.com/v2/patch-request/123123', @@ -378,7 +790,7 @@ function it_logs_debug_id_from_failed_patch_request( 'PayPal-Partner-Attribution-Id' => 'TRACKING-ID', ], 'json' => ['parameter' => 'value', 'another_parameter' => 'another_value'], - ] + ], )->willThrow($exception->getWrappedObject()); $exception->getResponse()->willReturn($response); @@ -399,9 +811,41 @@ function it_logs_debug_id_from_failed_patch_request( function it_throws_exception_if_the_timeout_has_been_reached_the_specified_amount_of_time( ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, + PayPalConfigurationProviderInterface $payPalConfigurationProvider, + ChannelInterface $channel, + ): void { + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); + + $requestFactory->createRequest('GET', 'https://test-api.paypal.com/v2/get-request/')->willReturn($request); + $client->sendRequest($request)->willThrow(ConnectException::class); + + $this + ->shouldThrow(PayPalApiTimeoutException::class) + ->during('get', ['v2/get-request/', 'TOKEN']) + ; + } + + function it_throws_exception_if_the_timeout_has_been_reached_the_specified_amount_of_time_using_guzzle_client( + GuzzleClientInterface $client, + LoggerInterface $logger, + UuidProviderInterface $uuidProvider, PayPalConfigurationProviderInterface $payPalConfigurationProvider, - ChannelInterface $channel + ChannelContextInterface $channelContext, + ChannelInterface $channel, ): void { + $this->beConstructedWith( + $client, + $logger, + $uuidProvider, + $payPalConfigurationProvider, + $channelContext, + 'https://test-api.paypal.com/', + 5, + false, + ); + $payPalConfigurationProvider->getPartnerAttributionId($channel)->willReturn('TRACKING-ID'); $client->request( @@ -414,7 +858,7 @@ function it_throws_exception_if_the_timeout_has_been_reached_the_specified_amoun 'Accept' => 'application/json', 'PayPal-Partner-Attribution-Id' => 'TRACKING-ID', ], - ] + ], )->willThrow(ConnectException::class); $this diff --git a/spec/Downloader/SftpPayoutsReportDownloaderSpec.php b/spec/Downloader/SftpPayoutsReportDownloaderSpec.php index de4cd8b6..2d21fe1b 100644 --- a/spec/Downloader/SftpPayoutsReportDownloaderSpec.php +++ b/spec/Downloader/SftpPayoutsReportDownloaderSpec.php @@ -36,7 +36,7 @@ function it_implements_payouts_report_downloader_interface(): void function it_returns_content_of_the_latest_pyt_report_from_pay_pal_sftp_server( SFTP $sftp, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn( @@ -44,7 +44,7 @@ function it_returns_content_of_the_latest_pyt_report_from_pay_pal_sftp_server( 'partner_attribution_id' => 'PARTNER-ID', 'reports_sftp_username' => 'SFTP-USERNAME', 'reports_sftp_password' => 'SFTP-PASSWORD', - ] + ], ); $sftp->login('SFTP-USERNAME', 'SFTP-PASSWORD')->willReturn(true); @@ -64,7 +64,7 @@ function it_returns_content_of_the_latest_pyt_report_from_pay_pal_sftp_server( function it_throws_an_exception_if_payment_method_has_no_partner_attribution_id( SFTP $sftp, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn([]); @@ -78,7 +78,7 @@ function it_throws_an_exception_if_payment_method_has_no_partner_attribution_id( function it_throws_an_exception_if_credentials_are_invalid( SFTP $sftp, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn( @@ -86,7 +86,7 @@ function it_throws_an_exception_if_credentials_are_invalid( 'partner_attribution_id' => 'PARTNER-ID', 'reports_sftp_username' => 'SFTP-USERNAME', 'reports_sftp_password' => 'SFTP-PASSWORD', - ] + ], ); $sftp->login('SFTP-USERNAME', 'SFTP-PASSWORD')->willReturn(false); @@ -100,7 +100,7 @@ function it_throws_an_exception_if_credentials_are_invalid( function it_throws_an_exception_if_there_is_no_report_with_given_name( SFTP $sftp, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn( @@ -108,7 +108,7 @@ function it_throws_an_exception_if_there_is_no_report_with_given_name( 'partner_attribution_id' => 'PARTNER-ID', 'reports_sftp_username' => 'SFTP-USERNAME', 'reports_sftp_password' => 'SFTP-PASSWORD', - ] + ], ); $sftp->login('SFTP-USERNAME', 'SFTP-PASSWORD')->willReturn(true); diff --git a/spec/Enabler/PayPalPaymentMethodEnablerSpec.php b/spec/Enabler/PayPalPaymentMethodEnablerSpec.php index 10e29401..7fa66bf1 100644 --- a/spec/Enabler/PayPalPaymentMethodEnablerSpec.php +++ b/spec/Enabler/PayPalPaymentMethodEnablerSpec.php @@ -14,9 +14,12 @@ namespace spec\Sylius\PayPalPlugin\Enabler; use Doctrine\Persistence\ObjectManager; -use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; use Payum\Core\Model\GatewayConfigInterface; use PhpSpec\ObjectBehavior; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use Sylius\Component\Core\Model\PaymentMethodInterface; @@ -27,12 +30,17 @@ final class PayPalPaymentMethodEnablerSpec extends ObjectBehavior { function let( - Client $client, + ClientInterface $client, + RequestFactoryInterface $requestFactory, ObjectManager $paymentMethodManager, - SellerWebhookRegistrarInterface $sellerWebhookRegistrar + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, ): void { $this->beConstructedWith( - $client, 'http://base-url.com', $paymentMethodManager, $sellerWebhookRegistrar + $client, + 'http://base-url.com', + $paymentMethodManager, + $sellerWebhookRegistrar, + $requestFactory, ); } @@ -42,17 +50,53 @@ function it_implements_payment_method_enabler_interface(): void } function it_enables_payment_method_if_it_has_proper_credentials_and_webhook_are_set( - Client $client, + ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, ObjectManager $paymentMethodManager, SellerWebhookRegistrarInterface $sellerWebhookRegistrar, PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn(['merchant_id' => '123123', 'client_id' => 'CLIENT-ID', 'client_secret' => 'SECRET']); + $requestFactory + ->createRequest('GET', 'http://base-url.com/seller-permissions/check/123123') + ->willReturn($request); + $client->sendRequest($request)->willReturn($response); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{ "permissionsGranted": true }'); + + $sellerWebhookRegistrar->register($paymentMethod)->shouldBeCalled(); + + $paymentMethod->setEnabled(true)->shouldBeCalled(); + $paymentMethodManager->flush()->shouldBeCalled(); + + $this->enable($paymentMethod); + } + + function it_enables_payment_method_if_it_has_proper_credentials_and_webhook_are_set_using_guzzle_client( + GuzzleClientInterface $client, + ObjectManager $paymentMethodManager, + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + PaymentMethodInterface $paymentMethod, + GatewayConfigInterface $gatewayConfig, + ResponseInterface $response, + StreamInterface $body, + ): void { + $this->beConstructedWith( + $client, + 'http://base-url.com', + $paymentMethodManager, + $sellerWebhookRegistrar, + ); + + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); + $gatewayConfig->getConfig()->willReturn(['merchant_id' => '123123', 'client_id' => 'CLIENT-ID', 'client_secret' => 'SECRET']); + $client->request('GET', 'http://base-url.com/seller-permissions/check/123123')->willReturn($response); $response->getBody()->willReturn($body); $body->getContents()->willReturn('{ "permissionsGranted": true }'); @@ -66,17 +110,57 @@ function it_enables_payment_method_if_it_has_proper_credentials_and_webhook_are_ } function it_throws_exception_if_payment_method_credentials_are_not_granted( - Client $client, + ClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, ObjectManager $paymentMethodManager, SellerWebhookRegistrarInterface $sellerWebhookRegistrar, PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, ResponseInterface $response, - StreamInterface $body + StreamInterface $body, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn(['merchant_id' => '123123', 'client_id' => 'CLIENT-ID', 'client_secret' => 'SECRET']); + $requestFactory + ->createRequest('GET', 'http://base-url.com/seller-permissions/check/123123') + ->willReturn($request); + $client->sendRequest($request)->willReturn($response); + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{ "permissionsGranted": false }'); + + $sellerWebhookRegistrar->register($paymentMethod)->shouldNotBeCalled(); + $paymentMethod->setEnabled(true)->shouldNotBeCalled(); + $paymentMethodManager->flush()->shouldNotBeCalled(); + + $this + ->shouldThrow(PaymentMethodCouldNotBeEnabledException::class) + ->during('enable', [$paymentMethod]) + ; + } + + function it_throws_exception_if_payment_method_credentials_are_not_granted_using_guzzle_client( + GuzzleClientInterface $client, + RequestFactoryInterface $requestFactory, + RequestInterface $request, + ObjectManager $paymentMethodManager, + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + PaymentMethodInterface $paymentMethod, + GatewayConfigInterface $gatewayConfig, + ResponseInterface $response, + StreamInterface $body, + ): void { + $this->beConstructedWith( + $client, + 'http://base-url.com', + $paymentMethodManager, + $sellerWebhookRegistrar, + ); + + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); + $gatewayConfig->getConfig()->willReturn(['merchant_id' => '123123', 'client_id' => 'CLIENT-ID', 'client_secret' => 'SECRET']); + $client->request('GET', 'http://base-url.com/seller-permissions/check/123123')->willReturn($response); $response->getBody()->willReturn($body); $body->getContents()->willReturn('{ "permissionsGranted": false }'); diff --git a/spec/Generator/PayPalAuthAssertionGeneratorSpec.php b/spec/Generator/PayPalAuthAssertionGeneratorSpec.php index 658d512a..5ec3cc4b 100644 --- a/spec/Generator/PayPalAuthAssertionGeneratorSpec.php +++ b/spec/Generator/PayPalAuthAssertionGeneratorSpec.php @@ -27,7 +27,7 @@ function it_implements_pay_pal_auth_assertion_generator_interface(): void function it_generates_auth_assertion_based_on_payment_method_config( PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn(['client_id' => 'CLIENT_ID', 'merchant_id' => 'MERCHANT_ID']); @@ -40,7 +40,7 @@ function it_generates_auth_assertion_based_on_payment_method_config( function it_throws_an_exception_if_gateway_config_does_not_have_proper_values_set( PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig, $gatewayConfig); $gatewayConfig->getConfig()->willReturn(['merchant_id' => 'MERCHANT_ID'], ['client_id' => 'CLIENT_ID']); diff --git a/spec/Listener/PayPalPaymentMethodListenerSpec.php b/spec/Listener/PayPalPaymentMethodListenerSpec.php index d32ca09f..22a9417f 100644 --- a/spec/Listener/PayPalPaymentMethodListenerSpec.php +++ b/spec/Listener/PayPalPaymentMethodListenerSpec.php @@ -22,13 +22,13 @@ function let( OnboardingInitiatorInterface $onboardingInitiator, UrlGeneratorInterface $urlGenerator, FlashBagInterface $flashBag, - PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider + PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider, ): void { $this->beConstructedWith( $onboardingInitiator, $urlGenerator, $flashBag, - $payPalPaymentMethodProvider + $payPalPaymentMethodProvider, ); } @@ -37,7 +37,7 @@ function it_initiates_onboarding_when_creating_a_supported_payment_method( PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider, ResourceControllerEvent $event, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $event->getSubject()->willReturn($paymentMethod); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -71,7 +71,7 @@ function it_redirects_with_error_if_the_pay_pal_payment_method_already_exists( FlashBagInterface $flashBag, ResourceControllerEvent $event, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $event->getSubject()->willReturn($paymentMethod); $payPalPaymentMethodProvider->provide()->willReturn($paymentMethod); @@ -95,7 +95,7 @@ function it_does_nothing_when_creating_an_unsupported_payment_method( PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider, ResourceControllerEvent $event, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $event->getSubject()->willReturn($paymentMethod); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -112,7 +112,7 @@ function it_does_nothing_when_creating_an_unsupported_payment_method( function it_does_nothing_if_payment_method_is_not_pay_pal( ResourceControllerEvent $event, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $event->getSubject()->willReturn($paymentMethod); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); diff --git a/spec/Manager/PaymentStateManagerSpec.php b/spec/Manager/PaymentStateManagerSpec.php index 28ab1d42..f6caad5a 100644 --- a/spec/Manager/PaymentStateManagerSpec.php +++ b/spec/Manager/PaymentStateManagerSpec.php @@ -19,7 +19,7 @@ final class PaymentStateManagerSpec extends ObjectBehavior function let( FactoryInterface $stateMachineFactory, ObjectManager $paymentManager, - PaymentCompleteProcessorInterface $paymentCompleteProcessor + PaymentCompleteProcessorInterface $paymentCompleteProcessor, ): void { $this->beConstructedWith($stateMachineFactory, $paymentManager, $paymentCompleteProcessor); } @@ -33,7 +33,7 @@ function it_creates_payment( FactoryInterface $stateMachineFactory, ObjectManager $paymentManager, PaymentInterface $payment, - StateMachineInterface $stateMachine + StateMachineInterface $stateMachine, ): void { $stateMachineFactory->get($payment, PaymentTransitions::GRAPH)->willReturn($stateMachine); $stateMachine->apply(PaymentTransitions::TRANSITION_CREATE)->shouldBeCalled(); @@ -47,7 +47,7 @@ function it_completes_payment_if_its_completed_in_paypal( ObjectManager $paymentManager, PaymentCompleteProcessorInterface $paymentCompleteProcessor, PaymentInterface $payment, - StateMachineInterface $stateMachine + StateMachineInterface $stateMachine, ): void { $paymentCompleteProcessor->completePayment($payment); $payment->getDetails()->willReturn(['status' => StatusAction::STATUS_COMPLETED]); @@ -64,7 +64,7 @@ function it_processes_payment_if_its_processing_in_paypal_and_not_processing_in_ ObjectManager $paymentManager, PaymentCompleteProcessorInterface $paymentCompleteProcessor, PaymentInterface $payment, - StateMachineInterface $stateMachine + StateMachineInterface $stateMachine, ): void { $paymentCompleteProcessor->completePayment($payment); $payment->getDetails()->willReturn(['status' => StatusAction::STATUS_PROCESSING]); @@ -80,7 +80,7 @@ function it_processes_payment_if_its_processing_in_paypal_and_not_processing_in_ function it_does_nothing_if_payment_is_processing_in_paypal_but_already_processing_in_sylius( FactoryInterface $stateMachineFactory, PaymentCompleteProcessorInterface $paymentCompleteProcessor, - PaymentInterface $payment + PaymentInterface $payment, ): void { $paymentCompleteProcessor->completePayment($payment); $payment->getDetails()->willReturn(['status' => StatusAction::STATUS_PROCESSING]); @@ -95,7 +95,7 @@ function it_processes_payment( FactoryInterface $stateMachineFactory, ObjectManager $paymentManager, PaymentInterface $payment, - StateMachineInterface $stateMachine + StateMachineInterface $stateMachine, ): void { $stateMachineFactory->get($payment, PaymentTransitions::GRAPH)->willReturn($stateMachine); $stateMachine->apply(PaymentTransitions::TRANSITION_PROCESS)->shouldBeCalled(); @@ -108,7 +108,7 @@ function it_cancels_payment( FactoryInterface $stateMachineFactory, ObjectManager $paymentManager, PaymentInterface $payment, - StateMachineInterface $stateMachine + StateMachineInterface $stateMachine, ): void { $stateMachineFactory->get($payment, PaymentTransitions::GRAPH)->willReturn($stateMachine); $stateMachine->apply(PaymentTransitions::TRANSITION_CANCEL)->shouldBeCalled(); diff --git a/spec/Model/PayPalOrderSpec.php b/spec/Model/PayPalOrderSpec.php index cfa4a32b..37bc35b2 100644 --- a/spec/Model/PayPalOrderSpec.php +++ b/spec/Model/PayPalOrderSpec.php @@ -28,7 +28,7 @@ function let(OrderInterface $order, PayPalPurchaseUnit $payPalPurchaseUnit): voi public function it_returns_full_paypal_order_data( OrderInterface $order, PayPalPurchaseUnit $payPalPurchaseUnit, - AddressInterface $shippingAddress + AddressInterface $shippingAddress, ): void { $order->isShippingRequired()->willReturn(true); $order->getShippingAddress()->willReturn($shippingAddress); @@ -64,18 +64,18 @@ public function it_returns_full_paypal_order_data( ], 'soft_descriptor' => 'DESCRIPTION', 'items' => [ - ['test_item'] + ['test_item'], ], 'shipping' => [ 'name' => [ - 'full_name' => 'Gandalf The Grey' + 'full_name' => 'Gandalf The Grey', ], 'address' => [ 'address_line_1' => 'Hobbit St. 123', 'admin_area_2' => 'Minas Tirith', 'postal_code' => '000', - 'country_code' => 'US' - ] + 'country_code' => 'US', + ], ], ], ); @@ -114,31 +114,31 @@ public function it_returns_full_paypal_order_data( ], 'soft_descriptor' => 'DESCRIPTION', 'items' => [ - ['test_item'] + ['test_item'], ], 'shipping' => [ 'name' => [ - 'full_name' => 'Gandalf The Grey' + 'full_name' => 'Gandalf The Grey', ], 'address' => [ 'address_line_1' => 'Hobbit St. 123', 'admin_area_2' => 'Minas Tirith', 'postal_code' => '000', - 'country_code' => 'US' - ] + 'country_code' => 'US', + ], ], ], ], 'application_context' => [ - 'shipping_preference' => 'SET_PROVIDED_ADDRESS' - ] - ] + 'shipping_preference' => 'SET_PROVIDED_ADDRESS', + ], + ], ); } public function it_returns_paypal_order_data_without_shipping_address( OrderInterface $order, - PayPalPurchaseUnit $payPalPurchaseUnit + PayPalPurchaseUnit $payPalPurchaseUnit, ): void { $order->isShippingRequired()->willReturn(true); $order->getShippingAddress()->willReturn(null); @@ -174,7 +174,7 @@ public function it_returns_paypal_order_data_without_shipping_address( ], 'soft_descriptor' => 'DESCRIPTION', 'items' => [ - ['test_item'] + ['test_item'], ], ], ); @@ -213,20 +213,20 @@ public function it_returns_paypal_order_data_without_shipping_address( ], 'soft_descriptor' => 'DESCRIPTION', 'items' => [ - ['test_item'] + ['test_item'], ], ], ], 'application_context' => [ - 'shipping_preference' => 'GET_FROM_FILE' - ] - ] + 'shipping_preference' => 'GET_FROM_FILE', + ], + ], ); } public function it_returns_paypal_order_data_if_shipping_is_not_required( OrderInterface $order, - PayPalPurchaseUnit $payPalPurchaseUnit + PayPalPurchaseUnit $payPalPurchaseUnit, ): void { $order->isShippingRequired()->willReturn(false); $order->getShippingAddress()->shouldNotBeCalled(); @@ -262,7 +262,7 @@ public function it_returns_paypal_order_data_if_shipping_is_not_required( ], 'soft_descriptor' => 'DESCRIPTION', 'items' => [ - ['test_item'] + ['test_item'], ], ], ); @@ -301,14 +301,14 @@ public function it_returns_paypal_order_data_if_shipping_is_not_required( ], 'soft_descriptor' => 'DESCRIPTION', 'items' => [ - ['test_item'] + ['test_item'], ], ], ], 'application_context' => [ - 'shipping_preference' => 'NO_SHIPPING' - ] - ] + 'shipping_preference' => 'NO_SHIPPING', + ], + ], ); } } diff --git a/spec/Model/PayPalPurchaseUnitSpec.php b/spec/Model/PayPalPurchaseUnitSpec.php index a5227954..5b4c0daf 100644 --- a/spec/Model/PayPalPurchaseUnitSpec.php +++ b/spec/Model/PayPalPurchaseUnitSpec.php @@ -33,7 +33,7 @@ function let(AddressInterface $shippingAddress): void [['test_item']], true, $shippingAddress, - 'DESCRIPTION' + 'DESCRIPTION', ); } @@ -76,18 +76,18 @@ function it_returns_proper_paypal_purchase_unit(AddressInterface $shippingAddres ], 'soft_descriptor' => 'DESCRIPTION', 'items' => [ - ['test_item'] + ['test_item'], ], 'shipping' => [ 'name' => [ - 'full_name' => 'Gandalf The Grey' + 'full_name' => 'Gandalf The Grey', ], 'address' => [ 'address_line_1' => 'Hobbit St. 123', 'admin_area_2' => 'Minas Tirith', 'postal_code' => '000', - 'country_code' => 'US' - ] + 'country_code' => 'US', + ], ], ], ); @@ -107,7 +107,7 @@ function it_returns_proper_paypal_purchase_unit_if_shipping_is_not_required(Addr 'MERCHANT_ID', [['test_item']], false, - $shippingAddress + $shippingAddress, ); $this->toArray()->shouldReturn( @@ -141,7 +141,7 @@ function it_returns_proper_paypal_purchase_unit_if_shipping_is_not_required(Addr ], 'soft_descriptor' => 'Sylius PayPal Payment', 'items' => [ - ['test_item'] + ['test_item'], ], ], ); @@ -161,7 +161,7 @@ function it_returns_proper_paypal_purchase_unit_if_shipping_is_not_set(): void 'MERCHANT_ID', [['test_item']], false, - null + null, ); $this->toArray()->shouldReturn( @@ -195,7 +195,7 @@ function it_returns_proper_paypal_purchase_unit_if_shipping_is_not_set(): void ], 'soft_descriptor' => 'Sylius PayPal Payment', 'items' => [ - ['test_item'] + ['test_item'], ], ], ); diff --git a/spec/Onboarding/Initiator/OnboardingInitiatorSpec.php b/spec/Onboarding/Initiator/OnboardingInitiatorSpec.php index 73d6a041..5ddd772f 100644 --- a/spec/Onboarding/Initiator/OnboardingInitiatorSpec.php +++ b/spec/Onboarding/Initiator/OnboardingInitiatorSpec.php @@ -25,7 +25,7 @@ function it_implements_onboarding_initiator_interface(): void } function it_throws_an_exception_during_initialization_if_payment_method_is_not_supported( - PaymentMethodInterface $paymentMethod + PaymentMethodInterface $paymentMethod, ): void { $paymentMethod->getGatewayConfig()->willReturn(null); @@ -37,7 +37,7 @@ function it_throws_an_exception_during_initialization_if_payment_method_is_not_s function it_supports_paypal_payment_method_without_client_id_set( PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); @@ -48,7 +48,7 @@ function it_supports_paypal_payment_method_without_client_id_set( function it_does_not_support_paypal_payment_method_with_client_id_set( PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); @@ -59,7 +59,7 @@ function it_does_not_support_paypal_payment_method_with_client_id_set( function it_does_not_support_payment_method_with_invalid_gateway_factory_name( PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getFactoryName()->willReturn('offline'); @@ -68,7 +68,7 @@ function it_does_not_support_payment_method_with_invalid_gateway_factory_name( } function it_does_not_support_payment_method_without_gateway_config( - PaymentMethodInterface $paymentMethod + PaymentMethodInterface $paymentMethod, ): void { $paymentMethod->getGatewayConfig()->willReturn(null); @@ -80,7 +80,7 @@ function it_returns_url_when_payment_is_valid( GatewayConfigInterface $gatewayConfig, Security $security, AdminUserInterface $adminUser, - UrlGeneratorInterface $urlGenerator + UrlGeneratorInterface $urlGenerator, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -96,7 +96,7 @@ function it_returns_url_when_payment_is_valid( ; $this->initiate($paymentMethod)->shouldReturn( - 'https://paypal-url/partner-referrals/create?email=sylius%40sylius.com&return_url=%2Fadmin%2Fpayment-methods%2Fnew%2Fsylius.pay_pal' + 'https://paypal-url/partner-referrals/create?email=sylius%40sylius.com&return_url=%2Fadmin%2Fpayment-methods%2Fnew%2Fsylius.pay_pal', ); } } diff --git a/spec/Onboarding/Processor/BasicOnboardingProcessorSpec.php b/spec/Onboarding/Processor/BasicOnboardingProcessorSpec.php index 51da39d2..e65966ed 100644 --- a/spec/Onboarding/Processor/BasicOnboardingProcessorSpec.php +++ b/spec/Onboarding/Processor/BasicOnboardingProcessorSpec.php @@ -4,9 +4,13 @@ namespace spec\Sylius\PayPalPlugin\Onboarding\Processor; -use GuzzleHttp\ClientInterface; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; use Payum\Core\Model\GatewayConfigInterface; use PhpSpec\ObjectBehavior; +use Prophecy\Argument; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use Sylius\Component\Core\Model\PaymentMethod; @@ -21,40 +25,103 @@ final class BasicOnboardingProcessorSpec extends ObjectBehavior { function let( ClientInterface $httpClient, - SellerWebhookRegistrarInterface $sellerWebhookRegistrar + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + RequestFactoryInterface $requestFactory, + RequestInterface $apiRequest, ): void { - $this->beConstructedWith($httpClient, $sellerWebhookRegistrar, 'https://paypal.facilitator.com'); + $this->beConstructedWith( + $httpClient, + $sellerWebhookRegistrar, + 'https://paypal.facilitator.com', + $requestFactory, + ); + + $apiRequest->withHeader(Argument::any(), Argument::any())->willReturn($apiRequest); } function it_processes_onboarding_for_supported_payment_method_and_request( ClientInterface $httpClient, + RequestFactoryInterface $requestFactory, + RequestInterface $apiRequest, SellerWebhookRegistrarInterface $sellerWebhookRegistrar, ResponseInterface $response, StreamInterface $body, GatewayConfigInterface $gatewayConfig, PaymentMethodInterface $paymentMethod, - Request $request + Request $request, ): void { $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); - $gatewayConfig->getConfig()->willReturn( - [ - 'client_id' => 'CLIENT-ID', - 'client_secret' => 'CLIENT-SECRET', - 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', - 'merchant_id' => 'MERCHANT-ID', - ] + $gatewayConfig->getConfig()->willReturn([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + ]); + + $gatewayConfig->setConfig([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'onboarding_id' => 'ONBOARDING-ID', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + 'partner_attribution_id' => 'ATTRIBUTION-ID', + ])->shouldBeCalled(); + + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); + + $request->query = new ParameterBag(['onboarding_id' => 'ONBOARDING-ID']); + + $requestFactory->createRequest( + 'GET', + 'https://paypal.facilitator.com/partner-referrals/check/ONBOARDING-ID', + )->willReturn($apiRequest); + $httpClient->sendRequest($apiRequest)->willReturn($response); + + $response->getBody()->willReturn($body); + $body->getContents()->willReturn( + '{"client_id":"CLIENT-ID", + "client_secret":"CLIENT-SECRET", + "sylius_merchant_id":"SYLIUS-MERCHANT-ID", + "merchant_id":"MERCHANT-ID", + "partner_attribution_id":"ATTRIBUTION-ID"}', ); - $gatewayConfig->setConfig( - [ - 'client_id' => 'CLIENT-ID', - 'client_secret' => 'CLIENT-SECRET', - 'onboarding_id' => 'ONBOARDING-ID', - 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', - 'merchant_id' => 'MERCHANT-ID', - 'partner_attribution_id' => 'ATTRIBUTION-ID', - ] - )->shouldBeCalled(); + $sellerWebhookRegistrar->register($paymentMethod)->shouldBeCalled(); + + $this->process($paymentMethod, $request)->shouldReturn($paymentMethod); + } + + function it_processes_onboarding_for_supported_payment_method_and_request_using_guzzle_client( + GuzzleClientInterface $httpClient, + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + ResponseInterface $response, + StreamInterface $body, + GatewayConfigInterface $gatewayConfig, + PaymentMethodInterface $paymentMethod, + Request $request, + ): void { + $this->beConstructedWith( + $httpClient, + $sellerWebhookRegistrar, + 'https://paypal.facilitator.com', + ); + + $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); + $gatewayConfig->getConfig()->willReturn([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + ]); + + $gatewayConfig->setConfig([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'onboarding_id' => 'ONBOARDING-ID', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + 'partner_attribution_id' => 'ATTRIBUTION-ID', + ])->shouldBeCalled(); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -69,7 +136,7 @@ function it_processes_onboarding_for_supported_payment_method_and_request( 'Content-Type' => 'application/json', 'Accept' => 'application/json', ], - ] + ], ) ->willReturn($response) ; @@ -80,7 +147,7 @@ function it_processes_onboarding_for_supported_payment_method_and_request( "client_secret":"CLIENT-SECRET", "sylius_merchant_id":"SYLIUS-MERCHANT-ID", "merchant_id":"MERCHANT-ID", - "partner_attribution_id":"ATTRIBUTION-ID"}' + "partner_attribution_id":"ATTRIBUTION-ID"}', ); $sellerWebhookRegistrar->register($paymentMethod)->shouldBeCalled(); @@ -90,23 +157,82 @@ function it_processes_onboarding_for_supported_payment_method_and_request( function it_processes_onboarding_for_supported_payment_method_with_not_granted_permissions_and_request( ClientInterface $httpClient, + RequestFactoryInterface $requestFactory, + RequestInterface $apiRequest, SellerWebhookRegistrarInterface $sellerWebhookRegistrar, ResponseInterface $response, StreamInterface $body, GatewayConfigInterface $gatewayConfig, PaymentMethodInterface $paymentMethod, - Request $request + Request $request, ): void { $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); - $gatewayConfig->getConfig()->willReturn( - [ - 'client_id' => 'CLIENT-ID', - 'client_secret' => 'CLIENT-SECRET', - 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', - 'merchant_id' => 'MERCHANT-ID', - ] + $gatewayConfig->getConfig()->willReturn([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + ]); + + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); + + $request->query = new ParameterBag(['onboarding_id' => 'ONBOARDING-ID', 'permissionsGranted' => false]); + + $requestFactory->createRequest( + 'GET', + 'https://paypal.facilitator.com/partner-referrals/check/ONBOARDING-ID', + )->willReturn($apiRequest); + $httpClient->sendRequest($apiRequest)->willReturn($response); + + $response->getBody()->willReturn($body); + $body->getContents()->willReturn( + '{"client_id":"CLIENT-ID", + "client_secret":"CLIENT-SECRET", + "sylius_merchant_id":"SYLIUS-MERCHANT-ID", + "merchant_id":"MERCHANT-ID", + "partner_attribution_id":"ATTRIBUTION-ID"}', + ); + + $paymentMethod->setEnabled(false)->shouldBeCalled(); + $gatewayConfig->setConfig([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'onboarding_id' => 'ONBOARDING-ID', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + 'partner_attribution_id' => 'ATTRIBUTION-ID', + ])->shouldBeCalled(); + + $sellerWebhookRegistrar->register($paymentMethod)->shouldBeCalled(); + + $this->process($paymentMethod, $request)->shouldReturn($paymentMethod); + } + + function it_processes_onboarding_for_supported_payment_method_with_not_granted_permissions_and_request_using_guzzle_client( + GuzzleClientInterface $httpClient, + RequestFactoryInterface $requestFactory, + RequestInterface $apiRequest, + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + ResponseInterface $response, + StreamInterface $body, + GatewayConfigInterface $gatewayConfig, + PaymentMethodInterface $paymentMethod, + Request $request, + ): void { + $this->beConstructedWith( + $httpClient, + $sellerWebhookRegistrar, + 'https://paypal.facilitator.com', ); + $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); + $gatewayConfig->getConfig()->willReturn([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + ]); + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $request->query = new ParameterBag(['onboarding_id' => 'ONBOARDING-ID', 'permissionsGranted' => false]); @@ -120,7 +246,7 @@ function it_processes_onboarding_for_supported_payment_method_with_not_granted_p 'Content-Type' => 'application/json', 'Accept' => 'application/json', ], - ] + ], ) ->willReturn($response) ; @@ -131,20 +257,18 @@ function it_processes_onboarding_for_supported_payment_method_with_not_granted_p "client_secret":"CLIENT-SECRET", "sylius_merchant_id":"SYLIUS-MERCHANT-ID", "merchant_id":"MERCHANT-ID", - "partner_attribution_id":"ATTRIBUTION-ID"}' + "partner_attribution_id":"ATTRIBUTION-ID"}', ); $paymentMethod->setEnabled(false)->shouldBeCalled(); - $gatewayConfig->setConfig( - [ - 'client_id' => 'CLIENT-ID', - 'client_secret' => 'CLIENT-SECRET', - 'onboarding_id' => 'ONBOARDING-ID', - 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', - 'merchant_id' => 'MERCHANT-ID', - 'partner_attribution_id' => 'ATTRIBUTION-ID', - ] - )->shouldBeCalled(); + $gatewayConfig->setConfig([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'onboarding_id' => 'ONBOARDING-ID', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + 'partner_attribution_id' => 'ATTRIBUTION-ID', + ])->shouldBeCalled(); $sellerWebhookRegistrar->register($paymentMethod)->shouldBeCalled(); @@ -153,23 +277,81 @@ function it_processes_onboarding_for_supported_payment_method_with_not_granted_p function it_processes_onboarding_for_supported_payment_method_with_not_granted_permissions_and_without_registered_webhook( ClientInterface $httpClient, + RequestFactoryInterface $requestFactory, + RequestInterface $apiRequest, SellerWebhookRegistrarInterface $sellerWebhookRegistrar, ResponseInterface $response, StreamInterface $body, GatewayConfigInterface $gatewayConfig, PaymentMethodInterface $paymentMethod, - Request $request + Request $request, ): void { $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); - $gatewayConfig->getConfig()->willReturn( - [ - 'client_id' => 'CLIENT-ID', - 'client_secret' => 'CLIENT-SECRET', - 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', - 'merchant_id' => 'MERCHANT-ID', - ] + $gatewayConfig->getConfig()->willReturn([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + ]); + + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); + + $request->query = new ParameterBag(['onboarding_id' => 'ONBOARDING-ID', 'permissionsGranted' => false]); + + $requestFactory->createRequest( + 'GET', + 'https://paypal.facilitator.com/partner-referrals/check/ONBOARDING-ID', + )->willReturn($apiRequest); + $httpClient->sendRequest($apiRequest)->willReturn($response); + + $response->getBody()->willReturn($body); + $body->getContents()->willReturn( + '{"client_id":"CLIENT-ID", + "client_secret":"CLIENT-SECRET", + "sylius_merchant_id":"SYLIUS-MERCHANT-ID", + "merchant_id":"MERCHANT-ID", + "partner_attribution_id":"ATTRIBUTION-ID"}', + ); + + $paymentMethod->setEnabled(false)->shouldBeCalled(); + $gatewayConfig->setConfig([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'onboarding_id' => 'ONBOARDING-ID', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + 'partner_attribution_id' => 'ATTRIBUTION-ID', + ])->shouldBeCalled(); + + $sellerWebhookRegistrar->register($paymentMethod)->willThrow(PayPalWebhookUrlNotValidException::class); + $paymentMethod->setEnabled(false)->shouldBeCalled(); + + $this->process($paymentMethod, $request)->shouldReturn($paymentMethod); + } + + function it_processes_onboarding_for_supported_payment_method_with_not_granted_permissions_and_without_registered_webhook_using_guzzle_client( + GuzzleClientInterface $httpClient, + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + ResponseInterface $response, + StreamInterface $body, + GatewayConfigInterface $gatewayConfig, + PaymentMethodInterface $paymentMethod, + Request $request, + ): void { + $this->beConstructedWith( + $httpClient, + $sellerWebhookRegistrar, + 'https://paypal.facilitator.com', ); + $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); + $gatewayConfig->getConfig()->willReturn([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + ]); + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $request->query = new ParameterBag(['onboarding_id' => 'ONBOARDING-ID', 'permissionsGranted' => false]); @@ -183,7 +365,7 @@ function it_processes_onboarding_for_supported_payment_method_with_not_granted_p 'Content-Type' => 'application/json', 'Accept' => 'application/json', ], - ] + ], ) ->willReturn($response) ; @@ -194,20 +376,18 @@ function it_processes_onboarding_for_supported_payment_method_with_not_granted_p "client_secret":"CLIENT-SECRET", "sylius_merchant_id":"SYLIUS-MERCHANT-ID", "merchant_id":"MERCHANT-ID", - "partner_attribution_id":"ATTRIBUTION-ID"}' + "partner_attribution_id":"ATTRIBUTION-ID"}', ); $paymentMethod->setEnabled(false)->shouldBeCalled(); - $gatewayConfig->setConfig( - [ - 'client_id' => 'CLIENT-ID', - 'client_secret' => 'CLIENT-SECRET', - 'onboarding_id' => 'ONBOARDING-ID', - 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', - 'merchant_id' => 'MERCHANT-ID', - 'partner_attribution_id' => 'ATTRIBUTION-ID', - ] - )->shouldBeCalled(); + $gatewayConfig->setConfig([ + 'client_id' => 'CLIENT-ID', + 'client_secret' => 'CLIENT-SECRET', + 'onboarding_id' => 'ONBOARDING-ID', + 'sylius_merchant_id' => 'SYLIUS-MERCHANT-ID', + 'merchant_id' => 'MERCHANT-ID', + 'partner_attribution_id' => 'ATTRIBUTION-ID', + ])->shouldBeCalled(); $sellerWebhookRegistrar->register($paymentMethod)->willThrow(PayPalWebhookUrlNotValidException::class); $paymentMethod->setEnabled(false)->shouldBeCalled(); @@ -217,7 +397,7 @@ function it_processes_onboarding_for_supported_payment_method_with_not_granted_p function it_throws_an_exception_when_trying_to_process_onboarding_for_unsupported_payment_method_or_request( PaymentMethodInterface $paymentMethod, - Request $request + Request $request, ): void { $this ->shouldThrow(\DomainException::class) @@ -225,10 +405,28 @@ function it_throws_an_exception_when_trying_to_process_onboarding_for_unsupporte ; } + function it_throws_an_exception_when_trying_to_process_onboarding_for_unsupported_payment_method_or_request_using_guzzle_client( + GuzzleClientInterface $httpClient, + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + PaymentMethodInterface $paymentMethod, + Request $request, + ): void { + $this->beConstructedWith( + $httpClient, + $sellerWebhookRegistrar, + 'https://paypal.facilitator.com', + ); + + $this + ->shouldThrow(\DomainException::class) + ->during('process', [$paymentMethod, $request]) + ; + } + function it_supports_paypal_payment_method_with_request_containing_id( GatewayConfigInterface $gatewayConfig, PaymentMethod $paymentMethod, - Request $request + Request $request, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); @@ -238,9 +436,30 @@ function it_supports_paypal_payment_method_with_request_containing_id( $this->supports($paymentMethod, $request)->shouldReturn(true); } + function it_supports_paypal_payment_method_with_request_containing_id_using_guzzle_client( + GuzzleClientInterface $httpClient, + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + GatewayConfigInterface $gatewayConfig, + PaymentMethod $paymentMethod, + Request $request, + ): void { + $this->beConstructedWith( + $httpClient, + $sellerWebhookRegistrar, + 'https://paypal.facilitator.com', + ); + + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); + $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); + + $request->query = new ParameterBag(['onboarding_id' => 'FACILITATOR-ID']); + + $this->supports($paymentMethod, $request)->shouldReturn(true); + } + function it_does_not_support_payment_method_that_has_no_gateway_config( PaymentMethodInterface $paymentMethod, - Request $request + Request $request, ): void { $this->supports($paymentMethod, $request)->shouldReturn(false); } @@ -248,7 +467,7 @@ function it_does_not_support_payment_method_that_has_no_gateway_config( function it_does_not_support_payment_method_that_does_not_have_paypal_as_a_gateway_factory( GatewayConfigInterface $gatewayConfig, PaymentMethodInterface $paymentMethod, - Request $request + Request $request, ): void { $gatewayConfig->getFactoryName()->willReturn('random'); @@ -259,7 +478,7 @@ function it_does_not_support_payment_method_that_does_not_have_paypal_as_a_gatew function it_does_not_support_payment_method_that_has_client_id_is_not_set_on_request( GatewayConfigInterface $gatewayConfig, - PaymentMethodInterface $paymentMethod + PaymentMethodInterface $paymentMethod, ): void { $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); @@ -270,12 +489,52 @@ function it_does_not_support_payment_method_that_has_client_id_is_not_set_on_req function it_throws_error_if_facilitator_data_is_not_loaded( ClientInterface $httpClient, + RequestFactoryInterface $requestFactory, + RequestInterface $apiRequest, + ResponseInterface $response, + StreamInterface $body, + GatewayConfigInterface $gatewayConfig, + PaymentMethodInterface $paymentMethod, + Request $request, + ): void { + $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); + + $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); + + $request->query = new ParameterBag(['onboarding_id' => 'ONBOARDING-ID']); + + $requestFactory->createRequest( + 'GET', + 'https://paypal.facilitator.com/partner-referrals/check/ONBOARDING-ID', + )->willReturn($apiRequest); + $httpClient->sendRequest($apiRequest)->willReturn($response); + + $response->getBody()->willReturn($body); + $body->getContents()->willReturn('{"client_id":null,"client_secret":null}'); + + $this + ->shouldThrow(PayPalPluginException::class) + ->during('process', [$paymentMethod, $request]) + ; + } + + function it_throws_error_if_facilitator_data_is_not_loaded_using_guzzle_client( + GuzzleClientInterface $httpClient, + SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + RequestFactoryInterface $requestFactory, + RequestInterface $apiRequest, ResponseInterface $response, StreamInterface $body, GatewayConfigInterface $gatewayConfig, PaymentMethodInterface $paymentMethod, - Request $request + Request $request, ): void { + $this->beConstructedWith( + $httpClient, + $sellerWebhookRegistrar, + 'https://paypal.facilitator.com', + ); + $gatewayConfig->getFactoryName()->willReturn('sylius.pay_pal'); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -291,7 +550,7 @@ function it_throws_error_if_facilitator_data_is_not_loaded( 'Content-Type' => 'application/json', 'Accept' => 'application/json', ], - ] + ], ) ->willReturn($response) ; diff --git a/spec/Payum/Action/AuthorizeActionSpec.php b/spec/Payum/Action/AuthorizeActionSpec.php index fdc34be8..1fbedcd5 100644 --- a/spec/Payum/Action/AuthorizeActionSpec.php +++ b/spec/Payum/Action/AuthorizeActionSpec.php @@ -31,7 +31,7 @@ function it_implements_action_interface(): void function it_marks_payment_as_created( Authorize $request, - PaymentInterface $payment + PaymentInterface $payment, ): void { $request->getModel()->willReturn($payment); $payment->setDetails(['status' => StatusAction::STATUS_CREATED])->shouldBeCalled(); @@ -49,7 +49,7 @@ function it_throws_an_exception_if_request_type_is_invalid(GetStatus $request): function it_supports_authorize_request_with_payment_as_first_model( Authorize $request, - PaymentInterface $payment + PaymentInterface $payment, ): void { $request->getModel()->willReturn($payment); diff --git a/spec/Payum/Action/CaptureActionSpec.php b/spec/Payum/Action/CaptureActionSpec.php index 750db99b..f274529a 100644 --- a/spec/Payum/Action/CaptureActionSpec.php +++ b/spec/Payum/Action/CaptureActionSpec.php @@ -31,7 +31,7 @@ final class CaptureActionSpec extends ObjectBehavior function let( CacheAuthorizeClientApiInterface $authorizeClientApi, CreateOrderApiInterface $createOrderApi, - UuidProviderInterface $uuidProvider + UuidProviderInterface $uuidProvider, ): void { $this->beConstructedWith($authorizeClientApi, $createOrderApi, $uuidProvider); } @@ -48,7 +48,7 @@ function it_authorizes_seller_send_create_order_request_and_sets_order_response_ OrderInterface $order, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - UuidProviderInterface $uuidProvider + UuidProviderInterface $uuidProvider, ): void { $request->getModel()->willReturn($payment); $payment->getMethod()->willReturn($paymentMethod); @@ -81,7 +81,7 @@ function it_throws_an_exception_if_request_type_is_invalid(GetStatus $request): function it_supports_capture_request_with_payment_as_first_model( Capture $request, - PaymentInterface $payment + PaymentInterface $payment, ): void { $request->getModel()->willReturn($payment); diff --git a/spec/Payum/Action/CompleteOrderActionSpec.php b/spec/Payum/Action/CompleteOrderActionSpec.php index f743bc39..7d7b36f5 100644 --- a/spec/Payum/Action/CompleteOrderActionSpec.php +++ b/spec/Payum/Action/CompleteOrderActionSpec.php @@ -39,7 +39,7 @@ function let( PayPalAddressProcessorInterface $payPalAddressProcessor, PaymentUpdaterInterface $payPalPaymentUpdater, StateResolverInterface $orderPaymentStateResolver, - PayPalItemDataProviderInterface $payPalItemsDataProvider + PayPalItemDataProviderInterface $payPalItemsDataProvider, ): void { $this->beConstructedWith( $authorizeClientApi, @@ -49,7 +49,7 @@ function let( $payPalAddressProcessor, $payPalPaymentUpdater, $orderPaymentStateResolver, - $payPalItemsDataProvider + $payPalItemsDataProvider, ); } @@ -65,7 +65,7 @@ function it_completes_order( CompleteOrder $request, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - OrderInterface $order + OrderInterface $order, ): void { $request->getModel()->willReturn($payment); $payment->getMethod()->willReturn($paymentMethod); @@ -76,7 +76,7 @@ function it_completes_order( $request->getOrderId()->willReturn('123123'); - $payment->getAmount()->willReturn(1000);; + $payment->getAmount()->willReturn(1000); $order->getTotal()->willReturn(1000); $completeOrderApi->complete('TOKEN', '123123')->shouldBeCalled(); @@ -84,8 +84,8 @@ function it_completes_order( 'status' => 'COMPLETED', 'id' => '123123', 'purchase_units' => [ - ['reference_id' => 'REFERENCE_ID'] - ] + ['reference_id' => 'REFERENCE_ID'], + ], ]); $payment->setDetails([ @@ -106,7 +106,7 @@ function it_completes_order_and_saves_transaction_id( CompleteOrder $request, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - OrderInterface $order + OrderInterface $order, ): void { $request->getModel()->willReturn($payment); $payment->getMethod()->willReturn($paymentMethod); @@ -117,7 +117,7 @@ function it_completes_order_and_saves_transaction_id( $request->getOrderId()->willReturn('123123'); - $payment->getAmount()->willReturn(1000);; + $payment->getAmount()->willReturn(1000); $order->getTotal()->willReturn(1000); $completeOrderApi->complete('TOKEN', '123123')->shouldBeCalled(); @@ -128,8 +128,8 @@ function it_completes_order_and_saves_transaction_id( [ 'reference_id' => 'REFERENCE_ID', 'payments' => ['captures' => [['id' => 'TRANSACTION_ID']]], - ] - ] + ], + ], ]); $payment->setDetails([ diff --git a/spec/Payum/Action/ResolveNextRouteActionSpec.php b/spec/Payum/Action/ResolveNextRouteActionSpec.php index 99a8ec61..6ab680e5 100644 --- a/spec/Payum/Action/ResolveNextRouteActionSpec.php +++ b/spec/Payum/Action/ResolveNextRouteActionSpec.php @@ -19,7 +19,7 @@ function it_executes_resolve_next_route_request_with_processing_payment( PaymentInterface $payment, OrderInterface $order, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $request->getFirstModel()->willReturn($payment); @@ -43,7 +43,7 @@ function it_executes_resolve_next_route_request_with_completed_payment( PaymentInterface $payment, OrderInterface $order, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $request->getFirstModel()->willReturn($payment); $payment->getOrder()->willReturn($order); @@ -63,7 +63,7 @@ function it_executes_resolve_next_route_request_with_some_other_payment( PaymentInterface $payment, OrderInterface $order, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $request->getFirstModel()->willReturn($payment); @@ -85,7 +85,7 @@ function it_supports_resolve_next_route_request_with_payment_as_first_model( ResolveNextRoute $request, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $request->getFirstModel()->willReturn($payment); $payment->getMethod()->willReturn($paymentMethod); @@ -99,7 +99,7 @@ function it_does_not_support_payment_with_other_factory_name_than_pay_pal( ResolveNextRoute $request, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $request->getFirstModel()->willReturn($payment); $payment->getMethod()->willReturn($paymentMethod); diff --git a/spec/Payum/Action/StatusActionSpec.php b/spec/Payum/Action/StatusActionSpec.php index 7bd5d8e8..fd6fd373 100644 --- a/spec/Payum/Action/StatusActionSpec.php +++ b/spec/Payum/Action/StatusActionSpec.php @@ -68,7 +68,7 @@ function it_throws_an_exception_if_request_is_not_supported(Capture $request): v function it_supports_get_status_request_with_payment_as_first_model( GetStatus $request, - PaymentInterface $payment + PaymentInterface $payment, ): void { $request->getFirstModel()->willReturn($payment); diff --git a/spec/Processor/AfterCheckoutOrderPaymentProcessorSpec.php b/spec/Processor/AfterCheckoutOrderPaymentProcessorSpec.php index 7a07975b..907e50bf 100644 --- a/spec/Processor/AfterCheckoutOrderPaymentProcessorSpec.php +++ b/spec/Processor/AfterCheckoutOrderPaymentProcessorSpec.php @@ -32,7 +32,7 @@ function it_implements_order_processor_interface(): void function it_does_nothing_if_order_is_not_completed( OrderProcessorInterface $baseOrderPaymentProcessor, - OrderInterface $order + OrderInterface $order, ): void { $order->getCheckoutState()->willReturn(OrderCheckoutStates::STATE_ADDRESSED); @@ -43,7 +43,7 @@ function it_does_nothing_if_order_is_not_completed( function it_uses_processor_if_order_is_completed( OrderProcessorInterface $baseOrderPaymentProcessor, - OrderInterface $order + OrderInterface $order, ): void { $order->getCheckoutState()->willReturn(OrderCheckoutStates::STATE_COMPLETED); diff --git a/spec/Processor/OrderPaymentProcessorSpec.php b/spec/Processor/OrderPaymentProcessorSpec.php index 9c588fe5..920ec679 100644 --- a/spec/Processor/OrderPaymentProcessorSpec.php +++ b/spec/Processor/OrderPaymentProcessorSpec.php @@ -41,7 +41,7 @@ function it_does_nothing_if_there_is_a_pay_pal_processing_captured_payment( OrderInterface $order, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $order->getLastPayment(PaymentInterface::STATE_PROCESSING)->willReturn($payment); $payment->getDetails()->willReturn(['status' => 'CAPTURED']); @@ -56,7 +56,7 @@ function it_does_nothing_if_there_is_a_pay_pal_processing_captured_payment( function it_processes_order_if_there_is_no_processing_payment( OrderProcessorInterface $baseOrderProcessor, - OrderInterface $order + OrderInterface $order, ): void { $order->getLastPayment(PaymentInterface::STATE_PROCESSING)->willReturn(null); @@ -70,7 +70,7 @@ function it_processes_order_if_the_processing_payment_is_not_captured( OrderInterface $order, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $order->getLastPayment(PaymentInterface::STATE_PROCESSING)->willReturn($payment); $payment->getDetails()->willReturn(['status' => 'CANCELLED']); @@ -91,7 +91,7 @@ function it_cancels_payment_and_processes_order_if_the_processing_payment_has_me PaymentInterface $payment, PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, - StateMachineInterface $stateMachine + StateMachineInterface $stateMachine, ): void { $order->getLastPayment(PaymentInterface::STATE_PROCESSING)->willReturn($payment); $payment->getDetails()->willReturn(['status' => 'CANCELLED']); diff --git a/spec/Processor/PayPalAddressProcessorSpec.php b/spec/Processor/PayPalAddressProcessorSpec.php index 5bd3cf24..b8e82cbe 100644 --- a/spec/Processor/PayPalAddressProcessorSpec.php +++ b/spec/Processor/PayPalAddressProcessorSpec.php @@ -25,7 +25,7 @@ function it_implements_pay_pal_address_processor_interface(): void function it_updates_order_address( OrderInterface $order, AddressInterface $orderAddress, - ObjectManager $objectManager + ObjectManager $objectManager, ): void { $order->getShippingAddress()->willReturn($orderAddress); @@ -43,14 +43,14 @@ function it_updates_order_address( 'postal_code' => '10001', 'country_code' => 'US', ], - $order + $order, ); } function it_updates_order_address_with_two_address_lines( OrderInterface $order, AddressInterface $orderAddress, - ObjectManager $objectManager + ObjectManager $objectManager, ): void { $order->getShippingAddress()->willReturn($orderAddress); @@ -69,14 +69,14 @@ function it_updates_order_address_with_two_address_lines( 'postal_code' => '10001', 'country_code' => 'US', ], - $order + $order, ); } function it_throws_an_exception_if_address_data_is_missing( OrderInterface $order, AddressInterface $orderAddress, - ObjectManager $objectManager + ObjectManager $objectManager, ): void { $order->getShippingAddress()->willReturn($orderAddress); diff --git a/spec/Processor/PayPalOrderCompleteProcessorSpec.php b/spec/Processor/PayPalOrderCompleteProcessorSpec.php index 6ed54bdb..234fdb2e 100644 --- a/spec/Processor/PayPalOrderCompleteProcessorSpec.php +++ b/spec/Processor/PayPalOrderCompleteProcessorSpec.php @@ -33,7 +33,7 @@ function it_completes_pay_pal_order( OrderInterface $order, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $order->getLastPayment(PaymentInterface::STATE_PROCESSING)->willReturn($payment); @@ -51,7 +51,7 @@ function it_does_nothing_if_processing_payment_is_not_pay_pal( OrderInterface $order, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $order->getLastPayment(PaymentInterface::STATE_PROCESSING)->willReturn($payment); @@ -66,7 +66,7 @@ function it_does_nothing_if_processing_payment_is_not_pay_pal( function it_does_nothing_if_there_is_no_processing_payment_for_the_order( PaymentStateManagerInterface $paymentStateManager, - OrderInterface $order + OrderInterface $order, ): void { $order->getLastPayment(PaymentInterface::STATE_PROCESSING)->willReturn(null); diff --git a/spec/Processor/PayPalPaymentCompleteProcessorSpec.php b/spec/Processor/PayPalPaymentCompleteProcessorSpec.php index 2e4302cc..e22a2f43 100644 --- a/spec/Processor/PayPalPaymentCompleteProcessorSpec.php +++ b/spec/Processor/PayPalPaymentCompleteProcessorSpec.php @@ -42,7 +42,7 @@ function it_completes_payment_in_pay_pal( PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, GatewayInterface $gateway, - CompleteOrderPaymentResolverInterface $completeOrderPaymentResolver + CompleteOrderPaymentResolverInterface $completeOrderPaymentResolver, ): void { $payment->getDetails()->willReturn(['paypal_order_id' => '123123']); @@ -61,7 +61,7 @@ function it_completes_payment_in_pay_pal( function it_does_nothing_if_payment_has_no_pay_pal_order_id_set( Payum $payum, PaymentInterface $payment, - GatewayInterface $gateway + GatewayInterface $gateway, ): void { $payment->getDetails()->willReturn([]); diff --git a/spec/Processor/PayPalPaymentRefundProcessorSpec.php b/spec/Processor/PayPalPaymentRefundProcessorSpec.php index 075695b6..aeaf9cf7 100644 --- a/spec/Processor/PayPalPaymentRefundProcessorSpec.php +++ b/spec/Processor/PayPalPaymentRefundProcessorSpec.php @@ -35,14 +35,14 @@ function let( OrderDetailsApiInterface $orderDetailsApi, RefundPaymentApiInterface $refundOrderApi, PayPalAuthAssertionGeneratorInterface $payPalAuthAssertionGenerator, - RefundReferenceNumberProviderInterface $refundReferenceNumberProvider + RefundReferenceNumberProviderInterface $refundReferenceNumberProvider, ): void { $this->beConstructedWith( $authorizeClientApi, $orderDetailsApi, $refundOrderApi, $payPalAuthAssertionGenerator, - $refundReferenceNumberProvider + $refundReferenceNumberProvider, ); } @@ -60,7 +60,7 @@ function it_fully_refunds_payment_in_pay_pal( PaymentInterface $payment, PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, - OrderInterface $order + OrderInterface $order, ): void { $payment->getMethod()->willReturn($paymentMethod); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -92,7 +92,7 @@ function it_does_nothing_if_payment_is_not_pay_pal( RefundPaymentApiInterface $refundOrderApi, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $payment->getMethod()->willReturn($paymentMethod); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -108,7 +108,7 @@ function it_does_nothing_if_payment_is_payment_has_not_pay_pal_order_id( RefundPaymentApiInterface $refundOrderApi, PaymentInterface $payment, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $payment->getMethod()->willReturn($paymentMethod); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); @@ -130,7 +130,7 @@ function it_throws_exception_if_something_went_wrong_during_refunding_payment( PaymentInterface $payment, PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, - OrderInterface $order + OrderInterface $order, ): void { $payment->getMethod()->willReturn($paymentMethod); $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); diff --git a/spec/Processor/UiPayPalPaymentRefundProcessorSpec.php b/spec/Processor/UiPayPalPaymentRefundProcessorSpec.php index 657323dd..41232c18 100644 --- a/spec/Processor/UiPayPalPaymentRefundProcessorSpec.php +++ b/spec/Processor/UiPayPalPaymentRefundProcessorSpec.php @@ -33,7 +33,7 @@ function it_implements_payment_refund_processor_interface(): void function it_throws_exception_if_refund_has_fails( PaymentRefundProcessorInterface $paymentRefundProcessor, - PaymentInterface $payment + PaymentInterface $payment, ): void { $paymentRefundProcessor->refund($payment)->willThrow(PayPalOrderRefundException::class); @@ -42,7 +42,7 @@ function it_throws_exception_if_refund_has_fails( function it_does_nothing_if_refund_was_successful( PaymentRefundProcessorInterface $paymentRefundProcessor, - PaymentInterface $payment + PaymentInterface $payment, ): void { $paymentRefundProcessor->refund($payment)->shouldBeCalled(); diff --git a/spec/Provider/AvailableCountriesProviderSpec.php b/spec/Provider/AvailableCountriesProviderSpec.php index 9d39f09b..a2fb8807 100644 --- a/spec/Provider/AvailableCountriesProviderSpec.php +++ b/spec/Provider/AvailableCountriesProviderSpec.php @@ -25,7 +25,7 @@ function it_provides_available_countries_if_channel_does_not_have_any( RepositoryInterface $countryRepository, ChannelContextInterface $channelContext, ChannelInterface $channel, - Collection $collection + Collection $collection, ): void { $channel->getCountries()->willReturn($collection); @@ -46,7 +46,7 @@ function it_provides_available_countries_if_channel_contains_countries( RepositoryInterface $countryRepository, ChannelContextInterface $channelContext, ChannelInterface $channel, - Collection $collection + Collection $collection, ): void { $channel->getCountries()->willReturn($collection); $collection->toArray()->willReturn([$countryOne, $countryTwo]); diff --git a/spec/Provider/OrderItemNonNeutralTaxesProviderSpec.php b/spec/Provider/OrderItemNonNeutralTaxesProviderSpec.php index f5aabc88..fe15cc05 100644 --- a/spec/Provider/OrderItemNonNeutralTaxesProviderSpec.php +++ b/spec/Provider/OrderItemNonNeutralTaxesProviderSpec.php @@ -16,7 +16,7 @@ function it_provides_non_neutral_tax_based_on_given_order_item( OrderItemInterface $orderItem, AdjustmentInterface $adjustment, OrderItemUnitInterface $orderItemUnit, - AdjustmentInterface $unitAdjustment + AdjustmentInterface $unitAdjustment, ): void { $orderItem->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT) ->willReturn(new ArrayCollection([$adjustment->getWrappedObject()])); diff --git a/spec/Provider/OrderProviderSpec.php b/spec/Provider/OrderProviderSpec.php index 76cebbd6..f261dbe5 100644 --- a/spec/Provider/OrderProviderSpec.php +++ b/spec/Provider/OrderProviderSpec.php @@ -24,7 +24,7 @@ function it_is_an_order_provider(): void function it_provides_order_by_given_id( OrderRepositoryInterface $orderRepository, - OrderInterface $order + OrderInterface $order, ): void { $orderRepository->find(420)->willReturn($order); @@ -33,7 +33,7 @@ function it_provides_order_by_given_id( function it_provides_order_by_given_token( OrderRepositoryInterface $orderRepository, - OrderInterface $order + OrderInterface $order, ): void { $orderRepository->findOneByTokenValue('token-str')->willReturn($order); @@ -41,7 +41,7 @@ function it_provides_order_by_given_token( } function it_throws_error_if_order_is_not_found_by_id( - OrderRepositoryInterface $orderRepository + OrderRepositoryInterface $orderRepository, ): void { $orderRepository->find(123)->willReturn(null); @@ -49,7 +49,7 @@ function it_throws_error_if_order_is_not_found_by_id( } function it_throws_error_if_order_is_not_found_by_token( - OrderRepositoryInterface $orderRepository + OrderRepositoryInterface $orderRepository, ): void { $orderRepository->findOneByTokenValue('token')->willReturn(null); diff --git a/spec/Provider/PayPalConfigurationProviderSpec.php b/spec/Provider/PayPalConfigurationProviderSpec.php index d4191937..644bacf7 100644 --- a/spec/Provider/PayPalConfigurationProviderSpec.php +++ b/spec/Provider/PayPalConfigurationProviderSpec.php @@ -38,7 +38,7 @@ function it_returns_client_id_from_payment_method_config( PaymentMethodInterface $otherPaymentMethod, GatewayConfigInterface $payPalGatewayConfig, GatewayConfigInterface $otherGatewayConfig, - ChannelInterface $channel + ChannelInterface $channel, ): void { $paymentMethodRepository ->findEnabledForChannel($channel) @@ -62,7 +62,7 @@ function it_returns_partner_attribution_id_from_payment_method_config( PaymentMethodInterface $otherPaymentMethod, GatewayConfigInterface $payPalGatewayConfig, GatewayConfigInterface $otherGatewayConfig, - ChannelInterface $channel + ChannelInterface $channel, ): void { $paymentMethodRepository ->findEnabledForChannel($channel) @@ -84,7 +84,7 @@ function it_throws_an_exception_if_there_is_no_pay_pal_payment_method_defined( PaymentMethodRepositoryInterface $paymentMethodRepository, PaymentMethodInterface $otherPaymentMethod, GatewayConfigInterface $otherGatewayConfig, - ChannelInterface $channel + ChannelInterface $channel, ): void { $paymentMethodRepository->findEnabledForChannel($channel)->willReturn([$otherPaymentMethod]); $otherPaymentMethod->getGatewayConfig()->willReturn($otherGatewayConfig); @@ -107,7 +107,7 @@ function it_throws_an_exception_if_there_is_no_client_id_on_pay_pal_payment_meth PaymentMethodInterface $otherPaymentMethod, GatewayConfigInterface $payPalGatewayConfig, GatewayConfigInterface $otherGatewayConfig, - ChannelInterface $channel + ChannelInterface $channel, ): void { $paymentMethodRepository ->findEnabledForChannel($channel) @@ -134,7 +134,7 @@ function it_throws_an_exception_if_there_is_no_partner_attribution_id_on_pay_pal PaymentMethodInterface $otherPaymentMethod, GatewayConfigInterface $payPalGatewayConfig, GatewayConfigInterface $otherGatewayConfig, - ChannelInterface $channel + ChannelInterface $channel, ): void { $paymentMethodRepository ->findEnabledForChannel($channel) diff --git a/spec/Provider/PayPalItemDataProviderSpec.php b/spec/Provider/PayPalItemDataProviderSpec.php index d4e0430e..daf980f1 100644 --- a/spec/Provider/PayPalItemDataProviderSpec.php +++ b/spec/Provider/PayPalItemDataProviderSpec.php @@ -20,7 +20,7 @@ function let(OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxes function it_returns_array_of_items_with_tax( OrderInterface $order, OrderItemInterface $orderItem, - OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider + OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider, ): void { $order->getItems()->willReturn(new ArrayCollection([$orderItem->getWrappedObject()])); $orderItem->getProductName()->willReturn('PRODUCT_ONE'); @@ -49,14 +49,14 @@ function it_returns_array_of_items_with_tax( ], 'total_item_value' => '20.00', 'total_tax' => '2.00', - ] + ], ); } function it_returns_array_of_items_with_different_quantities_with_tax( OrderInterface $order, OrderItemInterface $orderItem, - OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider + OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider, ): void { $order->getItems()->willReturn(new ArrayCollection([$orderItem->getWrappedObject()])); $orderItem->getProductName()->willReturn('PRODUCT_ONE'); @@ -116,7 +116,7 @@ function it_returns_array_of_items_with_different_quantities_with_tax( function it_returns_array_of_items_with_different_quantities_without_tax( OrderInterface $order, OrderItemInterface $orderItem, - OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider + OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider, ): void { $order->getItems()->willReturn(new ArrayCollection([$orderItem->getWrappedObject()])); $orderItem->getProductName()->willReturn('PRODUCT_ONE'); @@ -153,7 +153,7 @@ function it_returns_array_of_different_items_with_different_quantities_without_t OrderInterface $order, OrderItemInterface $orderItemOne, OrderItemInterface $orderItemTwo, - OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider + OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider, ): void { $order->getItems() ->willReturn(new ArrayCollection([$orderItemOne->getWrappedObject(), $orderItemTwo->getWrappedObject()])); @@ -208,7 +208,7 @@ function it_returns_array_of_different_items_with_different_quantities_with_tax( OrderInterface $order, OrderItemInterface $orderItemOne, OrderItemInterface $orderItemTwo, - OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider + OrderItemNonNeutralTaxesProviderInterface $orderItemNonNeutralTaxesProvider, ): void { $order->getItems()->willReturn(new ArrayCollection([$orderItemOne->getWrappedObject(), $orderItemTwo->getWrappedObject()])); $orderItemOne->getProductName()->willReturn('PRODUCT_ONE'); diff --git a/spec/Provider/PayPalRefundDataProviderSpec.php b/spec/Provider/PayPalRefundDataProviderSpec.php index 2686019c..e5c470c3 100644 --- a/spec/Provider/PayPalRefundDataProviderSpec.php +++ b/spec/Provider/PayPalRefundDataProviderSpec.php @@ -16,7 +16,7 @@ final class PayPalRefundDataProviderSpec extends ObjectBehavior public function let( CacheAuthorizeClientApiInterface $authorizeClientApi, GenericApiInterface $genericApi, - PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider + PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider, ) { $this->beConstructedWith($authorizeClientApi, $genericApi, $payPalPaymentMethodProvider); } @@ -25,7 +25,7 @@ public function it_provides_data_from_provided_url( PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider, PaymentMethodInterface $paymentMethod, CacheAuthorizeClientApiInterface $authorizeClientApi, - GenericApiInterface $genericApi + GenericApiInterface $genericApi, ): void { $payPalPaymentMethodProvider->provide()->willReturn($paymentMethod); $authorizeClientApi->authorize($paymentMethod)->willReturn('TOKEN'); @@ -47,7 +47,7 @@ public function it_throws_error_if_paypal_data_doesnt_contain_url( PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider, PaymentMethodInterface $paymentMethod, CacheAuthorizeClientApiInterface $authorizeClientApi, - GenericApiInterface $genericApi + GenericApiInterface $genericApi, ): void { $payPalPaymentMethodProvider->provide()->willReturn($paymentMethod); $authorizeClientApi->authorize($paymentMethod)->willReturn('TOKEN'); diff --git a/spec/Provider/PaymentProviderSpec.php b/spec/Provider/PaymentProviderSpec.php index 128ea4dc..91fc3ee3 100644 --- a/spec/Provider/PaymentProviderSpec.php +++ b/spec/Provider/PaymentProviderSpec.php @@ -35,7 +35,7 @@ function it_returns_payment_for_given_pay_pal_order_id( PaymentRepositoryInterface $paymentRepository, PaymentInterface $firstPayment, PaymentInterface $secondPayment, - PaymentInterface $thirdPayment + PaymentInterface $thirdPayment, ): void { $paymentRepository->findAll()->willReturn([$firstPayment, $secondPayment, $thirdPayment]); @@ -50,7 +50,7 @@ function it_throws_exception_if_there_is_no_payment_with_given_paypal_order_id( PaymentRepositoryInterface $paymentRepository, PaymentInterface $firstPayment, PaymentInterface $secondPayment, - PaymentInterface $thirdPayment + PaymentInterface $thirdPayment, ): void { $paymentRepository->findAll()->willReturn([$firstPayment, $secondPayment, $thirdPayment]); diff --git a/spec/Registrar/SellerWebhookRegistrarSpec.php b/spec/Registrar/SellerWebhookRegistrarSpec.php index 8f8a0792..1a386aed 100644 --- a/spec/Registrar/SellerWebhookRegistrarSpec.php +++ b/spec/Registrar/SellerWebhookRegistrarSpec.php @@ -27,7 +27,7 @@ final class SellerWebhookRegistrarSpec extends ObjectBehavior function let( AuthorizeClientApiInterface $authorizeClientApi, UrlGeneratorInterface $urlGenerator, - WebhookApiInterface $webhookApi + WebhookApiInterface $webhookApi, ): void { $this->beConstructedWith($authorizeClientApi, $urlGenerator, $webhookApi); } @@ -42,7 +42,7 @@ function it_registers_sellers_webhook( UrlGeneratorInterface $urlGenerator, WebhookApiInterface $webhookApi, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn(['client_id' => 'CLIENT_ID', 'client_secret' => 'CLIENT_SECRET']); @@ -63,7 +63,7 @@ function it_throws_exception_if_webhook_could_not_be_registered( UrlGeneratorInterface $urlGenerator, WebhookApiInterface $webhookApi, PaymentMethodInterface $paymentMethod, - GatewayConfigInterface $gatewayConfig + GatewayConfigInterface $gatewayConfig, ): void { $paymentMethod->getGatewayConfig()->willReturn($gatewayConfig); $gatewayConfig->getConfig()->willReturn(['client_id' => 'CLIENT_ID', 'client_secret' => 'CLIENT_SECRET']); diff --git a/spec/Resolver/CapturePaymentResolverSpec.php b/spec/Resolver/CapturePaymentResolverSpec.php index b46f2930..1665779f 100644 --- a/spec/Resolver/CapturePaymentResolverSpec.php +++ b/spec/Resolver/CapturePaymentResolverSpec.php @@ -31,7 +31,7 @@ function it_executes_capture_action_on_payment( PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, GatewayInterface $gateway, - Payum $payum + Payum $payum, ): void { $payment->getMethod()->willReturn($paymentMethod); diff --git a/spec/Resolver/CompleteOrderPaymentResolverSpec.php b/spec/Resolver/CompleteOrderPaymentResolverSpec.php index 27f04446..0ac64e9d 100644 --- a/spec/Resolver/CompleteOrderPaymentResolverSpec.php +++ b/spec/Resolver/CompleteOrderPaymentResolverSpec.php @@ -31,7 +31,7 @@ function it_executes_complete_order_action_on_payment( PaymentMethodInterface $paymentMethod, GatewayConfigInterface $gatewayConfig, GatewayInterface $gateway, - Payum $payum + Payum $payum, ): void { $payment->getMethod()->willReturn($paymentMethod); @@ -41,13 +41,15 @@ function it_executes_complete_order_action_on_payment( $payum->getGateway('gateway-12')->willReturn($gateway); $gateway->execute( - Argument::that(function (CompleteOrder $request) use ($payment): bool { - return - $request->getModel() === $payment->getWrappedObject() && - $request->getOrderId() === 'paypal-order-id' - ; - }, - ))->shouldBeCalled(); + Argument::that( + function (CompleteOrder $request) use ($payment): bool { + return + $request->getModel() === $payment->getWrappedObject() && + $request->getOrderId() === 'paypal-order-id' + ; + }, + ), + )->shouldBeCalled(); $this->resolve($payment, 'paypal-order-id'); } diff --git a/spec/Resolver/PayPalDefaultPaymentMethodResolverSpec.php b/spec/Resolver/PayPalDefaultPaymentMethodResolverSpec.php index 38f43c45..e9aad5f6 100644 --- a/spec/Resolver/PayPalDefaultPaymentMethodResolverSpec.php +++ b/spec/Resolver/PayPalDefaultPaymentMethodResolverSpec.php @@ -43,7 +43,7 @@ function it_returns_prioritised_payment_method_for_channel( GatewayConfigInterface $firstGatewayConfig, GatewayConfigInterface $secondGatewayConfig, PaymentInterface $subject, - OrderInterface $order + OrderInterface $order, ): void { $firstPayment->getGatewayConfig()->willReturn($firstGatewayConfig); $firstGatewayConfig->getFactoryName()->willReturn('new.payment'); @@ -67,7 +67,7 @@ function it_returns_first_available_payment_method_if_priotitised_payment_method GatewayConfigInterface $firstGatewayConfig, GatewayConfigInterface $secondGatewayConfig, PaymentInterface $subject, - OrderInterface $order + OrderInterface $order, ): void { $firstPayment->getGatewayConfig()->willReturn($firstGatewayConfig); $firstGatewayConfig->getFactoryName()->willReturn('payment1'); @@ -87,7 +87,7 @@ function it_throws_error_if_there_is_no_available_payment( PaymentMethodRepositoryInterface $paymentMethodRepository, ChannelInterface $channel, PaymentInterface $subject, - OrderInterface $order + OrderInterface $order, ): void { $paymentMethodRepository->findEnabledForChannel($channel)->willReturn([]); diff --git a/spec/Resolver/PayPalPrioritisingPaymentMethodsResolverSpec.php b/spec/Resolver/PayPalPrioritisingPaymentMethodsResolverSpec.php index 9d6126e8..1c50f9f7 100644 --- a/spec/Resolver/PayPalPrioritisingPaymentMethodsResolverSpec.php +++ b/spec/Resolver/PayPalPrioritisingPaymentMethodsResolverSpec.php @@ -30,7 +30,7 @@ function it_prioritizes_payment_method( PaymentMethodInterface $thirdPayment, GatewayConfigInterface $firstGatewayConfig, GatewayConfigInterface $secondGatewayConfig, - GatewayConfigInterface $thirdGatewayConfig + GatewayConfigInterface $thirdGatewayConfig, ): void { $firstPayment->getGatewayConfig()->willReturn($firstGatewayConfig); $firstGatewayConfig->getFactoryName()->willReturn('payment1'); @@ -44,7 +44,7 @@ function it_prioritizes_payment_method( $paymentMethodsResolver->getSupportedMethods($payment)->willReturn([$firstPayment, $secondPayment, $thirdPayment]); $this->getSupportedMethods($payment)->shouldReturn( - [$thirdPayment, $firstPayment, $secondPayment] + [$thirdPayment, $firstPayment, $secondPayment], ); } @@ -56,7 +56,7 @@ function it_does_nothing_if_prioritized_payment_is_not_available( PaymentMethodInterface $thirdPayment, GatewayConfigInterface $firstGatewayConfig, GatewayConfigInterface $secondGatewayConfig, - GatewayConfigInterface $thirdGatewayConfig + GatewayConfigInterface $thirdGatewayConfig, ): void { $firstPayment->getGatewayConfig()->willReturn($firstGatewayConfig); $firstGatewayConfig->getFactoryName()->willReturn('payment1'); @@ -70,7 +70,7 @@ function it_does_nothing_if_prioritized_payment_is_not_available( $paymentMethodsResolver->getSupportedMethods($payment)->willReturn([$firstPayment, $secondPayment, $thirdPayment]); $this->getSupportedMethods($payment)->shouldReturn( - [$firstPayment, $secondPayment, $thirdPayment] + [$firstPayment, $secondPayment, $thirdPayment], ); } } diff --git a/spec/Updater/PayPalPaymentUpdaterSpec.php b/spec/Updater/PayPalPaymentUpdaterSpec.php index a2dc15a4..1eab6aef 100644 --- a/spec/Updater/PayPalPaymentUpdaterSpec.php +++ b/spec/Updater/PayPalPaymentUpdaterSpec.php @@ -32,7 +32,7 @@ function it_implements_payment_updater_interface(): void function it_updates_payment_amount( ObjectManager $paymentManager, - PaymentInterface $payment + PaymentInterface $payment, ): void { $payment->setAmount(1000)->shouldBeCalled(); $paymentManager->flush(); diff --git a/src/Api/CacheAuthorizeClientApi.php b/src/Api/CacheAuthorizeClientApi.php index 68ebf0c3..2bcc54e7 100644 --- a/src/Api/CacheAuthorizeClientApi.php +++ b/src/Api/CacheAuthorizeClientApi.php @@ -35,7 +35,7 @@ public function __construct( ObjectManager $payPalCredentialsManager, ObjectRepository $payPalCredentialsRepository, AuthorizeClientApiInterface $authorizeClientApi, - UuidProviderInterface $uuidProvider + UuidProviderInterface $uuidProvider, ) { $this->payPalCredentialsManager = $payPalCredentialsManager; $this->payPalCredentialsRepository = $payPalCredentialsRepository; @@ -61,10 +61,15 @@ public function authorize(PaymentMethodInterface $paymentMethod): string $config = $gatewayConfig->getConfig(); $token = $this->authorizeClientApi->authorize( - (string) $config['client_id'], (string) $config['client_secret'] + (string) $config['client_id'], + (string) $config['client_secret'], ); $payPalCredentials = new PayPalCredentials( - $this->uuidProvider->provide(), $paymentMethod, $token, new \DateTime(), 3600 + $this->uuidProvider->provide(), + $paymentMethod, + $token, + new \DateTime(), + 3600, ); $this->payPalCredentialsManager->persist($payPalCredentials); diff --git a/src/Api/CreateOrderApi.php b/src/Api/CreateOrderApi.php index 743d6b4b..39f46be9 100644 --- a/src/Api/CreateOrderApi.php +++ b/src/Api/CreateOrderApi.php @@ -26,7 +26,7 @@ final class CreateOrderApi implements CreateOrderApiInterface { - const PAYPAL_INTENT_CAPTURE = 'CAPTURE'; + public const PAYPAL_INTENT_CAPTURE = 'CAPTURE'; private PayPalClientInterface $client; @@ -37,7 +37,7 @@ final class CreateOrderApi implements CreateOrderApiInterface public function __construct( PayPalClientInterface $client, PaymentReferenceNumberProviderInterface $paymentReferenceNumberProvider, - PayPalItemDataProviderInterface $payPalItemDataProvider + PayPalItemDataProviderInterface $payPalItemDataProvider, ) { $this->client = $client; $this->paymentReferenceNumberProvider = $paymentReferenceNumberProvider; @@ -74,7 +74,7 @@ public function create(string $token, PaymentInterface $payment, string $referen (string) $config['merchant_id'], (array) $payPalItemData['items'], $order->isShippingRequired(), - $order->getShippingAddress() + $order->getShippingAddress(), ); $payPalOrder = new PayPalOrder($order, $payPalPurchaseUnit, self::PAYPAL_INTENT_CAPTURE); diff --git a/src/Api/GenericApi.php b/src/Api/GenericApi.php index d8fc5788..fb0e137c 100644 --- a/src/Api/GenericApi.php +++ b/src/Api/GenericApi.php @@ -4,18 +4,49 @@ namespace Sylius\PayPalPlugin\Api; -use GuzzleHttp\ClientInterface; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; final class GenericApi implements GenericApiInterface { - private ClientInterface $client; + public function __construct( + private readonly GuzzleClientInterface|ClientInterface $client, + private readonly ?RequestFactoryInterface $requestFactory = null, + ) { + if ($this->client instanceof GuzzleClientInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Passing GuzzleHttp\ClientInterface as a first argument in the constructor is deprecated and will prohibited in 2.0. Use Psr\Http\Client\ClientInterface instead.', + ); + } - public function __construct(ClientInterface $client) - { - $this->client = $client; + if (null === $this->requestFactory) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Not passing $requestFactory to %s constructor is deprecated and will be prohibited in 2.0', + self::class, + ); + } } public function get(string $token, string $url): array + { + if ($this->client instanceof GuzzleClientInterface || null === $this->requestFactory) { + return $this->legacyGet($token, $url); + } + + $request = $this->requestFactory->createRequest('GET', $url) + ->withHeader('Authorization', 'Bearer ' . $token) + ->withHeader('Content-Type', 'application/json') + ->withHeader('Accept', 'application/json'); + + return (array) json_decode($this->client->sendRequest($request)->getBody()->getContents(), true); + } + + private function legacyGet(string $token, string $url): array { $response = $this->client->request('GET', $url, [ 'headers' => [ diff --git a/src/Api/RefundPaymentApi.php b/src/Api/RefundPaymentApi.php index 35ac8211..afc5211a 100644 --- a/src/Api/RefundPaymentApi.php +++ b/src/Api/RefundPaymentApi.php @@ -30,13 +30,13 @@ public function refund( string $payPalAuthAssertion, string $invoiceNumber, string $amount, - string $currencyCode + string $currencyCode, ): array { return $this->client->post( sprintf('v2/payments/captures/%s/refund', $paymentId), $token, ['amount' => ['value' => $amount, 'currency_code' => $currencyCode], 'invoice_number' => $invoiceNumber], - ['PayPal-Auth-Assertion' => $payPalAuthAssertion] + ['PayPal-Auth-Assertion' => $payPalAuthAssertion], ); } } diff --git a/src/Api/RefundPaymentApiInterface.php b/src/Api/RefundPaymentApiInterface.php index 3f7fde7b..40422c0e 100644 --- a/src/Api/RefundPaymentApiInterface.php +++ b/src/Api/RefundPaymentApiInterface.php @@ -12,6 +12,6 @@ public function refund( string $payPalAuthAssertion, string $invoiceNumber, string $amount, - string $currencyCode + string $currencyCode, ): array; } diff --git a/src/Api/UpdateOrderApi.php b/src/Api/UpdateOrderApi.php index d659722e..06bece25 100644 --- a/src/Api/UpdateOrderApi.php +++ b/src/Api/UpdateOrderApi.php @@ -13,7 +13,6 @@ namespace Sylius\PayPalPlugin\Api; -use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Core\Model\PaymentInterface; use Sylius\PayPalPlugin\Client\PayPalClientInterface; @@ -32,7 +31,7 @@ final class UpdateOrderApi implements UpdateOrderApiInterface public function __construct( PayPalClientInterface $client, PaymentReferenceNumberProviderInterface $paymentReferenceNumberProvider, - PayPalItemDataProviderInterface $payPalItemsDataProvider + PayPalItemDataProviderInterface $payPalItemsDataProvider, ) { $this->client = $client; $this->paymentReferenceNumberProvider = $paymentReferenceNumberProvider; @@ -44,7 +43,7 @@ public function update( string $orderId, PaymentInterface $payment, string $referenceId, - string $merchantId + string $merchantId, ): array { /** @var OrderInterface $order */ $order = $payment->getOrder(); @@ -63,7 +62,7 @@ public function update( $merchantId, (array) $payPalItemData['items'], $order->isShippingRequired(), - $order->getShippingAddress() + $order->getShippingAddress(), ); return $this->client->patch( @@ -75,7 +74,7 @@ public function update( 'path' => sprintf('/purchase_units/@reference_id==\'%s\'', $referenceId), 'value' => $data->toArray(), ], - ] + ], ); } } diff --git a/src/Api/UpdateOrderApiInterface.php b/src/Api/UpdateOrderApiInterface.php index f859d503..427beda3 100644 --- a/src/Api/UpdateOrderApiInterface.php +++ b/src/Api/UpdateOrderApiInterface.php @@ -13,6 +13,6 @@ public function update( string $orderId, PaymentInterface $payment, string $referenceId, - string $merchantId + string $merchantId, ): array; } diff --git a/src/Api/WebhookApi.php b/src/Api/WebhookApi.php index 89c0be6f..871821fe 100644 --- a/src/Api/WebhookApi.php +++ b/src/Api/WebhookApi.php @@ -4,21 +4,68 @@ namespace Sylius\PayPalPlugin\Api; -use GuzzleHttp\ClientInterface; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; +use Psr\Http\Message\StreamFactoryInterface; final class WebhookApi implements WebhookApiInterface { - private ClientInterface $client; + public function __construct( + private readonly GuzzleClientInterface|ClientInterface $client, + private readonly string $baseUrl, + private readonly ?RequestFactoryInterface $requestFactory = null, + private readonly ?StreamFactoryInterface $streamFactory = null, + ) { + if ($this->client instanceof GuzzleClientInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Passing GuzzleHttp\ClientInterface as a first argument in the constructor is deprecated and will be prohibited in 2.0. Use Psr\Http\Client\ClientInterface instead.', + self::class, + ); + } - private string $baseUrl; + if (null === $this->requestFactory || null === $this->streamFactory) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Not passing $requestFactory and $streamFactory to %s constructor is deprecated and will be prohibited in 2.0', + self::class, + ); + } + } - public function __construct(ClientInterface $client, string $baseUrl) + public function register(string $token, string $webhookUrl): array { - $this->client = $client; - $this->baseUrl = $baseUrl; + if ($this->client instanceof GuzzleClientInterface || null === $this->requestFactory || null === $this->streamFactory) { + return $this->legacyRegister($token, $webhookUrl); + } + + $request = $this->requestFactory->createRequest('POST', $this->baseUrl . 'v1/notifications/webhooks') + ->withHeader('Authorization', 'Bearer ' . $token) + ->withHeader('Content-Type', 'application/json') + ->withHeader('Accept', 'application/json'); + + $request = $request->withBody( + $this->streamFactory->createStream( + json_encode( + [ + 'url' => preg_replace('/^http:/i', 'https:', $webhookUrl), + 'event_types' => [ + ['name' => 'PAYMENT.CAPTURE.REFUNDED'], + ], + ], + ), + ), + ); + + $response = $this->client->sendRequest($request); + + return (array) json_decode($response->getBody()->getContents(), true); } - public function register(string $token, string $webhookUrl): array + private function legacyRegister(string $token, string $webhookUrl): array { $response = $this->client->request('POST', $this->baseUrl . 'v1/notifications/webhooks', [ 'headers' => [ diff --git a/src/ApiPlatform/PayPalPayment.php b/src/ApiPlatform/PayPalPayment.php index 1be17b57..6a739e3b 100644 --- a/src/ApiPlatform/PayPalPayment.php +++ b/src/ApiPlatform/PayPalPayment.php @@ -63,12 +63,12 @@ public function provideConfiguration(PaymentInterface $payment): array 'completePayPalOrderFromPaymentPageUrl' => $this->router->generate( 'sylius_paypal_plugin_complete_paypal_order', ['token' => $order->getTokenValue()], - UrlGeneratorInterface::ABSOLUTE_URL + UrlGeneratorInterface::ABSOLUTE_URL, ), 'createPayPalOrderFromPaymentPageUrl' => $this->router->generate( 'sylius_paypal_plugin_create_paypal_order', ['token' => $order->getTokenValue()], - UrlGeneratorInterface::ABSOLUTE_URL + UrlGeneratorInterface::ABSOLUTE_URL, ), 'cancelPayPalPaymentUrl' => $this->router->generate('sylius_paypal_plugin_cancel_payment', [], UrlGeneratorInterface::ABSOLUTE_URL), 'partnerAttributionId' => $gatewayConfig->getConfig()['partner_attribution_id'], diff --git a/src/Client/PayPalClient.php b/src/Client/PayPalClient.php index a4935bc3..5ab8d73c 100644 --- a/src/Client/PayPalClient.php +++ b/src/Client/PayPalClient.php @@ -13,10 +13,13 @@ namespace Sylius\PayPalPlugin\Client; -use GuzzleHttp\ClientInterface; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\StreamFactoryInterface; use Psr\Log\LoggerInterface; use Sylius\Component\Channel\Context\ChannelContextInterface; use Sylius\Component\Core\Model\ChannelInterface; @@ -27,40 +30,35 @@ final class PayPalClient implements PayPalClientInterface { - private ClientInterface $client; - - private LoggerInterface $logger; - - private UuidProviderInterface $uuidProvider; - - private PayPalConfigurationProviderInterface $payPalConfigurationProvider; - - private ChannelContextInterface $channelContext; - - private string $baseUrl; - - private int $requestTrialsLimit; - - private bool $loggingLevelIncreased; - public function __construct( - ClientInterface $client, - LoggerInterface $logger, - UuidProviderInterface $uuidProvider, - PayPalConfigurationProviderInterface $payPalConfigurationProvider, - ChannelContextInterface $channelContext, - string $baseUrl, - int $requestTrialsLimit, - bool $loggingLevelIncreased = false + private readonly GuzzleClientInterface|ClientInterface $client, + private readonly LoggerInterface $logger, + private readonly UuidProviderInterface $uuidProvider, + private readonly PayPalConfigurationProviderInterface $payPalConfigurationProvider, + private readonly ChannelContextInterface $channelContext, + private readonly string $baseUrl, + private int $requestTrialsLimit, + private readonly bool $loggingLevelIncreased = false, + private readonly ?RequestFactoryInterface $requestFactory = null, + private readonly ?StreamFactoryInterface $streamFactory = null, ) { - $this->client = $client; - $this->logger = $logger; - $this->uuidProvider = $uuidProvider; - $this->payPalConfigurationProvider = $payPalConfigurationProvider; - $this->channelContext = $channelContext; - $this->baseUrl = $baseUrl; - $this->requestTrialsLimit = $requestTrialsLimit; - $this->loggingLevelIncreased = $loggingLevelIncreased; + if ($this->client instanceof GuzzleClientInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Passing GuzzleHttp\ClientInterface as a first argument in the constructor is deprecated and will be prohibited in 2.0. Use Psr\Http\Client\ClientInterface instead.', + self::class, + ); + } + + if (null === $this->requestFactory || null === $this->streamFactory) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Not passing $requestFactory and $streamFactory to %s constructor is deprecated and will be prohibited in 2.0', + self::class, + ); + } } public function authorize(string $clientId, string $clientSecret): array @@ -71,7 +69,7 @@ public function authorize(string $clientId, string $clientSecret): array [ 'auth' => [$clientId, $clientSecret], 'form_params' => ['grant_type' => 'client_credentials'], - ] + ], ); if ($response->getStatusCode() !== 200) { @@ -145,7 +143,49 @@ private function request(string $method, string $url, string $token, array $data private function doRequest(string $method, string $fullUrl, array $options): ResponseInterface { try { - $response = $this->client->request($method, $fullUrl, $options); + if ($this->client instanceof GuzzleClientInterface || null === $this->requestFactory || null === $this->streamFactory) { + $response = $this->client->request($method, $fullUrl, $options); + } else { + $request = $this->requestFactory->createRequest($method, $fullUrl); + + if (isset($options['auth'])) { + $request = $request->withHeader( + 'Authorization', + sprintf( + 'Basic %s', + base64_encode(sprintf('%s:%s', $options['auth'][0], $options['auth'][1])), + ), + ); + } + + if (isset($options['form_params'])) { + $request = $request->withHeader('Content-Type', 'application/x-www-form-urlencoded'); + $request = $request->withBody( + $this->streamFactory->createStream( + http_build_query( + $options['form_params'], + '', + '&', + \PHP_QUERY_RFC1738, + ), + ), + ); + } + + if (isset($options['json'])) { + $request = $request->withBody( + $this->streamFactory->createStream(json_encode($options['json'])), + ); + } + + if (isset($options['headers'])) { + foreach ($options['headers'] as $header => $headerValue) { + $request = $request->withHeader($header, $headerValue); + } + } + + $response = $this->client->sendRequest($request); + } } catch (ConnectException $exception) { --$this->requestTrialsLimit; if ($this->requestTrialsLimit === 0) { diff --git a/src/Command/CompletePaidPaymentsCommand.php b/src/Command/CompletePaidPaymentsCommand.php index 931077bb..1d4b2df9 100644 --- a/src/Command/CompletePaidPaymentsCommand.php +++ b/src/Command/CompletePaidPaymentsCommand.php @@ -7,6 +7,8 @@ use Doctrine\Persistence\ObjectManager; use Payum\Core\Model\GatewayConfigInterface; use SM\Factory\FactoryInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Component\Core\Model\PaymentInterface; use Sylius\Component\Core\Model\PaymentMethodInterface; use Sylius\Component\Core\Repository\PaymentRepositoryInterface; @@ -20,30 +22,26 @@ final class CompletePaidPaymentsCommand extends Command { - private PaymentRepositoryInterface $paymentRepository; - - private ObjectManager $paymentManager; - - private CacheAuthorizeClientApiInterface $authorizeClientApi; - - private OrderDetailsApiInterface $orderDetailsApi; - - private FactoryInterface $stateMachineFactory; - public function __construct( - PaymentRepositoryInterface $paymentRepository, - ObjectManager $paymentManager, - CacheAuthorizeClientApiInterface $authorizeClientApi, - OrderDetailsApiInterface $orderDetailsApi, - FactoryInterface $stateMachineFactory + private readonly PaymentRepositoryInterface $paymentRepository, + private readonly ObjectManager $paymentManager, + private readonly CacheAuthorizeClientApiInterface $authorizeClientApi, + private readonly OrderDetailsApiInterface $orderDetailsApi, + private readonly FactoryInterface|StateMachineInterface $stateMachineFactory, ) { parent::__construct(); - $this->paymentRepository = $paymentRepository; - $this->paymentManager = $paymentManager; - $this->authorizeClientApi = $authorizeClientApi; - $this->orderDetailsApi = $orderDetailsApi; - $this->stateMachineFactory = $stateMachineFactory; + if ($this->stateMachineFactory instanceof FactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the fifth argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + FactoryInterface::class, + StateMachineInterface::class, + ), + ); + } } protected function configure(): void @@ -74,8 +72,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $details = $this->orderDetailsApi->get($token, $payPalOrderId); if ($details['status'] === 'COMPLETED') { - $stateMachine = $this->stateMachineFactory->get($payment, PaymentTransitions::GRAPH); - $stateMachine->apply(PaymentTransitions::TRANSITION_COMPLETE); + $this->getStateMachine()->apply($payment, PaymentTransitions::GRAPH, PaymentTransitions::TRANSITION_COMPLETE); $paymentDetails = $payment->getDetails(); $paymentDetails['status'] = StatusAction::STATUS_COMPLETED; @@ -88,4 +85,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int return 0; } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachineFactory instanceof FactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachineFactory); + } + + return $this->stateMachineFactory; + } } diff --git a/src/Controller/CancelLastPayPalPaymentAction.php b/src/Controller/CancelLastPayPalPaymentAction.php index 9d587293..dfb33f8d 100644 --- a/src/Controller/CancelLastPayPalPaymentAction.php +++ b/src/Controller/CancelLastPayPalPaymentAction.php @@ -6,6 +6,8 @@ use Doctrine\Persistence\ObjectManager; use SM\Factory\FactoryInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Core\Model\PaymentInterface; use Sylius\Component\Core\Repository\OrderRepositoryInterface; @@ -16,28 +18,23 @@ final class CancelLastPayPalPaymentAction { - /** @var ObjectManager */ - private $objectManager; - - /** @var FactoryInterface */ - private $stateMachineFactory; - - /** @var OrderProcessorInterface */ - private $orderPaymentProcessor; - - /** @var OrderRepositoryInterface */ - private $orderRepository; - public function __construct( - ObjectManager $objectManager, - FactoryInterface $stateMachineFactory, - OrderProcessorInterface $orderPaymentProcessor, - OrderRepositoryInterface $orderRepository + private readonly ObjectManager $objectManager, + private readonly FactoryInterface|StateMachineInterface $stateMachineFactory, + private readonly OrderProcessorInterface $orderPaymentProcessor, + private readonly OrderRepositoryInterface $orderRepository, ) { - $this->objectManager = $objectManager; - $this->stateMachineFactory = $stateMachineFactory; - $this->orderPaymentProcessor = $orderPaymentProcessor; - $this->orderRepository = $orderRepository; + if ($this->stateMachineFactory instanceof FactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the second argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + FactoryInterface::class, + StateMachineInterface::class, + ), + ); + } } public function __invoke(Request $request): Response @@ -48,12 +45,28 @@ public function __invoke(Request $request): Response /** @var PaymentInterface $payment */ $payment = $order->getLastPayment(); - $paymentStateMachine = $this->stateMachineFactory->get($payment, PaymentTransitions::GRAPH); - $paymentStateMachine->apply(PaymentTransitions::TRANSITION_CANCEL); + $this->getStateMachine()->apply($payment, PaymentTransitions::GRAPH, PaymentTransitions::TRANSITION_CANCEL); + + /** @var PaymentInterface $lastPayment */ + $lastPayment = $order->getLastPayment(); + if ($lastPayment->getState() === PaymentInterface::STATE_NEW) { + $this->objectManager->flush(); + + return new Response('', Response::HTTP_NO_CONTENT); + } $this->orderPaymentProcessor->process($order); $this->objectManager->flush(); return new Response('', Response::HTTP_NO_CONTENT); } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachineFactory instanceof FactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachineFactory); + } + + return $this->stateMachineFactory; + } } diff --git a/src/Controller/CancelPayPalCheckoutPaymentAction.php b/src/Controller/CancelPayPalCheckoutPaymentAction.php index 0020c599..f43b842e 100644 --- a/src/Controller/CancelPayPalCheckoutPaymentAction.php +++ b/src/Controller/CancelPayPalCheckoutPaymentAction.php @@ -18,7 +18,7 @@ final class CancelPayPalCheckoutPaymentAction public function __construct( PaymentProviderInterface $paymentProvider, - PaymentStateManagerInterface $paymentStateManager + PaymentStateManagerInterface $paymentStateManager, ) { $this->paymentProvider = $paymentProvider; $this->paymentStateManager = $paymentStateManager; @@ -28,7 +28,6 @@ public function __invoke(Request $request): Response { /** * @var string $content - * @psalm-suppress UnnecessaryVarAnnotation */ $content = $request->getContent(); diff --git a/src/Controller/CancelPayPalOrderAction.php b/src/Controller/CancelPayPalOrderAction.php index ea5d15bc..b4760c4a 100644 --- a/src/Controller/CancelPayPalOrderAction.php +++ b/src/Controller/CancelPayPalOrderAction.php @@ -24,7 +24,7 @@ final class CancelPayPalOrderAction public function __construct( PaymentProviderInterface $paymentProvider, OrderRepositoryInterface $orderRepository, - FlashBag|RequestStack $flashBagOrRequestStack + FlashBag|RequestStack $flashBagOrRequestStack, ) { if ($flashBagOrRequestStack instanceof FlashBag) { trigger_deprecation('sylius/paypal-plugin', '1.5', sprintf('Passing an instance of %s as constructor argument for %s is deprecated as of PayPalPlugin 1.5 and will be removed in 2.0. Pass an instance of %s instead.', FlashBag::class, self::class, RequestStack::class)); @@ -39,7 +39,6 @@ public function __invoke(Request $request): Response { /** * @var string $content - * @psalm-suppress UnnecessaryVarAnnotation */ $content = $request->getContent(); diff --git a/src/Controller/CancelPayPalPaymentAction.php b/src/Controller/CancelPayPalPaymentAction.php index 33c407e8..e9aa986a 100644 --- a/src/Controller/CancelPayPalPaymentAction.php +++ b/src/Controller/CancelPayPalPaymentAction.php @@ -6,6 +6,8 @@ use Doctrine\Persistence\ObjectManager; use SM\Factory\FactoryInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Order\Processor\OrderProcessorInterface; use Sylius\Component\Payment\PaymentTransitions; @@ -18,39 +20,34 @@ final class CancelPayPalPaymentAction { - private PaymentProviderInterface $paymentProvider; - - private ObjectManager $objectManager; - - private FlashBag|RequestStack $flashBagOrRequestStack; - - private FactoryInterface $stateMachineFactory; - - private OrderProcessorInterface $orderPaymentProcessor; - public function __construct( - PaymentProviderInterface $paymentProvider, - ObjectManager $objectManager, - FlashBag|RequestStack $flashBagOrRequestStack, - FactoryInterface $stateMachineFactory, - OrderProcessorInterface $orderPaymentProcessor + private readonly PaymentProviderInterface $paymentProvider, + private readonly ObjectManager $objectManager, + private readonly FlashBag|RequestStack $flashBagOrRequestStack, + private readonly FactoryInterface|StateMachineInterface $stateMachineFactory, + private readonly OrderProcessorInterface $orderPaymentProcessor, ) { if ($flashBagOrRequestStack instanceof FlashBag) { trigger_deprecation('sylius/paypal-plugin', '1.5', sprintf('Passing an instance of %s as constructor argument for %s is deprecated as of PayPalPlugin 1.5 and will be removed in 2.0. Pass an instance of %s instead.', FlashBag::class, self::class, RequestStack::class)); } - $this->paymentProvider = $paymentProvider; - $this->objectManager = $objectManager; - $this->flashBagOrRequestStack = $flashBagOrRequestStack; - $this->stateMachineFactory = $stateMachineFactory; - $this->orderPaymentProcessor = $orderPaymentProcessor; + if ($this->stateMachineFactory instanceof FactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the fourth argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + FactoryInterface::class, + StateMachineInterface::class, + ), + ); + } } public function __invoke(Request $request): Response { /** * @var string $content - * @psalm-suppress UnnecessaryVarAnnotation */ $content = $request->getContent(); @@ -61,8 +58,7 @@ public function __invoke(Request $request): Response /** @var OrderInterface $order */ $order = $payment->getOrder(); - $paymentStateMachine = $this->stateMachineFactory->get($payment, PaymentTransitions::GRAPH); - $paymentStateMachine->apply(PaymentTransitions::TRANSITION_CANCEL); + $this->getStateMachine()->apply($payment, PaymentTransitions::GRAPH, PaymentTransitions::TRANSITION_CANCEL); $this->orderPaymentProcessor->process($order); $this->objectManager->flush(); @@ -73,4 +69,13 @@ public function __invoke(Request $request): Response return new Response('', Response::HTTP_NO_CONTENT); } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachineFactory instanceof FactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachineFactory); + } + + return $this->stateMachineFactory; + } } diff --git a/src/Controller/CompletePayPalOrderAction.php b/src/Controller/CompletePayPalOrderAction.php index 453b5f1e..24e6af9a 100644 --- a/src/Controller/CompletePayPalOrderAction.php +++ b/src/Controller/CompletePayPalOrderAction.php @@ -23,7 +23,7 @@ final class CompletePayPalOrderAction public function __construct( PaymentStateManagerInterface $paymentStateManager, UrlGeneratorInterface $router, - OrderProviderInterface $orderProvider + OrderProviderInterface $orderProvider, ) { $this->paymentStateManager = $paymentStateManager; $this->router = $router; diff --git a/src/Controller/CompletePayPalOrderFromPaymentPageAction.php b/src/Controller/CompletePayPalOrderFromPaymentPageAction.php index 44fc735e..b34b0a2c 100644 --- a/src/Controller/CompletePayPalOrderFromPaymentPageAction.php +++ b/src/Controller/CompletePayPalOrderFromPaymentPageAction.php @@ -6,7 +6,8 @@ use Doctrine\Persistence\ObjectManager; use SM\Factory\FactoryInterface; -use Sylius\Component\Core\Model\OrderInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Component\Core\Model\PaymentInterface; use Sylius\Component\Core\OrderCheckoutTransitions; use Sylius\PayPalPlugin\Manager\PaymentStateManagerInterface; @@ -18,28 +19,24 @@ final class CompletePayPalOrderFromPaymentPageAction { - private PaymentStateManagerInterface $paymentStateManager; - - private UrlGeneratorInterface $router; - - private OrderProviderInterface $orderProvider; - - private FactoryInterface $stateMachine; - - private ObjectManager $orderManager; - public function __construct( - PaymentStateManagerInterface $paymentStateManager, - UrlGeneratorInterface $router, - OrderProviderInterface $orderProvider, - FactoryInterface $stateMachine, - ObjectManager $orderManager + private readonly PaymentStateManagerInterface $paymentStateManager, + private readonly UrlGeneratorInterface $router, + private readonly OrderProviderInterface $orderProvider, + private readonly FactoryInterface|StateMachineInterface $stateMachine, + private readonly ObjectManager $orderManager, ) { - $this->paymentStateManager = $paymentStateManager; - $this->router = $router; - $this->orderProvider = $orderProvider; - $this->stateMachine = $stateMachine; - $this->orderManager = $orderManager; + if ($this->stateMachine instanceof FactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the fourth argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + FactoryInterface::class, + StateMachineInterface::class, + ), + ); + } } public function __invoke(Request $request): Response @@ -52,9 +49,8 @@ public function __invoke(Request $request): Response $this->paymentStateManager->complete($payment); - $orderStateMachine = $this->stateMachine->get($order, OrderCheckoutTransitions::GRAPH); - $orderStateMachine->apply(OrderCheckoutTransitions::TRANSITION_SELECT_PAYMENT); - $orderStateMachine->apply(OrderCheckoutTransitions::TRANSITION_COMPLETE); + $this->getStateMachine()->apply($order, OrderCheckoutTransitions::GRAPH, OrderCheckoutTransitions::TRANSITION_SELECT_PAYMENT); + $this->getStateMachine()->apply($order, OrderCheckoutTransitions::GRAPH, OrderCheckoutTransitions::TRANSITION_COMPLETE); $this->orderManager->flush(); @@ -64,4 +60,13 @@ public function __invoke(Request $request): Response 'return_url' => $this->router->generate('sylius_shop_order_thank_you', [], UrlGeneratorInterface::ABSOLUTE_URL), ]); } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachine instanceof FactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachine); + } + + return $this->stateMachine; + } } diff --git a/src/Controller/CreatePayPalOrderAction.php b/src/Controller/CreatePayPalOrderAction.php index 6da35553..5e85e2e1 100644 --- a/src/Controller/CreatePayPalOrderAction.php +++ b/src/Controller/CreatePayPalOrderAction.php @@ -18,36 +18,55 @@ final class CreatePayPalOrderAction { - private Payum $payum; - - private OrderRepositoryInterface $orderRepository; - - private FactoryInterface $stateMachineFactory; - - private ObjectManager $paymentManager; - - private PaymentStateManagerInterface $paymentStateManager; - - private OrderProviderInterface $orderProvider; - - private CapturePaymentResolverInterface $capturePaymentResolver; - public function __construct( - Payum $payum, - OrderRepositoryInterface $orderRepository, - FactoryInterface $stateMachineFactory, - ObjectManager $paymentManager, - PaymentStateManagerInterface $paymentStateManager, - OrderProviderInterface $orderProvider, - CapturePaymentResolverInterface $capturePaymentResolver + private readonly ?Payum $payum, + private readonly ?OrderRepositoryInterface $orderRepository, + private readonly ?FactoryInterface $stateMachineFactory, + private readonly ?ObjectManager $paymentManager, + private readonly PaymentStateManagerInterface $paymentStateManager, + private readonly OrderProviderInterface $orderProvider, + private readonly CapturePaymentResolverInterface $capturePaymentResolver, ) { - $this->payum = $payum; - $this->orderRepository = $orderRepository; - $this->stateMachineFactory = $stateMachineFactory; - $this->paymentManager = $paymentManager; - $this->paymentStateManager = $paymentStateManager; - $this->orderProvider = $orderProvider; - $this->capturePaymentResolver = $capturePaymentResolver; + if (null !== $this->payum) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the first argument is deprecated and will be prohibited in 2.0', + Payum::class, + ), + ); + } + if (null !== $this->orderRepository) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the second argument is deprecated and will be prohibited in 2.0', + OrderRepositoryInterface::class, + ), + ); + } + if (null !== $this->stateMachineFactory) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the third argument is deprecated and will be prohibited in 2.0', + FactoryInterface::class, + ), + ); + } + if (null !== $this->paymentManager) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the fourth argument is deprecated and will be prohibited in 2.0', + ObjectManager::class, + ), + ); + } } public function __invoke(Request $request): Response diff --git a/src/Controller/CreatePayPalOrderFromCartAction.php b/src/Controller/CreatePayPalOrderFromCartAction.php index 83068787..10c52dca 100644 --- a/src/Controller/CreatePayPalOrderFromCartAction.php +++ b/src/Controller/CreatePayPalOrderFromCartAction.php @@ -19,32 +19,44 @@ final class CreatePayPalOrderFromCartAction { - private Payum $payum; - - private OrderRepositoryInterface $orderRepository; - - private FactoryInterface $stateMachineFactory; - - private ObjectManager $paymentManager; - - private OrderProviderInterface $orderProvider; - - private CapturePaymentResolverInterface $capturePaymentResolver; - public function __construct( - Payum $payum, - OrderRepositoryInterface $orderRepository, - FactoryInterface $stateMachineFactory, - ObjectManager $paymentManager, - OrderProviderInterface $orderProvider, - CapturePaymentResolverInterface $capturePaymentResolver + private readonly ?Payum $payum, + private readonly ?OrderRepositoryInterface $orderRepository, + private readonly ?FactoryInterface $stateMachineFactory, + private readonly ObjectManager $paymentManager, + private readonly OrderProviderInterface $orderProvider, + private readonly CapturePaymentResolverInterface $capturePaymentResolver, ) { - $this->payum = $payum; - $this->orderRepository = $orderRepository; - $this->stateMachineFactory = $stateMachineFactory; - $this->paymentManager = $paymentManager; - $this->orderProvider = $orderProvider; - $this->capturePaymentResolver = $capturePaymentResolver; + if (null !== $this->payum) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the first argument is deprecated and will be prohibited in 2.0', + Payum::class, + ), + ); + } + if (null !== $this->orderRepository) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the second argument is deprecated and will be prohibited in 2.0', + OrderRepositoryInterface::class, + ), + ); + } + if (null !== $this->stateMachineFactory) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the third argument is deprecated and will be prohibited in 2.0', + FactoryInterface::class, + ), + ); + } } public function __invoke(Request $request): Response diff --git a/src/Controller/CreatePayPalOrderFromPaymentPageAction.php b/src/Controller/CreatePayPalOrderFromPaymentPageAction.php index 90b70b99..253bd30a 100644 --- a/src/Controller/CreatePayPalOrderFromPaymentPageAction.php +++ b/src/Controller/CreatePayPalOrderFromPaymentPageAction.php @@ -7,7 +7,9 @@ use Doctrine\Persistence\ObjectManager; use GuzzleHttp\Exception\GuzzleException; use SM\Factory\FactoryInterface; -use Sylius\Component\Core\Model\OrderInterface; +use SM\Factory\FactoryInterface as StateMachineFactoryInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Component\Core\Model\PaymentInterface; use Sylius\Component\Core\OrderCheckoutTransitions; use Sylius\PayPalPlugin\Manager\PaymentStateManagerInterface; @@ -20,28 +22,35 @@ final class CreatePayPalOrderFromPaymentPageAction { - private FactoryInterface $stateMachineFactory; - - private ObjectManager $paymentManager; - - private PaymentStateManagerInterface $paymentStateManager; - - private OrderProviderInterface $orderProvider; - - private CapturePaymentResolverInterface $capturePaymentResolver; - public function __construct( - FactoryInterface $stateMachineFactory, - ObjectManager $paymentManager, - PaymentStateManagerInterface $paymentStateManager, - OrderProviderInterface $orderProvider, - CapturePaymentResolverInterface $capturePaymentResolver + private readonly FactoryInterface|StateMachineInterface $stateMachineFactory, + private readonly ?ObjectManager $paymentManager, + private readonly PaymentStateManagerInterface $paymentStateManager, + private readonly OrderProviderInterface $orderProvider, + private readonly CapturePaymentResolverInterface $capturePaymentResolver, ) { - $this->stateMachineFactory = $stateMachineFactory; - $this->paymentManager = $paymentManager; - $this->paymentStateManager = $paymentStateManager; - $this->orderProvider = $orderProvider; - $this->capturePaymentResolver = $capturePaymentResolver; + if ($this->stateMachineFactory instanceof FactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the first argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + FactoryInterface::class, + StateMachineInterface::class, + ), + ); + } + + if (null !== $this->paymentManager) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the second argument is deprecated and will be prohibited in 2.0', + ObjectManager::class, + ), + ); + } } public function __invoke(Request $request): Response @@ -53,8 +62,7 @@ public function __invoke(Request $request): Response /** @var PaymentInterface $payment */ $payment = $order->getLastPayment(PaymentInterface::STATE_CART); - $orderCheckoutStateMachine = $this->stateMachineFactory->get($order, OrderCheckoutTransitions::GRAPH); - $orderCheckoutStateMachine->apply(OrderCheckoutTransitions::TRANSITION_SELECT_PAYMENT); + $this->getStateMachine()->apply($order, OrderCheckoutTransitions::GRAPH, OrderCheckoutTransitions::TRANSITION_SELECT_PAYMENT); try { $this->capturePaymentResolver->resolve($payment); @@ -73,4 +81,13 @@ public function __invoke(Request $request): Response 'order_id' => $payment->getDetails()['paypal_order_id'], ]); } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachineFactory instanceof StateMachineFactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachineFactory); + } + + return $this->stateMachineFactory; + } } diff --git a/src/Controller/DownloadPayoutsReportAction.php b/src/Controller/DownloadPayoutsReportAction.php index 1dbdd402..9b06c47e 100644 --- a/src/Controller/DownloadPayoutsReportAction.php +++ b/src/Controller/DownloadPayoutsReportAction.php @@ -19,7 +19,7 @@ final class DownloadPayoutsReportAction public function __construct( PayoutsReportDownloaderInterface $payoutsReportDownloader, - PaymentMethodRepositoryInterface $paymentMethodRepository + PaymentMethodRepositoryInterface $paymentMethodRepository, ) { $this->payoutsReportDownloader = $payoutsReportDownloader; $this->paymentMethodRepository = $paymentMethodRepository; diff --git a/src/Controller/EnableSellerAction.php b/src/Controller/EnableSellerAction.php index ac662985..f84c1026 100644 --- a/src/Controller/EnableSellerAction.php +++ b/src/Controller/EnableSellerAction.php @@ -22,7 +22,7 @@ final class EnableSellerAction public function __construct( PaymentMethodRepositoryInterface $paymentMethodRepository, - PaymentMethodEnablerInterface $paymentMethodEnabler + PaymentMethodEnablerInterface $paymentMethodEnabler, ) { $this->paymentMethodRepository = $paymentMethodRepository; $this->paymentMethodEnabler = $paymentMethodEnabler; diff --git a/src/Controller/PayPalButtonsController.php b/src/Controller/PayPalButtonsController.php index 6640282d..6235f432 100644 --- a/src/Controller/PayPalButtonsController.php +++ b/src/Controller/PayPalButtonsController.php @@ -43,7 +43,7 @@ public function __construct( PayPalConfigurationProviderInterface $payPalConfigurationProvider, OrderRepositoryInterface $orderRepository, AvailableCountriesProviderInterface $availableCountriesProvider, - LocaleProcessorInterface $localeProcessor + LocaleProcessorInterface $localeProcessor, ) { $this->twig = $twig; $this->router = $router; diff --git a/src/Controller/PayPalOrderItemController.php b/src/Controller/PayPalOrderItemController.php index 545fa3c6..b059e631 100644 --- a/src/Controller/PayPalOrderItemController.php +++ b/src/Controller/PayPalOrderItemController.php @@ -34,7 +34,7 @@ public function createFromProductDetailsAction(Request $request): Response $form = $this->getFormFactory()->create( $formType, $this->createAddToCartCommand($cart, $orderItem), - $configuration->getFormOptions() + $configuration->getFormOptions(), ); $form = $form->handleRequest($request); diff --git a/src/Controller/PayPalPaymentOnErrorAction.php b/src/Controller/PayPalPaymentOnErrorAction.php index 9c218499..879b13c8 100644 --- a/src/Controller/PayPalPaymentOnErrorAction.php +++ b/src/Controller/PayPalPaymentOnErrorAction.php @@ -31,7 +31,6 @@ public function __invoke(Request $request): Response { /** * @var string $content - * @psalm-suppress UnnecessaryVarAnnotation */ $content = $request->getContent(); diff --git a/src/Controller/PayWithPayPalFormAction.php b/src/Controller/PayWithPayPalFormAction.php index 4bac1a14..81ad4c4f 100644 --- a/src/Controller/PayWithPayPalFormAction.php +++ b/src/Controller/PayWithPayPalFormAction.php @@ -33,7 +33,7 @@ public function __construct( PaymentRepositoryInterface $paymentRepository, AvailableCountriesProviderInterface $countriesProvider, CacheAuthorizeClientApiInterface $authorizeClientApi, - IdentityApiInterface $identityApi + IdentityApiInterface $identityApi, ) { $this->twig = $twig; $this->paymentRepository = $paymentRepository; diff --git a/src/Controller/ProcessPayPalOrderAction.php b/src/Controller/ProcessPayPalOrderAction.php index 11d79841..a38603eb 100644 --- a/src/Controller/ProcessPayPalOrderAction.php +++ b/src/Controller/ProcessPayPalOrderAction.php @@ -6,6 +6,8 @@ use Doctrine\Persistence\ObjectManager; use SM\Factory\FactoryInterface as StateMachineFactoryInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Component\Core\Factory\AddressFactoryInterface; use Sylius\Component\Core\Model\CustomerInterface; use Sylius\Component\Core\Model\PaymentInterface; @@ -24,48 +26,29 @@ final class ProcessPayPalOrderAction { - private OrderRepositoryInterface $orderRepository; - - private CustomerRepositoryInterface $customerRepository; - - private \Sylius\Component\Resource\Factory\FactoryInterface $customerFactory; - - private AddressFactoryInterface $addressFactory; - - private ObjectManager $orderManager; - - private StateMachineFactoryInterface $stateMachineFactory; - - private PaymentStateManagerInterface $paymentStateManager; - - private CacheAuthorizeClientApiInterface $authorizeClientApi; - - private OrderDetailsApiInterface $orderDetailsApi; - - private OrderProviderInterface $orderProvider; - public function __construct( - OrderRepositoryInterface $orderRepository, - CustomerRepositoryInterface $customerRepository, - FactoryInterface $customerFactory, - AddressFactoryInterface $addressFactory, - ObjectManager $orderManager, - StateMachineFactoryInterface $stateMachineFactory, - PaymentStateManagerInterface $paymentStateManager, - CacheAuthorizeClientApiInterface $authorizeClientApi, - OrderDetailsApiInterface $orderDetailsApi, - OrderProviderInterface $orderProvider + private readonly OrderRepositoryInterface $orderRepository, + private readonly CustomerRepositoryInterface $customerRepository, + private readonly FactoryInterface $customerFactory, + private readonly AddressFactoryInterface $addressFactory, + private readonly ObjectManager $orderManager, + private readonly StateMachineFactoryInterface|StateMachineInterface $stateMachineFactory, + private readonly PaymentStateManagerInterface $paymentStateManager, + private readonly CacheAuthorizeClientApiInterface $authorizeClientApi, + private readonly OrderDetailsApiInterface $orderDetailsApi, + private readonly OrderProviderInterface $orderProvider, ) { - $this->orderRepository = $orderRepository; - $this->customerRepository = $customerRepository; - $this->customerFactory = $customerFactory; - $this->addressFactory = $addressFactory; - $this->orderManager = $orderManager; - $this->stateMachineFactory = $stateMachineFactory; - $this->paymentStateManager = $paymentStateManager; - $this->authorizeClientApi = $authorizeClientApi; - $this->orderDetailsApi = $orderDetailsApi; - $this->orderProvider = $orderProvider; + if ($this->stateMachineFactory instanceof StateMachineFactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + message: sprintf( + 'Passing an instance of "%s" as the sixth argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + StateMachineFactoryInterface::class, + StateMachineInterface::class, + ), + ); + } } public function __invoke(Request $request): Response @@ -85,7 +68,6 @@ public function __invoke(Request $request): Response } $purchaseUnit = (array) $data['purchase_units'][0]; - $stateMachine = $this->stateMachineFactory->get($order, OrderCheckoutTransitions::GRAPH); $address = $this->addressFactory->createForCustomer($customer); @@ -98,8 +80,8 @@ public function __invoke(Request $request): Response $address->setPostcode($purchaseUnit['shipping']['address']['postal_code']); $address->setCountryCode($purchaseUnit['shipping']['address']['country_code']); - $stateMachine->apply(OrderCheckoutTransitions::TRANSITION_ADDRESS); - $stateMachine->apply(OrderCheckoutTransitions::TRANSITION_SELECT_SHIPPING); + $this->getStateMachine()->apply($order, OrderCheckoutTransitions::GRAPH, OrderCheckoutTransitions::TRANSITION_ADDRESS); + $this->getStateMachine()->apply($order, OrderCheckoutTransitions::GRAPH, OrderCheckoutTransitions::TRANSITION_SELECT_SHIPPING); } else { $address->setFirstName($customer->getFirstName()); $address->setLastName($customer->getLastName()); @@ -110,13 +92,14 @@ public function __invoke(Request $request): Response $address->setCity($defaultAddress ? $defaultAddress->getCity() : ''); $address->setPostcode($defaultAddress ? $defaultAddress->getPostcode() : ''); $address->setCountryCode($data['payer']['address']['country_code']); - $stateMachine->apply(OrderCheckoutTransitions::TRANSITION_ADDRESS); + + $this->getStateMachine()->apply($order, OrderCheckoutTransitions::GRAPH, OrderCheckoutTransitions::TRANSITION_ADDRESS); } $order->setShippingAddress(clone $address); $order->setBillingAddress(clone $address); - $stateMachine->apply(OrderCheckoutTransitions::TRANSITION_SELECT_PAYMENT); + $this->getStateMachine()->apply($order, OrderCheckoutTransitions::GRAPH, OrderCheckoutTransitions::TRANSITION_SELECT_PAYMENT); $this->orderManager->flush(); @@ -151,4 +134,13 @@ private function getOrderDetails(string $id, PaymentInterface $payment): array return $this->orderDetailsApi->get($token, $id); } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachineFactory instanceof StateMachineFactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachineFactory); + } + + return $this->stateMachineFactory; + } } diff --git a/src/Controller/UpdatePayPalOrderAction.php b/src/Controller/UpdatePayPalOrderAction.php index 7048c14b..f74636f7 100644 --- a/src/Controller/UpdatePayPalOrderAction.php +++ b/src/Controller/UpdatePayPalOrderAction.php @@ -38,7 +38,7 @@ public function __construct( OrderDetailsApiInterface $orderDetailsApi, UpdateOrderApiInterface $updateOrderApi, AddressFactoryInterface $addressFactory, - OrderProcessorInterface $orderProcessor + OrderProcessorInterface $orderProcessor, ) { $this->paymentProvider = $paymentProvider; $this->authorizeClientApi = $authorizeClientApi; diff --git a/src/Controller/Webhook/RefundOrderAction.php b/src/Controller/Webhook/RefundOrderAction.php index 0c9bc9aa..fae86cba 100644 --- a/src/Controller/Webhook/RefundOrderAction.php +++ b/src/Controller/Webhook/RefundOrderAction.php @@ -6,8 +6,9 @@ use Doctrine\Persistence\ObjectManager; use SM\Factory\FactoryInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Component\Payment\PaymentTransitions; -use Sylius\Component\Resource\StateMachine\StateMachineInterface; use Sylius\PayPalPlugin\Exception\PaymentNotFoundException; use Sylius\PayPalPlugin\Exception\PayPalWrongDataException; use Sylius\PayPalPlugin\Provider\PaymentProviderInterface; @@ -19,24 +20,23 @@ final class RefundOrderAction { - private FactoryInterface $stateMachineFactory; - - private PaymentProviderInterface $paymentProvider; - - private ObjectManager $paymentManager; - - private PayPalRefundDataProviderInterface $payPalRefundDataProvider; - public function __construct( - FactoryInterface $stateMachineFactory, - PaymentProviderInterface $paymentProvider, - ObjectManager $paymentManager, - PayPalRefundDataProviderInterface $payPalRefundDataProvider + private readonly FactoryInterface|StateMachineInterface $stateMachineFactory, + private readonly PaymentProviderInterface $paymentProvider, + private readonly ObjectManager $paymentManager, + private readonly PayPalRefundDataProviderInterface $payPalRefundDataProvider, ) { - $this->stateMachineFactory = $stateMachineFactory; - $this->paymentProvider = $paymentProvider; - $this->paymentManager = $paymentManager; - $this->payPalRefundDataProvider = $payPalRefundDataProvider; + if ($this->stateMachineFactory instanceof FactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + message: sprintf( + 'Passing an instance of "%s" as the first argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + FactoryInterface::class, + StateMachineInterface::class, + ), + ); + } } public function __invoke(Request $request): Response @@ -49,10 +49,10 @@ public function __invoke(Request $request): Response return new JsonResponse(['error' => $exception->getMessage()], Response::HTTP_NOT_FOUND); } - /** @var StateMachineInterface $stateMachine */ - $stateMachine = $this->stateMachineFactory->get($payment, PaymentTransitions::GRAPH); - if ($stateMachine->can(PaymentTransitions::TRANSITION_REFUND)) { - $stateMachine->apply(PaymentTransitions::TRANSITION_REFUND); + $stateMachine = $this->getStateMachine(); + + if ($stateMachine->can($payment, PaymentTransitions::GRAPH, PaymentTransitions::TRANSITION_REFUND)) { + $stateMachine->apply($payment, PaymentTransitions::GRAPH, PaymentTransitions::TRANSITION_REFUND); } $this->paymentManager->flush(); @@ -64,7 +64,6 @@ private function getPayPalPaymentUrl(Request $request): string { /** * @var string $content - * @psalm-suppress UnnecessaryVarAnnotation */ $content = $request->getContent(); @@ -82,4 +81,13 @@ private function getPayPalPaymentUrl(Request $request): string throw new PayPalWrongDataException(); } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachineFactory instanceof FactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachineFactory); + } + + return $this->stateMachineFactory; + } } diff --git a/src/DependencyInjection/SyliusPayPalExtension.php b/src/DependencyInjection/SyliusPayPalExtension.php index 959f1879..79ea3468 100644 --- a/src/DependencyInjection/SyliusPayPalExtension.php +++ b/src/DependencyInjection/SyliusPayPalExtension.php @@ -6,9 +6,12 @@ use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\FileLocator; +use Symfony\Component\Config\Loader\DelegatingLoader; +use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface; +use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; final class SyliusPayPalExtension extends Extension implements PrependExtensionInterface @@ -16,7 +19,11 @@ final class SyliusPayPalExtension extends Extension implements PrependExtensionI public function load(array $configs, ContainerBuilder $container): void { $config = $this->processConfiguration($this->getConfiguration([], $container), $configs); - $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); + $loaderResolver = new LoaderResolver([ + new PhpFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')), + new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')), + ]); + $delegatingLoader = new DelegatingLoader($loaderResolver); $container->setParameter('sylius.paypal.logging.increased', (bool) $config['logging']['increased']); @@ -30,7 +37,7 @@ public function load(array $configs, ContainerBuilder $container): void $container->setParameter('sylius.pay_pal.reports_sftp_host', 'reports.paypal.com'); } - $loader->load('services.xml'); + $delegatingLoader->load('services.xml'); } public function getConfiguration(array $config, ContainerBuilder $container): ConfigurationInterface @@ -59,7 +66,7 @@ public function prepend(ContainerBuilder $container): void $migrationsPath, [ 'Sylius\PayPalPlugin\Migrations' => '@SyliusPayPalPlugin/Migrations', - ] + ], ), ]); diff --git a/src/Enabler/PayPalPaymentMethodEnabler.php b/src/Enabler/PayPalPaymentMethodEnabler.php index e67d88a6..9e868871 100644 --- a/src/Enabler/PayPalPaymentMethodEnabler.php +++ b/src/Enabler/PayPalPaymentMethodEnabler.php @@ -14,7 +14,9 @@ namespace Sylius\PayPalPlugin\Enabler; use Doctrine\Persistence\ObjectManager; -use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; use Sylius\Bundle\PayumBundle\Model\GatewayConfigInterface; use Sylius\Component\Core\Model\PaymentMethodInterface; use Sylius\PayPalPlugin\Exception\PaymentMethodCouldNotBeEnabledException; @@ -22,24 +24,29 @@ final class PayPalPaymentMethodEnabler implements PaymentMethodEnablerInterface { - private Client $client; - - private string $baseUrl; - - private ObjectManager $paymentMethodManager; - - private SellerWebhookRegistrarInterface $sellerWebhookRegistrar; - public function __construct( - Client $client, - string $baseUrl, - ObjectManager $paymentMethodManager, - SellerWebhookRegistrarInterface $sellerWebhookRegistrar + private readonly GuzzleClientInterface|ClientInterface $client, + private readonly string $baseUrl, + private readonly ObjectManager $paymentMethodManager, + private readonly SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + private readonly ?RequestFactoryInterface $requestFactory = null, ) { - $this->client = $client; - $this->baseUrl = $baseUrl; - $this->paymentMethodManager = $paymentMethodManager; - $this->sellerWebhookRegistrar = $sellerWebhookRegistrar; + if ($this->client instanceof GuzzleClientInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Passing GuzzleHttp\Client as a first argument in the constructor is deprecated and will be prohibited in 2.0. Use Psr\Http\Client\ClientInterface instead.', + ); + } + + if (null === $this->requestFactory) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Not passing $requestFactory to %s constructor is deprecated and will be prohibited in 2.0', + self::class, + ); + } } public function enable(PaymentMethodInterface $paymentMethod): void @@ -48,10 +55,19 @@ public function enable(PaymentMethodInterface $paymentMethod): void $gatewayConfig = $paymentMethod->getGatewayConfig(); $config = $gatewayConfig->getConfig(); - $response = $this->client->request( - 'GET', - sprintf('%s/seller-permissions/check/%s', $this->baseUrl, (string) $config['merchant_id']) - ); + if ($this->client instanceof GuzzleClientInterface || null === $this->requestFactory) { + $response = $this->client->request( + 'GET', + sprintf('%s/seller-permissions/check/%s', $this->baseUrl, (string) $config['merchant_id']), + ); + } else { + $response = $this->client->sendRequest( + $this->requestFactory->createRequest( + 'GET', + sprintf('%s/seller-permissions/check/%s', $this->baseUrl, (string) $config['merchant_id']), + ), + ); + } $content = (array) json_decode($response->getBody()->getContents(), true); if (!((bool) $content['permissionsGranted'])) { diff --git a/src/Entity/PayPalCredentials.php b/src/Entity/PayPalCredentials.php index 7e90db43..bb6a51bf 100644 --- a/src/Entity/PayPalCredentials.php +++ b/src/Entity/PayPalCredentials.php @@ -23,32 +23,24 @@ class PayPalCredentials implements PayPalCredentialsInterface { /** - * * @ORM\Id * @ORM\Column(type="string") */ private string $id; /** - * * @ORM\ManyToOne(targetEntity="Sylius\Component\Core\Model\PaymentMethodInterface") * @ORM\JoinColumn(name="payment_method_id", referencedColumnName="id") */ private PaymentMethodInterface $paymentMethod; - /** - * @ORM\Column(type="string", name="access_token") - */ + /** @ORM\Column(type="string", name="access_token") */ private string $accessToken; - /** - * @ORM\Column(type="datetime", name="creation_time") - */ + /** @ORM\Column(type="datetime", name="creation_time") */ private \DateTime $creationTime; - /** - * @ORM\Column(type="datetime", name="expiration_time") - */ + /** @ORM\Column(type="datetime", name="expiration_time") */ private \DateTime $expirationTime; public function __construct( @@ -56,7 +48,7 @@ public function __construct( PaymentMethodInterface $paymentMethod, string $accessToken, \DateTime $creationTime, - int $expiresIn + int $expiresIn, ) { $this->id = $id; $this->paymentMethod = $paymentMethod; diff --git a/src/EventListener/Workflow/CompletePayPalOrderListener.php b/src/EventListener/Workflow/CompletePayPalOrderListener.php new file mode 100644 index 00000000..5de27780 --- /dev/null +++ b/src/EventListener/Workflow/CompletePayPalOrderListener.php @@ -0,0 +1,35 @@ +getSubject(); + Assert::isInstanceOf($order, OrderInterface::class); + + $this->completeProcessor->completePayPalOrder($order); + } +} diff --git a/src/EventListener/Workflow/RefundPaymentListener.php b/src/EventListener/Workflow/RefundPaymentListener.php new file mode 100644 index 00000000..826690ea --- /dev/null +++ b/src/EventListener/Workflow/RefundPaymentListener.php @@ -0,0 +1,35 @@ +getSubject(); + Assert::isInstanceOf($payment, PaymentInterface::class); + + $this->paymentRefundProcessor->refund($payment); + } +} diff --git a/src/Factory/PayPalPaymentMethodNewResourceFactory.php b/src/Factory/PayPalPaymentMethodNewResourceFactory.php index 125645e1..1c5e2cd5 100644 --- a/src/Factory/PayPalPaymentMethodNewResourceFactory.php +++ b/src/Factory/PayPalPaymentMethodNewResourceFactory.php @@ -19,7 +19,7 @@ final class PayPalPaymentMethodNewResourceFactory implements NewResourceFactoryI public function __construct( NewResourceFactoryInterface $newResourceFactory, - OnboardingProcessorInterface $onboardingProcessor + OnboardingProcessorInterface $onboardingProcessor, ) { $this->newResourceFactory = $newResourceFactory; $this->onboardingProcessor = $onboardingProcessor; diff --git a/src/Form/Type/ChangePaymentMethodType.php b/src/Form/Type/ChangePaymentMethodType.php index ba9a4e2d..283a315e 100644 --- a/src/Form/Type/ChangePaymentMethodType.php +++ b/src/Form/Type/ChangePaymentMethodType.php @@ -24,7 +24,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void foreach ($payments as $key => $payment) { if (!in_array( $payment->getState(), - [PaymentInterface::STATE_NEW, PaymentInterface::STATE_CART, PaymentInterface::STATE_PROCESSING] + [PaymentInterface::STATE_NEW, PaymentInterface::STATE_CART, PaymentInterface::STATE_PROCESSING], )) { $form->remove((string) $key); } diff --git a/src/Generator/PayPalAuthAssertionGenerator.php b/src/Generator/PayPalAuthAssertionGenerator.php index 545c5055..fb94ce78 100644 --- a/src/Generator/PayPalAuthAssertionGenerator.php +++ b/src/Generator/PayPalAuthAssertionGenerator.php @@ -31,7 +31,7 @@ public function generate(PaymentMethodInterface $paymentMethod): string return base64_encode('{"alg":"none"}') . '.' . base64_encode( - (string) json_encode(['iss' => (string) $config['client_id'], 'payer_id' => (string) $config['merchant_id']]) + (string) json_encode(['iss' => (string) $config['client_id'], 'payer_id' => (string) $config['merchant_id']]), ) . '.' ; } diff --git a/src/Listener/PayPalPaymentMethodListener.php b/src/Listener/PayPalPaymentMethodListener.php index bb6cc99d..6344222a 100644 --- a/src/Listener/PayPalPaymentMethodListener.php +++ b/src/Listener/PayPalPaymentMethodListener.php @@ -31,7 +31,7 @@ public function __construct( OnboardingInitiatorInterface $onboardingInitiator, UrlGeneratorInterface $urlGenerator, FlashBagInterface|RequestStack $flashBagOrRequestStack, - PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider + PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider, ) { if ($flashBagOrRequestStack instanceof FlashBagInterface) { trigger_deprecation('sylius/paypal-plugin', '1.5', sprintf('Passing an instance of %s as constructor argument for %s is deprecated as of PayPalPlugin 1.5 and will be removed in 2.0. Pass an instance of %s instead.', FlashBagInterface::class, self::class, RequestStack::class)); diff --git a/src/Manager/PaymentStateManager.php b/src/Manager/PaymentStateManager.php index 32d3d3db..4aaf53d4 100644 --- a/src/Manager/PaymentStateManager.php +++ b/src/Manager/PaymentStateManager.php @@ -6,28 +6,31 @@ use Doctrine\Persistence\ObjectManager; use SM\Factory\FactoryInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Component\Core\Model\PaymentInterface; use Sylius\Component\Payment\PaymentTransitions; -use Sylius\Component\Resource\StateMachine\StateMachineInterface; use Sylius\PayPalPlugin\Payum\Action\StatusAction; use Sylius\PayPalPlugin\Processor\PaymentCompleteProcessorInterface; final class PaymentStateManager implements PaymentStateManagerInterface { - private FactoryInterface $stateMachineFactory; - - private ObjectManager $paymentManager; - - private PaymentCompleteProcessorInterface $paypalPaymentCompleteProcessor; - public function __construct( - FactoryInterface $stateMachineFactory, - ObjectManager $paymentManager, - PaymentCompleteProcessorInterface $paypalPaymentCompleteProcessor + private readonly FactoryInterface|StateMachineInterface $stateMachineFactory, + private readonly ObjectManager $paymentManager, + private readonly PaymentCompleteProcessorInterface $paypalPaymentCompleteProcessor, ) { - $this->stateMachineFactory = $stateMachineFactory; - $this->paymentManager = $paymentManager; - $this->paypalPaymentCompleteProcessor = $paypalPaymentCompleteProcessor; + if ($this->stateMachineFactory instanceof FactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the first argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + FactoryInterface::class, + StateMachineInterface::class, + ), + ); + } } public function create(PaymentInterface $payment): void @@ -67,10 +70,16 @@ public function cancel(PaymentInterface $payment): void private function applyTransitionAndSave(PaymentInterface $payment, string $transition): void { - /** @var StateMachineInterface $stateMachine */ - $stateMachine = $this->stateMachineFactory->get($payment, PaymentTransitions::GRAPH); - - $stateMachine->apply($transition); + $this->getStateMachine()->apply($payment, PaymentTransitions::GRAPH, $transition); $this->paymentManager->flush(); } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachineFactory instanceof FactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachineFactory); + } + + return $this->stateMachineFactory; + } } diff --git a/src/Migrations/Version20240319121423.php b/src/Migrations/Version20240319121423.php new file mode 100644 index 00000000..92fa3748 --- /dev/null +++ b/src/Migrations/Version20240319121423.php @@ -0,0 +1,36 @@ +hasTable('sylius_paypal_plugin_pay_pal_credentials')) { + $this->markAsExecuted($this->getVersion()); + $this->skipIf(true, 'This migration is marked as completed.'); + } + + $this->addSql('CREATE TABLE sylius_paypal_plugin_pay_pal_credentials (id VARCHAR(255) NOT NULL, payment_method_id INT DEFAULT NULL, access_token VARCHAR(255) NOT NULL, creation_time TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, expiration_time TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id))'); + $this->addSql('CREATE INDEX IDX_C56F54AD5AA1164F ON sylius_paypal_plugin_pay_pal_credentials (payment_method_id)'); + $this->addSql('ALTER TABLE sylius_paypal_plugin_pay_pal_credentials ADD CONSTRAINT FK_C56F54AD5AA1164F FOREIGN KEY (payment_method_id) REFERENCES sylius_payment_method (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE sylius_paypal_plugin_pay_pal_credentials DROP CONSTRAINT FK_C56F54AD5AA1164F'); + $this->addSql('DROP TABLE sylius_paypal_plugin_pay_pal_credentials'); + } + } +} diff --git a/src/Model/PayPalOrder.php b/src/Model/PayPalOrder.php index 42947ffc..6445288b 100644 --- a/src/Model/PayPalOrder.php +++ b/src/Model/PayPalOrder.php @@ -17,11 +17,11 @@ class PayPalOrder { - const NO_SHIPPING = 'NO_SHIPPING'; + public const NO_SHIPPING = 'NO_SHIPPING'; - const PROVIDED_ADDRESS = 'SET_PROVIDED_ADDRESS'; + public const PROVIDED_ADDRESS = 'SET_PROVIDED_ADDRESS'; - const PAYPAL_ADDRESS = 'GET_FROM_FILE'; + public const PAYPAL_ADDRESS = 'GET_FROM_FILE'; /** @var string */ private $intent; @@ -47,8 +47,8 @@ public function toArray(): array $this->payPalPurchaseUnit->toArray(), ], 'application_context' => [ - 'shipping_preference' => $this->getShippingPreference() - ] + 'shipping_preference' => $this->getShippingPreference(), + ], ]; } diff --git a/src/Model/PayPalPurchaseUnit.php b/src/Model/PayPalPurchaseUnit.php index 618b80ce..f726e114 100644 --- a/src/Model/PayPalPurchaseUnit.php +++ b/src/Model/PayPalPurchaseUnit.php @@ -70,7 +70,7 @@ public function __construct( array $items, bool $shippingRequired, ?AddressInterface $shippingAddress = null, - string $softDescriptor = 'Sylius PayPal Payment' + string $softDescriptor = 'Sylius PayPal Payment', ) { $this->referenceId = $referenceId; $this->invoiceNumber = $invoiceNumber; @@ -130,7 +130,8 @@ public function toArray(): array private function getShippingAddress(): array { - Assert::isInstanceOf( $this->shippingAddress, AddressInterface::class); + Assert::isInstanceOf($this->shippingAddress, AddressInterface::class); + return [ 'name' => ['full_name' => (string) $this->shippingAddress->getFullName()], 'address' => [ diff --git a/src/Onboarding/Initiator/OnboardingInitiator.php b/src/Onboarding/Initiator/OnboardingInitiator.php index 348ec3f5..80164288 100644 --- a/src/Onboarding/Initiator/OnboardingInitiator.php +++ b/src/Onboarding/Initiator/OnboardingInitiator.php @@ -42,7 +42,7 @@ public function initiate(PaymentMethodInterface $paymentMethod): string 'factory' => 'sylius.pay_pal', ], UrlGeneratorInterface::ABSOLUTE_URL), ]), - UrlUtils::APPEND_QUERY_STRING_REPLACE_DUPLICATE + UrlUtils::APPEND_QUERY_STRING_REPLACE_DUPLICATE, ); } diff --git a/src/Onboarding/Processor/BasicOnboardingProcessor.php b/src/Onboarding/Processor/BasicOnboardingProcessor.php index 89e69335..96ddaa9e 100644 --- a/src/Onboarding/Processor/BasicOnboardingProcessor.php +++ b/src/Onboarding/Processor/BasicOnboardingProcessor.php @@ -4,7 +4,9 @@ namespace Sylius\PayPalPlugin\Onboarding\Processor; -use GuzzleHttp\ClientInterface; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; use Sylius\Component\Core\Model\PaymentMethodInterface; use Sylius\PayPalPlugin\Exception\PayPalPluginException; use Sylius\PayPalPlugin\Exception\PayPalWebhookAlreadyRegisteredException; @@ -15,25 +17,34 @@ final class BasicOnboardingProcessor implements OnboardingProcessorInterface { - private ClientInterface $httpClient; - - private SellerWebhookRegistrarInterface $sellerWebhookRegistrar; - - private string $url; - public function __construct( - ClientInterface $httpClient, - SellerWebhookRegistrarInterface $sellerWebhookRegistrar, - string $url + private readonly GuzzleClientInterface|ClientInterface $httpClient, + private readonly SellerWebhookRegistrarInterface $sellerWebhookRegistrar, + private readonly string $url, + private readonly ?RequestFactoryInterface $requestFactory = null, ) { - $this->httpClient = $httpClient; - $this->sellerWebhookRegistrar = $sellerWebhookRegistrar; - $this->url = $url; + if ($this->httpClient instanceof GuzzleClientInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Passing GuzzleHttp\ClientInterface as a first argument in the constructor is deprecated and will be prohibited in 2.0. Use Psr\Http\Client\ClientInterface instead.', + self::class, + ); + } + + if (null === $this->requestFactory) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + 'Not passing $requestFactory to %s constructor is deprecated and will be prohibited in 2.0', + self::class, + ); + } } public function process( PaymentMethodInterface $paymentMethod, - Request $request + Request $request, ): PaymentMethodInterface { if (!$this->supports($paymentMethod, $request)) { throw new \DomainException('not supported'); @@ -43,17 +54,28 @@ public function process( Assert::notNull($gatewayConfig); $onboardingId = (string) $request->query->get('onboarding_id'); - $checkPartnerReferralsResponse = $this->httpClient->request( - 'GET', - sprintf('%s/partner-referrals/check/%s', $this->url, $onboardingId), - [ - 'headers' => [ - 'Content-Type' => 'application/json', - 'Accept' => 'application/json', - ], - ] - ); + if ($this->httpClient instanceof GuzzleClientInterface || null === $this->requestFactory) { + $checkPartnerReferralsResponse = $this->httpClient->request( + 'GET', + sprintf('%s/partner-referrals/check/%s', $this->url, $onboardingId), + [ + 'headers' => [ + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + ], + ], + ); + } else { + $checkPartnerReferralsRequest = $this->requestFactory->createRequest( + 'GET', + sprintf('%s/partner-referrals/check/%s', $this->url, $onboardingId), + ) + ->withHeader('Content-Type', 'application/json') + ->withHeader('Accept', 'application/json'); + + $checkPartnerReferralsResponse = $this->httpClient->sendRequest($checkPartnerReferralsRequest); + } $response = (array) json_decode($checkPartnerReferralsResponse->getBody()->getContents(), true); if (!isset($response['client_id']) || !isset($response['client_secret'])) { diff --git a/src/Payum/Action/CaptureAction.php b/src/Payum/Action/CaptureAction.php index a0982f71..ecc519e3 100644 --- a/src/Payum/Action/CaptureAction.php +++ b/src/Payum/Action/CaptureAction.php @@ -33,7 +33,7 @@ final class CaptureAction implements ActionInterface public function __construct( CacheAuthorizeClientApiInterface $authorizeClientApi, CreateOrderApiInterface $createOrderApi, - UuidProviderInterface $uuidProvider + UuidProviderInterface $uuidProvider, ) { $this->authorizeClientApi = $authorizeClientApi; $this->createOrderApi = $createOrderApi; diff --git a/src/Payum/Action/CompleteOrderAction.php b/src/Payum/Action/CompleteOrderAction.php index e6c5b6ab..6dda252f 100644 --- a/src/Payum/Action/CompleteOrderAction.php +++ b/src/Payum/Action/CompleteOrderAction.php @@ -25,7 +25,6 @@ use Sylius\PayPalPlugin\Api\OrderDetailsApiInterface; use Sylius\PayPalPlugin\Api\UpdateOrderApiInterface; use Sylius\PayPalPlugin\Payum\Request\CompleteOrder; -use Sylius\PayPalPlugin\Processor\PayPalAddressProcessor; use Sylius\PayPalPlugin\Processor\PayPalAddressProcessorInterface; use Sylius\PayPalPlugin\Provider\PayPalItemDataProviderInterface; use Sylius\PayPalPlugin\Updater\PaymentUpdaterInterface; @@ -56,7 +55,7 @@ public function __construct( PayPalAddressProcessorInterface $payPalAddressProcessor, PaymentUpdaterInterface $payPalPaymentUpdater, StateResolverInterface $orderPaymentStateResolver, - PayPalItemDataProviderInterface $payPalItemsDataProvider + PayPalItemDataProviderInterface $payPalItemsDataProvider, ) { $this->authorizeClientApi = $authorizeClientApi; $this->updateOrderApi = $updateOrderApi; @@ -93,7 +92,7 @@ public function execute($request): void (string) $details['paypal_order_id'], $payment, (string) $details['reference_id'], - $config['merchant_id'] + $config['merchant_id'], ); $this->payPalPaymentUpdater->updateAmount($payment, $order->getTotal()); @@ -108,10 +107,10 @@ public function execute($request): void 'paypal_order_id' => $orderDetails['id'], 'reference_id' => $orderDetails['purchase_units'][0]['reference_id'], ]; - if (isset($orderDetails['purchase_units'][0]["payments"]["captures"][0]["id"])) { + if (isset($orderDetails['purchase_units'][0]['payments']['captures'][0]['id'])) { $details = array_merge( $details, - ['transaction_id' => $orderDetails['purchase_units'][0]["payments"]["captures"][0]["id"]] + ['transaction_id' => $orderDetails['purchase_units'][0]['payments']['captures'][0]['id']], ); } diff --git a/src/Payum/Action/ResolveNextRouteAction.php b/src/Payum/Action/ResolveNextRouteAction.php index 30f6d80a..18e85a22 100644 --- a/src/Payum/Action/ResolveNextRouteAction.php +++ b/src/Payum/Action/ResolveNextRouteAction.php @@ -25,7 +25,7 @@ public function execute($request): void if ($payment->getState() === PaymentInterface::STATE_NEW) { $request->setRouteName('sylius_paypal_plugin_pay_with_paypal_form'); $request->setRouteParameters( - ['orderToken' => $order->getTokenValue(), 'paymentId' => $payment->getId()] + ['orderToken' => $order->getTokenValue(), 'paymentId' => $payment->getId()], ); return; diff --git a/src/Processor/OrderPaymentProcessor.php b/src/Processor/OrderPaymentProcessor.php index 205ac1a8..0c7ffee3 100644 --- a/src/Processor/OrderPaymentProcessor.php +++ b/src/Processor/OrderPaymentProcessor.php @@ -5,6 +5,8 @@ namespace Sylius\PayPalPlugin\Processor; use SM\Factory\FactoryInterface; +use Sylius\Abstraction\StateMachine\StateMachineInterface; +use Sylius\Abstraction\StateMachine\WinzouStateMachineAdapter; use Sylius\Bundle\PayumBundle\Model\GatewayConfigInterface; use Sylius\Component\Core\Model\PaymentInterface; use Sylius\Component\Core\Model\PaymentMethodInterface; @@ -15,16 +17,21 @@ final class OrderPaymentProcessor implements OrderProcessorInterface { - private OrderProcessorInterface $baseOrderPaymentProcessor; - - private FactoryInterface $stateMachineFactory; - public function __construct( - OrderProcessorInterface $baseOrderPaymentProcessor, - FactoryInterface $stateMachineFactory + private readonly OrderProcessorInterface $baseOrderPaymentProcessor, + private readonly FactoryInterface|StateMachineInterface $stateMachineFactory, ) { - $this->baseOrderPaymentProcessor = $baseOrderPaymentProcessor; - $this->stateMachineFactory = $stateMachineFactory; + if ($this->stateMachineFactory instanceof FactoryInterface) { + trigger_deprecation( + 'sylius/paypal-plugin', + '1.6', + sprintf( + 'Passing an instance of "%s" as the second argument is deprecated and will be prohibited in 2.0. Use "%s" instead.', + FactoryInterface::class, + StateMachineInterface::class, + ), + ); + } } public function process(OrderInterface $order): void @@ -45,8 +52,7 @@ public function process(OrderInterface $order): void $payment !== null && $this->getFactoryName($payment) !== 'sylius.pay_pal' ) { - $stateMachine = $this->stateMachineFactory->get($payment, PaymentTransitions::GRAPH); - $stateMachine->apply(PaymentTransitions::TRANSITION_CANCEL); + $this->getStateMachine()->apply($payment, PaymentTransitions::GRAPH, PaymentTransitions::TRANSITION_CANCEL); } $this->baseOrderPaymentProcessor->process($order); @@ -61,4 +67,13 @@ private function getFactoryName(PaymentInterface $payment): string return $gatewayConfig->getFactoryName(); } + + private function getStateMachine(): StateMachineInterface + { + if ($this->stateMachineFactory instanceof FactoryInterface) { + return new WinzouStateMachineAdapter($this->stateMachineFactory); + } + + return $this->stateMachineFactory; + } } diff --git a/src/Processor/PayPalAddressProcessor.php b/src/Processor/PayPalAddressProcessor.php index 81e81aac..5c25f56e 100644 --- a/src/Processor/PayPalAddressProcessor.php +++ b/src/Processor/PayPalAddressProcessor.php @@ -5,7 +5,6 @@ namespace Sylius\PayPalPlugin\Processor; use Doctrine\Persistence\ObjectManager; -use Sylius\Component\Core\Model\AddressInterface; use Sylius\Component\Core\Model\OrderInterface; use Webmozart\Assert\Assert; diff --git a/src/Processor/PayPalPaymentRefundProcessor.php b/src/Processor/PayPalPaymentRefundProcessor.php index f4778034..29f0f129 100644 --- a/src/Processor/PayPalPaymentRefundProcessor.php +++ b/src/Processor/PayPalPaymentRefundProcessor.php @@ -42,7 +42,7 @@ public function __construct( OrderDetailsApiInterface $orderDetailsApi, RefundPaymentApiInterface $refundOrderApi, PayPalAuthAssertionGeneratorInterface $payPalAuthAssertionGenerator, - RefundReferenceNumberProviderInterface $refundReferenceNumberProvider + RefundReferenceNumberProviderInterface $refundReferenceNumberProvider, ) { $this->authorizeClientApi = $authorizeClientApi; $this->orderDetailsApi = $orderDetailsApi; @@ -83,7 +83,7 @@ public function refund(PaymentInterface $payment): void $authAssertion, $referenceNumber, (string) (((int) $payment->getAmount()) / 100), - (string) $order->getCurrencyCode() + (string) $order->getCurrencyCode(), ); } catch (ClientException | \InvalidArgumentException $exception) { throw new PayPalOrderRefundException(); diff --git a/src/Provider/PayPalItemDataProvider.php b/src/Provider/PayPalItemDataProvider.php index 79deabec..4e838fd3 100644 --- a/src/Provider/PayPalItemDataProvider.php +++ b/src/Provider/PayPalItemDataProvider.php @@ -49,7 +49,6 @@ public function provide(OrderInterface $order): array 'currency_code' => $order->getCurrencyCode(), ], ]; - } } diff --git a/src/Provider/PayPalRefundDataProvider.php b/src/Provider/PayPalRefundDataProvider.php index 86693798..1bdf2c0b 100644 --- a/src/Provider/PayPalRefundDataProvider.php +++ b/src/Provider/PayPalRefundDataProvider.php @@ -19,7 +19,7 @@ final class PayPalRefundDataProvider implements PayPalRefundDataProviderInterfac public function __construct( CacheAuthorizeClientApiInterface $authorizeClientApi, GenericApiInterface $genericApi, - PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider + PayPalPaymentMethodProviderInterface $payPalPaymentMethodProvider, ) { $this->authorizeClientApi = $authorizeClientApi; $this->genericApi = $genericApi; diff --git a/src/Registrar/SellerWebhookRegistrar.php b/src/Registrar/SellerWebhookRegistrar.php index 32d13f02..3c31bdb2 100644 --- a/src/Registrar/SellerWebhookRegistrar.php +++ b/src/Registrar/SellerWebhookRegistrar.php @@ -34,7 +34,7 @@ final class SellerWebhookRegistrar implements SellerWebhookRegistrarInterface public function __construct( AuthorizeClientApiInterface $authorizeClientApi, UrlGeneratorInterface $urlGenerator, - WebhookApiInterface $webhookApi + WebhookApiInterface $webhookApi, ) { $this->authorizeClientApi = $authorizeClientApi; $this->urlGenerator = $urlGenerator; diff --git a/src/Resolver/PayPalDefaultPaymentMethodResolver.php b/src/Resolver/PayPalDefaultPaymentMethodResolver.php index 6d004442..1fb9dcca 100644 --- a/src/Resolver/PayPalDefaultPaymentMethodResolver.php +++ b/src/Resolver/PayPalDefaultPaymentMethodResolver.php @@ -33,7 +33,7 @@ final class PayPalDefaultPaymentMethodResolver implements DefaultPaymentMethodRe public function __construct( DefaultPaymentMethodResolverInterface $decoratedDefaultPaymentMethodResolver, - PaymentMethodRepositoryInterface $paymentMethodRepository + PaymentMethodRepositoryInterface $paymentMethodRepository, ) { $this->decoratedDefaultPaymentMethodResolver = $decoratedDefaultPaymentMethodResolver; $this->paymentMethodRepository = $paymentMethodRepository; diff --git a/src/Resolver/PayPalPrioritisingPaymentMethodsResolver.php b/src/Resolver/PayPalPrioritisingPaymentMethodsResolver.php index 14330035..e086f957 100644 --- a/src/Resolver/PayPalPrioritisingPaymentMethodsResolver.php +++ b/src/Resolver/PayPalPrioritisingPaymentMethodsResolver.php @@ -33,7 +33,7 @@ public function getSupportedMethods(BasePaymentInterface $subject): array { return $this->sortPayments( $this->decoratedPaymentMethodsResolver->getSupportedMethods($subject), - $this->firstPaymentMethodFactoryName + $this->firstPaymentMethodFactoryName, ); } diff --git a/src/Resources/config/integrations/services.php b/src/Resources/config/integrations/services.php new file mode 100644 index 00000000..6bb6476b --- /dev/null +++ b/src/Resources/config/integrations/services.php @@ -0,0 +1,22 @@ += '11300') { + $configurator->import('workflow.xml'); + } +}; diff --git a/src/Resources/config/integrations/workflow.xml b/src/Resources/config/integrations/workflow.xml new file mode 100644 index 00000000..afb24e8c --- /dev/null +++ b/src/Resources/config/integrations/workflow.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/src/Resources/config/services.xml b/src/Resources/config/services.xml index 94ac7197..8385cf0b 100644 --- a/src/Resources/config/services.xml +++ b/src/Resources/config/services.xml @@ -2,10 +2,8 @@ - - - - + + @@ -44,7 +42,7 @@ id="Sylius\PayPalPlugin\Manager\PaymentStateManagerInterface" class="Sylius\PayPalPlugin\Manager\PaymentStateManager" > - + @@ -129,7 +127,7 @@ decorates="sylius.order_processing.order_payment_processor.checkout" > - + @@ -230,10 +228,11 @@ id="Sylius\PayPalPlugin\Enabler\PaymentMethodEnablerInterface" class="Sylius\PayPalPlugin\Enabler\PayPalPaymentMethodEnabler" > - + %sylius.pay_pal.facilitator_url% + - + diff --git a/src/Resources/config/services/api.xml b/src/Resources/config/services/api.xml index 88b94775..98cd6f14 100644 --- a/src/Resources/config/services/api.xml +++ b/src/Resources/config/services/api.xml @@ -6,11 +6,12 @@ true + - + @@ -18,6 +19,8 @@ %sylius.pay_pal.api_base_url% %sylius.pay_pal.request_trials_limit% %sylius.paypal.logging.increased% + + - + + - + %sylius.pay_pal.api_base_url% + + - + @@ -21,13 +21,13 @@ - + - + @@ -46,8 +46,8 @@ - - + + null @@ -64,19 +64,19 @@ - - - - + null + null + null + null - - - + null + null + null @@ -107,7 +107,7 @@ - + @@ -127,7 +127,7 @@ - + diff --git a/src/Resources/config/services/onboarding.xml b/src/Resources/config/services/onboarding.xml index 917f0971..f6ce7c40 100644 --- a/src/Resources/config/services/onboarding.xml +++ b/src/Resources/config/services/onboarding.xml @@ -15,9 +15,10 @@ id="Sylius\PayPalPlugin\Onboarding\Processor\OnboardingProcessorInterface" class="Sylius\PayPalPlugin\Onboarding\Processor\BasicOnboardingProcessor" > - + %sylius.pay_pal.facilitator_url% + diff --git a/src/Resources/views/bundles/SyliusShopBundle/Checkout/SelectPayment/_choice.html.twig b/src/Resources/views/bundles/SyliusShopBundle/Checkout/SelectPayment/_choice.html.twig index ece6954b..2c841237 100644 --- a/src/Resources/views/bundles/SyliusShopBundle/Checkout/SelectPayment/_choice.html.twig +++ b/src/Resources/views/bundles/SyliusShopBundle/Checkout/SelectPayment/_choice.html.twig @@ -12,7 +12,7 @@ {% endif %} {% if method.gatewayConfig.factoryName == 'sylius.pay_pal' %} - {{ render(controller('Sylius\\PayPalPlugin\\Controller\\PayPalButtonsController:renderPaymentPageButtonsAction', {'orderId': order.id})) }} + {{ render(controller('Sylius\\PayPalPlugin\\Controller\\PayPalButtonsController::renderPaymentPageButtonsAction', {'orderId': order.id})) }} {% endif %} diff --git a/tests/Application/.env.test b/tests/Application/.env.test index 24a84d6d..46c3f79f 100644 --- a/tests/Application/.env.test +++ b/tests/Application/.env.test @@ -12,3 +12,5 @@ SYLIUS_MESSENGER_TRANSPORT_MAIN_FAILED_DSN=sync:// SYLIUS_MESSENGER_TRANSPORT_CATALOG_PROMOTION_REMOVAL_DSN=sync:// SYLIUS_MESSENGER_TRANSPORT_CATALOG_PROMOTION_REMOVAL_FAILED_DSN=sync:// ###< symfony/messenger ### + +MAILER_DSN=null://null diff --git a/tests/Application/Kernel.php b/tests/Application/Kernel.php index db65e57d..357920e3 100644 --- a/tests/Application/Kernel.php +++ b/tests/Application/Kernel.php @@ -5,7 +5,7 @@ namespace Tests\Sylius\PayPalPlugin\Application; use PSS\SymfonyMockerContainer\DependencyInjection\MockerContainer; -use Sylius\Bundle\CoreBundle\Application\Kernel as SyliusKernel; +use Sylius\Bundle\CoreBundle\SyliusCoreBundle; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\Config\Resource\FileResource; @@ -75,7 +75,7 @@ private function getConfigDirectories(): array { return array_filter([ $this->getProjectDir() . '/config', - $this->getProjectDir() . '/config/sylius/' . SyliusKernel::MAJOR_VERSION . '.' . SyliusKernel::MINOR_VERSION, + $this->getProjectDir() . '/config/sylius/' . SyliusCoreBundle::MAJOR_VERSION . '.' . SyliusCoreBundle::MINOR_VERSION, ], 'file_exists'); } diff --git a/tests/Application/composer.json b/tests/Application/composer.json index af8a51b2..c5ee6856 100644 --- a/tests/Application/composer.json +++ b/tests/Application/composer.json @@ -1,5 +1,8 @@ { "name": "sylius/paypal-plugin", "description": "PayPal plugin for Sylius", - "license": "MIT" + "license": "MIT", + "require": { + "nyholm/psr7": "^1.8" + } } diff --git a/tests/Application/config/bundles.php b/tests/Application/config/bundles.php index d260b314..3fc7cf47 100644 --- a/tests/Application/config/bundles.php +++ b/tests/Application/config/bundles.php @@ -1,8 +1,6 @@ ['all' => true], Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true], Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true], @@ -60,12 +58,6 @@ SyliusLabs\Polyfill\Symfony\Security\Bundle\SyliusLabsPolyfillSymfonySecurityBundle::class => ['all' => true], Symfony\WebpackEncoreBundle\WebpackEncoreBundle::class => ['all' => true], Sylius\Calendar\SyliusCalendarBundle::class => ['all' => true], + League\FlysystemBundle\FlysystemBundle::class => ['all' => true], + Sylius\Abstraction\StateMachine\SyliusStateMachineAbstractionBundle::class => ['all' => true], ]; - -if (Kernel::MINOR_VERSION < 12) { - $bundles[Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle::class] = ['all' => true]; -} else { - $bundles[League\FlysystemBundle\FlysystemBundle::class] = ['all' => true]; -} - -return $bundles; diff --git a/tests/Application/config/sylius/1.12/packages/mailer.yaml b/tests/Application/config/packages/mailer.yaml similarity index 100% rename from tests/Application/config/sylius/1.12/packages/mailer.yaml rename to tests/Application/config/packages/mailer.yaml diff --git a/tests/Application/config/packages/nyholm_psr7.yaml b/tests/Application/config/packages/nyholm_psr7.yaml new file mode 100644 index 00000000..b3fb6ce7 --- /dev/null +++ b/tests/Application/config/packages/nyholm_psr7.yaml @@ -0,0 +1,11 @@ +services: + # Register nyholm/psr7 services for autowiring with PSR-17 (HTTP factories) + Psr\Http\Message\RequestFactoryInterface: '@nyholm.psr7.psr17_factory' + Psr\Http\Message\ResponseFactoryInterface: '@nyholm.psr7.psr17_factory' + Psr\Http\Message\ServerRequestFactoryInterface: '@nyholm.psr7.psr17_factory' + Psr\Http\Message\StreamFactoryInterface: '@nyholm.psr7.psr17_factory' + Psr\Http\Message\UploadedFileFactoryInterface: '@nyholm.psr7.psr17_factory' + Psr\Http\Message\UriFactoryInterface: '@nyholm.psr7.psr17_factory' + + nyholm.psr7.psr17_factory: + class: Nyholm\Psr7\Factory\Psr17Factory diff --git a/tests/Application/config/packages/test/framework.yaml b/tests/Application/config/packages/test/framework.yaml index fc1d3c13..e71603ca 100644 --- a/tests/Application/config/packages/test/framework.yaml +++ b/tests/Application/config/packages/test/framework.yaml @@ -2,3 +2,10 @@ framework: test: ~ session: storage_factory_id: session.storage.factory.mock_file + + mailer: + dsn: '%env(MAILER_DSN)%' + cache: + pools: + test.mailer_pool: + adapter: cache.adapter.filesystem diff --git a/tests/Application/config/packages/workflow.yaml b/tests/Application/config/packages/workflow.yaml new file mode 100644 index 00000000..3adbf63d --- /dev/null +++ b/tests/Application/config/packages/workflow.yaml @@ -0,0 +1,2 @@ +framework: + workflows: ~ diff --git a/tests/Application/config/sylius/1.11/packages/dev/swiftmailer.yaml b/tests/Application/config/sylius/1.11/packages/dev/swiftmailer.yaml deleted file mode 100644 index f4380780..00000000 --- a/tests/Application/config/sylius/1.11/packages/dev/swiftmailer.yaml +++ /dev/null @@ -1,2 +0,0 @@ -swiftmailer: - disable_delivery: true diff --git a/tests/Application/config/sylius/1.11/packages/staging/swiftmailer.yaml b/tests/Application/config/sylius/1.11/packages/staging/swiftmailer.yaml deleted file mode 100644 index f4380780..00000000 --- a/tests/Application/config/sylius/1.11/packages/staging/swiftmailer.yaml +++ /dev/null @@ -1,2 +0,0 @@ -swiftmailer: - disable_delivery: true diff --git a/tests/Application/config/sylius/1.11/packages/swiftmailer.yaml b/tests/Application/config/sylius/1.11/packages/swiftmailer.yaml deleted file mode 100644 index 3bab0d32..00000000 --- a/tests/Application/config/sylius/1.11/packages/swiftmailer.yaml +++ /dev/null @@ -1,2 +0,0 @@ -swiftmailer: - url: '%env(MAILER_URL)%' diff --git a/tests/Application/config/sylius/1.11/packages/test/swiftmailer.yaml b/tests/Application/config/sylius/1.11/packages/test/swiftmailer.yaml deleted file mode 100644 index c438f4b2..00000000 --- a/tests/Application/config/sylius/1.11/packages/test/swiftmailer.yaml +++ /dev/null @@ -1,6 +0,0 @@ -swiftmailer: - disable_delivery: true - logging: true - spool: - type: file - path: "%kernel.cache_dir%/spool" diff --git a/tests/Application/config/sylius/1.11/packages/test_cached/swiftmailer.yaml b/tests/Application/config/sylius/1.11/packages/test_cached/swiftmailer.yaml deleted file mode 100644 index c438f4b2..00000000 --- a/tests/Application/config/sylius/1.11/packages/test_cached/swiftmailer.yaml +++ /dev/null @@ -1,6 +0,0 @@ -swiftmailer: - disable_delivery: true - logging: true - spool: - type: file - path: "%kernel.cache_dir%/spool" diff --git a/tests/Application/config/sylius/1.12/packages/test/mailer.yaml b/tests/Application/config/sylius/1.12/packages/test/mailer.yaml deleted file mode 100644 index 52610d69..00000000 --- a/tests/Application/config/sylius/1.12/packages/test/mailer.yaml +++ /dev/null @@ -1,5 +0,0 @@ -framework: - cache: - pools: - test.mailer_pool: - adapter: cache.adapter.filesystem diff --git a/tests/Application/config/sylius/1.12/packages/test_cached/mailer.yaml b/tests/Application/config/sylius/1.12/packages/test_cached/mailer.yaml deleted file mode 100644 index 16f3170a..00000000 --- a/tests/Application/config/sylius/1.12/packages/test_cached/mailer.yaml +++ /dev/null @@ -1,2 +0,0 @@ -imports: - - { resource: "../test/mailer.yaml" } diff --git a/tests/Application/config/sylius/1.13/packages/_sylius.yaml b/tests/Application/config/sylius/1.13/packages/_sylius.yaml new file mode 100644 index 00000000..2ff8f75c --- /dev/null +++ b/tests/Application/config/sylius/1.13/packages/_sylius.yaml @@ -0,0 +1,15 @@ +parameters: + test_default_state_machine_adapter: 'winzou_state_machine' + test_sylius_state_machine_adapter: '%env(string:default:test_default_state_machine_adapter:TEST_SYLIUS_STATE_MACHINE_ADAPTER)%' + +sylius_state_machine_abstraction: + graphs_to_adapters_mapping: + sylius_catalog_promotion: '%test_sylius_state_machine_adapter%' + sylius_order: '%test_sylius_state_machine_adapter%' + sylius_order_checkout: '%test_sylius_state_machine_adapter%' + sylius_order_payment: '%test_sylius_state_machine_adapter%' + sylius_order_shipping: '%test_sylius_state_machine_adapter%' + sylius_payment: '%test_sylius_state_machine_adapter%' + sylius_product_review: '%test_sylius_state_machine_adapter%' + sylius_shipment: '%test_sylius_state_machine_adapter%' + default_adapter: '%test_default_state_machine_adapter%' diff --git a/tests/Application/package.json b/tests/Application/package.json index 32ccdc44..b428c24b 100644 --- a/tests/Application/package.json +++ b/tests/Application/package.json @@ -1,68 +1,13 @@ { - "dependencies": { - "@babel/polyfill": "^7.0.0", - "chart.js": "^3.7.1", - "jquery": "^3.5.0", - "jquery.dirtyforms": "^2.0.0", - "lightbox2": "^2.9.0", - "semantic-ui-css": "^2.2.0", - "slick-carousel": "^1.8.1" - }, - "devDependencies": { - "@babel/core": "^7.0.0", - "@babel/plugin-external-helpers": "^7.0.0", - "@babel/plugin-proposal-object-rest-spread": "^7.18.9", - "@babel/preset-env": "^7.18.10", - "@babel/register": "^7.0.0", - "@rollup/plugin-babel": "^5.3.1", - "@rollup/plugin-commonjs": "^22.0.2", - "@rollup/plugin-inject": "^4.0.4", - "@rollup/plugin-node-resolve": "^13.3.0", - "@semantic-ui-react/css-patch": "^1.1.2", - "@symfony/webpack-encore": "^3.1.0", - "babel-plugin-fast-async": "^6.1.2", - "babel-plugin-module-resolver": "^4.1.0", - "dedent": "^0.7.0", - "eslint": "^8.23.0", - "eslint-config-airbnb-base": "^15.0.0", - "eslint-import-resolver-babel-module": "^5.3.1", - "eslint-plugin-import": "^2.26.0", - "fast-async": "^6.3.8", - "gulp": "^4.0.2", - "gulp-chug": "^0.5.1", - "gulp-concat": "^2.6.1", - "gulp-debug": "^4.0.0", - "gulp-if": "^3.0.0", - "gulp-livereload": "^4.0.2", - "gulp-order": "^1.2.0", - "gulp-sass": "^5.1.0", - "gulp-sourcemaps": "^3.0.0", - "gulp-uglifycss": "^1.1.0", - "merge-stream": "^2.0.0", - "rollup": "^2.79.0", - "rollup-plugin-terser": "^7.0.2", - "sass": "^1.54.8", - "sass-loader": "^13.0.0", - "upath": "^2.0.1", - "yargs": "^17.5.1" - }, - "engines": { - "node": "^14 || ^16 || ^18" - }, - "engineStrict": true, + "license": "UNLICENSED", "scripts": { - "watch": "encore dev --watch", "build": "encore dev", "build:prod": "encore production", - "gulp": "gulp build", + "postinstall": "semantic-ui-css-patch", "lint": "yarn lint:js", - "lint:js": "eslint gulpfile.babel.js src/Sylius/Bundle/AdminBundle/gulpfile.babel.js src/Sylius/Bundle/ShopBundle/gulpfile.babel.js src/Sylius/Bundle/UiBundle/Resources/private/js src/Sylius/Bundle/AdminBundle/Resources/private/js src/Sylius/Bundle/ShopBundle/Resources/private/js", - "postinstall": "semantic-ui-css-patch" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Sylius/Sylius.git" + "watch": "encore dev --watch" }, - "author": "Paweł Jędrzejewski", - "license": "MIT" + "devDependencies": { + "@sylius-ui/frontend": "^1.0" + } } diff --git a/tests/Behat/Context/Admin/ManagingOrdersContext.php b/tests/Behat/Context/Admin/ManagingOrdersContext.php index d31b2821..27cae68d 100644 --- a/tests/Behat/Context/Admin/ManagingOrdersContext.php +++ b/tests/Behat/Context/Admin/ManagingOrdersContext.php @@ -32,7 +32,7 @@ public function __construct( FactoryInterface $stateMachineFactory, ObjectManager $objectManager, KernelBrowser $client, - ShowPageInterface $showPage + ShowPageInterface $showPage, ) { $this->stateMachineFactory = $stateMachineFactory; $this->objectManager = $objectManager; @@ -47,7 +47,7 @@ public function __construct( public function thisOrderIsAlreadyPaidAsPayPalOrder( OrderInterface $order, string $payPalOrderId, - ?string $payPalPaymentId = null + ?string $payPalPaymentId = null, ): void { /** @var PaymentInterface $payment */ $payment = $order->getPayments()->first(); @@ -76,7 +76,7 @@ public function requestFromPayPalAboutOrderRefundHasBeenReceived(string $payPalO 'resource_type' => 'refund', 'resource' => [ 'id' => $payPalOrderId, - 'amount' => ['currency_code' => 'USD', 'amount' => (string) ($this->refundAmount/100)], + 'amount' => ['currency_code' => 'USD', 'amount' => (string) ($this->refundAmount / 100)], 'status' => 'COMPLETED', 'links' => [ ['rel' => 'up', 'href' => $payPalOrderId], diff --git a/tests/Behat/Context/Admin/ManagingPaymentMethodsContext.php b/tests/Behat/Context/Admin/ManagingPaymentMethodsContext.php index 493e71c5..05b78b41 100644 --- a/tests/Behat/Context/Admin/ManagingPaymentMethodsContext.php +++ b/tests/Behat/Context/Admin/ManagingPaymentMethodsContext.php @@ -8,7 +8,6 @@ use Behat\Mink\Exception\ElementNotFoundException; use Sylius\Behat\Exception\NotificationExpectationMismatchException; use Sylius\Behat\NotificationType; -use Sylius\Behat\Page\Admin\Crud\IndexPageInterface; use Sylius\Behat\Page\Admin\PaymentMethod\CreatePageInterface; use Sylius\Behat\Service\NotificationCheckerInterface; use Tests\Sylius\PayPalPlugin\Behat\Element\DownloadPayPalReportElementInterface; @@ -25,7 +24,7 @@ final class ManagingPaymentMethodsContext implements Context public function __construct( DownloadPayPalReportElementInterface $downloadPayPalReportElement, NotificationCheckerInterface $notificationChecker, - CreatePageInterface $createPage + CreatePageInterface $createPage, ) { $this->downloadPayPalReportElement = $downloadPayPalReportElement; $this->notificationChecker = $notificationChecker; @@ -63,7 +62,7 @@ public function iShouldBeNotifiedThatICannotOnboardMoreThanOnePayPalSeller(): vo { $this->notificationChecker->checkNotification( 'You cannot onboard more than one PayPal seller!', - NotificationType::failure() + NotificationType::failure(), ); } @@ -75,7 +74,7 @@ public function iShouldNotBeNotifiedThatICannotOnboardMoreThanOnePayPalSeller(): try { $this->notificationChecker->checkNotification( 'You cannot onboard more than one PayPal seller!', - NotificationType::failure() + NotificationType::failure(), ); } catch (NotificationExpectationMismatchException|ElementNotFoundException $exception) { return; diff --git a/tests/Behat/Context/Setup/PaymentPayPalContext.php b/tests/Behat/Context/Setup/PaymentPayPalContext.php index 3fc96a49..8d16804a 100644 --- a/tests/Behat/Context/Setup/PaymentPayPalContext.php +++ b/tests/Behat/Context/Setup/PaymentPayPalContext.php @@ -45,7 +45,7 @@ public function __construct( array $gatewayFactories, TranslatorInterface $translator, PayPalSelectPaymentPageInterface $selectPaymentPage, - string $clientId + string $clientId, ) { $this->sharedStorage = $sharedStorage; $this->paymentMethodRepository = $paymentMethodRepository; @@ -78,7 +78,7 @@ private function createPaymentMethod( string $code, string $gatewayFactory, string $description, - int $position + int $position, ): void { $gatewayFactory = $this->findGatewayNameByTranslation($gatewayFactory, $this->gatewayFactories); diff --git a/tests/Behat/Resources/services.xml b/tests/Behat/Resources/services.xml index bbb5b3b2..b7b2df86 100644 --- a/tests/Behat/Resources/services.xml +++ b/tests/Behat/Resources/services.xml @@ -4,10 +4,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd" > - - - - diff --git a/tests/Behat/Resources/services/mailer.php b/tests/Behat/Resources/services/mailer.php deleted file mode 100644 index 649a7f31..00000000 --- a/tests/Behat/Resources/services/mailer.php +++ /dev/null @@ -1,18 +0,0 @@ - 11) { - return; - } - - $configurator->services() - ->alias('sylius.behat.context.hook.mailer', 'sylius.behat.context.hook.email_spool') - ->public() - ; -}; diff --git a/tests/Functional/CreatePayPalOrderActionTest.php b/tests/Functional/CreatePayPalOrderActionTest.php index f05cb13a..47ec9952 100644 --- a/tests/Functional/CreatePayPalOrderActionTest.php +++ b/tests/Functional/CreatePayPalOrderActionTest.php @@ -9,7 +9,7 @@ final class CreatePayPalOrderActionTest extends JsonApiTestCase { /** @test */ - function it_creates_pay_pal_order_and_returns_its_data(): void + public function it_creates_pay_pal_order_and_returns_its_data(): void { $this->loadFixturesFromFiles(['resources/shop.yaml', 'resources/new_order.yaml']); diff --git a/tests/Functional/CreatePayPalOrderFromCartActionTest.php b/tests/Functional/CreatePayPalOrderFromCartActionTest.php index e70ed642..aa5a0b0a 100644 --- a/tests/Functional/CreatePayPalOrderFromCartActionTest.php +++ b/tests/Functional/CreatePayPalOrderFromCartActionTest.php @@ -9,7 +9,7 @@ final class CreatePayPalOrderFromCartActionTest extends JsonApiTestCase { /** @test */ - function it_creates_pay_pal_order_from_cart_and_returns_its_data(): void + public function it_creates_pay_pal_order_from_cart_and_returns_its_data(): void { $order = $this->loadFixturesFromFiles(['resources/shop.yaml', 'resources/new_cart.yaml']); /** @var int $orderId */ diff --git a/tests/Functional/CreatePayPalOrderFromPaymentPageActionTest.php b/tests/Functional/CreatePayPalOrderFromPaymentPageActionTest.php index 35ec88c2..32a28f0d 100644 --- a/tests/Functional/CreatePayPalOrderFromPaymentPageActionTest.php +++ b/tests/Functional/CreatePayPalOrderFromPaymentPageActionTest.php @@ -9,7 +9,7 @@ final class CreatePayPalOrderFromPaymentPageActionTest extends JsonApiTestCase { /** @test */ - function it_creates_pay_pal_order_from_payment_page_and_returns_its_data(): void + public function it_creates_pay_pal_order_from_payment_page_and_returns_its_data(): void { $order = $this->loadFixturesFromFiles(['resources/shop.yaml', 'resources/new_cart.yaml']); /** @var int $orderId */ diff --git a/tests/Service/DummyRefundPaymentApi.php b/tests/Service/DummyRefundPaymentApi.php index 6a22b9c0..37e97868 100644 --- a/tests/Service/DummyRefundPaymentApi.php +++ b/tests/Service/DummyRefundPaymentApi.php @@ -14,7 +14,7 @@ public function refund( string $payPalAuthAssertion, string $invoiceNumber, string $amount, - string $currencyCode + string $currencyCode, ): array { return ['status' => 'COMPLETED', 'id' => $paymentId]; } diff --git a/tests/Unit/PayPalGatewayFactoryTest.php b/tests/Unit/PayPalGatewayFactoryTest.php index 8ce3f603..73ba8c13 100644 --- a/tests/Unit/PayPalGatewayFactoryTest.php +++ b/tests/Unit/PayPalGatewayFactoryTest.php @@ -13,11 +13,9 @@ namespace Tests\Sylius\PayPalPlugin\Unit; -use Payum\Core\Bridge\Spl\ArrayObject; use PHPUnit\Framework\TestCase; use Sylius\PayPalPlugin\Payum\Action\StatusAction; use Sylius\PayPalPlugin\Payum\Factory\PayPalGatewayFactory; -use Sylius\PayPalPlugin\Payum\Model\PayPalApi; final class PayPalGatewayFactoryTest extends TestCase {