From 211a0dca5c7cb67f4a08abfe0a4ce9de3f7b6610 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 12:01:10 +0100 Subject: [PATCH 01/12] [BUGFIX] Ignore payment providers without clearing type The ProviderRedirect listener splits the provider of every payment into provider and clearing type. Providers of other extensions without an underscore, e.g. PAYPAL of cart_paypal, caused the warning "Undefined array key 1". The missing clearing type defaults to an empty string now, like in the PaymentController. Co-Authored-By: Claude Opus 5.5 --- Classes/EventListener/Order/Payment/ProviderRedirect.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Classes/EventListener/Order/Payment/ProviderRedirect.php b/Classes/EventListener/Order/Payment/ProviderRedirect.php index ad1ed96..16377a0 100644 --- a/Classes/EventListener/Order/Payment/ProviderRedirect.php +++ b/Classes/EventListener/Order/Payment/ProviderRedirect.php @@ -76,7 +76,7 @@ public function __invoke(PaymentEvent $event): void $payment = $this->orderItem->getPayment(); $provider = $payment->getProvider(); - [$provider, $clearingType] = explode('_', (string)$provider); + [$provider, $clearingType] = array_pad(explode('_', (string)$provider), 2, ''); if ($provider !== 'GIROSOLUTION') { return; From 693789650e25017fcc670e6e6e58e7ba8403e7e5 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 12:01:10 +0100 Subject: [PATCH 02/12] [BUGFIX] Respond to payment notification without template Girosolution calls the notifyAction after a payment and only expects the HTTP status. The action rendered a template that does not exist, so the request failed after the payment had been updated, and Girosolution retried the notification. The action returns an empty response now. Co-Authored-By: Claude Opus 5.5 --- Classes/Controller/Order/PaymentController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Classes/Controller/Order/PaymentController.php b/Classes/Controller/Order/PaymentController.php index b484f5e..bb8d52e 100644 --- a/Classes/Controller/Order/PaymentController.php +++ b/Classes/Controller/Order/PaymentController.php @@ -143,7 +143,7 @@ public function notifyAction(): ResponseInterface } $notify->sendOkStatus(); - return $this->htmlResponse(); + return $this->htmlResponse(''); } private function updatePaymentAndTransaction($notify, Item $orderItem, string $status): bool From 74647766adc45a342419cd4fc34d66ab9f20290d Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 12:03:51 +0100 Subject: [PATCH 03/12] [TASK] Add unit and functional tests The extension had no tests so far. The setup follows the other cart extensions: Build/phpunit.xml.dist with the testsuites unit and functional, run via Build/Scripts/phpunit.sh, the composer scripts project:test:unit and project:test:functional, the commands project-test-unit and project-test-functional in shell.nix and a CI job for all supported PHP versions. The tests are linted and analysed by PHPStan as well, Build/phpunit.xml.dist is validated by the xml lint. The unit tests cover the credential loaders, the events and the event listeners as far as they do not need the API of Girosolution. The functional tests send the notification of Girosolution to the frontend and check the stored payment and transaction and the dispatched events for successful and canceled payments, for repeated notifications, for a wrong hash and an unknown cart. They also verify that credentials from TYPO3_CONF_VARS override the ones from TypoScript. The events are recorded by the listener of the test extension girosolution_test, as frontend requests use their own listener provider. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 3 +- .github/workflows/ci.yaml | 39 ++++ Build/Scripts/lint-php.sh | 2 +- Build/Scripts/lint-xml.sh | 9 +- Build/Scripts/phpunit.sh | 57 +++++ Build/phpstan.neon | 1 + Build/phpunit.xml.dist | 33 +++ .../AbstractPaymentControllerTestCase.php | 135 ++++++++++++ .../Order/PaymentControllerTest.php | 131 +++++++++++ ...trollerWithCredentialsFromConfVarsTest.php | 61 ++++++ Tests/Functional/Fixtures/DataSets/Base.php | 49 +++++ Tests/Functional/Fixtures/DataSets/Order.php | 37 ++++ .../Classes/EventListener/EventRecorder.php | 45 ++++ .../Configuration/Services.yaml | 14 ++ .../girosolution_test/composer.json | 21 ++ .../Fixtures/Sites/default/config.yaml | 13 ++ .../CredentialLoaderRegistryTest.php | 129 +++++++++++ .../CredentialsFromConfVarsTest.php | 100 +++++++++ .../CredentialsFromTypoScriptTest.php | 90 ++++++++ Tests/Unit/Event/Order/CancelEventTest.php | 92 ++++++++ Tests/Unit/Event/Order/FinishEventTest.php | 92 ++++++++ .../Order/Payment/ClearCartTest.php | 204 ++++++++++++++++++ .../Order/Payment/ProviderRedirectTest.php | 147 +++++++++++++ composer.json | 14 +- shell.nix | 22 ++ 25 files changed, 1534 insertions(+), 6 deletions(-) create mode 100755 Build/Scripts/phpunit.sh create mode 100644 Build/phpunit.xml.dist create mode 100644 Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php create mode 100644 Tests/Functional/Controller/Order/PaymentControllerTest.php create mode 100644 Tests/Functional/Controller/Order/PaymentControllerWithCredentialsFromConfVarsTest.php create mode 100644 Tests/Functional/Fixtures/DataSets/Base.php create mode 100644 Tests/Functional/Fixtures/DataSets/Order.php create mode 100644 Tests/Functional/Fixtures/Extensions/girosolution_test/Classes/EventListener/EventRecorder.php create mode 100644 Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.yaml create mode 100644 Tests/Functional/Fixtures/Extensions/girosolution_test/composer.json create mode 100644 Tests/Functional/Fixtures/Sites/default/config.yaml create mode 100644 Tests/Unit/Configuration/CredentialLoaderRegistryTest.php create mode 100644 Tests/Unit/Configuration/CredentialsFromConfVarsTest.php create mode 100644 Tests/Unit/Configuration/CredentialsFromTypoScriptTest.php create mode 100644 Tests/Unit/Event/Order/CancelEventTest.php create mode 100644 Tests/Unit/Event/Order/FinishEventTest.php create mode 100644 Tests/Unit/EventListener/Order/Payment/ClearCartTest.php create mode 100644 Tests/Unit/EventListener/Order/Payment/ProviderRedirectTest.php diff --git a/.gitattributes b/.gitattributes index c69c6c8..624c649 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,6 @@ /.github/ export-ignore /Build/ export-ignore +/Tests/ export-ignore /.editorconfig export-ignore /.gitattributes export-ignore /.gitlab-ci.yml export-ignore @@ -7,4 +8,4 @@ /crowdin.yml export-ignore /Makefile export-ignore /rector.php export-ignore -/shell.nix export-ignore \ No newline at end of file +/shell.nix export-ignore diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 76eacfc..f79805d 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -59,6 +59,15 @@ jobs: - name: Install xmllint run: sudo apt-get update && sudo apt-get install -y libxml2-utils + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.2" + tools: composer:v2 + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-suggest + - name: XML lint run: Build/Scripts/lint-xml.sh @@ -135,3 +144,33 @@ jobs: - name: Code Quality (by PHPStan) run: Build/Scripts/phpstan.sh + + tests-unit-and-functional: + runs-on: ubuntu-latest + needs: + - coding-guideline + - code-quality + strategy: + matrix: + php-version: + - 8.2 + - 8.3 + - 8.4 + - 8.5 + steps: + - uses: actions/checkout@v4 + + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php-version }}" + tools: composer:v2 + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-suggest + + - name: Run unit tests + run: Build/Scripts/phpunit.sh unit + + - name: Run functional tests + run: Build/Scripts/phpunit.sh functional diff --git a/Build/Scripts/lint-php.sh b/Build/Scripts/lint-php.sh index b954914..1b86352 100755 --- a/Build/Scripts/lint-php.sh +++ b/Build/Scripts/lint-php.sh @@ -7,5 +7,5 @@ source "$(dirname "${BASH_SOURCE[0]}")/common.sh" -find ./*.php Classes Configuration -name '*.php' -print0 \ +find ./*.php Classes Configuration Tests -name '*.php' -print0 \ | xargs -0 -n 1 -P 4 "${PHP_BIN}" -l diff --git a/Build/Scripts/lint-xml.sh b/Build/Scripts/lint-xml.sh index 9766e04..06b4e08 100755 --- a/Build/Scripts/lint-xml.sh +++ b/Build/Scripts/lint-xml.sh @@ -1,7 +1,9 @@ #!/usr/bin/env bash # -# Validates the XLIFF files in Resources/Private/Language against XLIFF 1.2 -# strict (Build/xliff-core-1.2-strict.xsd, imports Build/xml.xsd). +# Validates the xml files of the extension against their schemas: +# - XLIFF files in Resources/Private/Language against XLIFF 1.2 strict +# (Build/xliff-core-1.2-strict.xsd, imports Build/xml.xsd) +# - Build/phpunit.xml.dist against the schema of the installed PHPUnit # # xmllint is not installed via composer. It is provided by shell.nix, in CI it # is installed via apt (libxml2-utils). @@ -15,8 +17,11 @@ if ! command -v xmllint > /dev/null; then echo "Missing xmllint, please install it first, e.g. the package libxml2-utils." >&2 exit 1 fi +requireBinary phpunit if [ -d Resources/Private/Language ]; then find Resources/Private/Language -name '*.xlf' -print0 \ | xargs -0 -r xmllint --schema Build/xliff-core-1.2-strict.xsd --noout fi + +xmllint --schema .Build/vendor/phpunit/phpunit/phpunit.xsd --noout Build/phpunit.xml.dist diff --git a/Build/Scripts/phpunit.sh b/Build/Scripts/phpunit.sh new file mode 100755 index 0000000..2636b97 --- /dev/null +++ b/Build/Scripts/phpunit.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# +# Runs the phpunit tests. +# +# Usage: +# Build/Scripts/phpunit.sh [testsuite] [additional phpunit arguments] +# +# Without a testsuite every suite defined in Build/phpunit.xml.dist is run, +# each one in its own phpunit process. They cannot share a process, the +# functional bootstrap leaks global state into the unit tests. The first +# argument is taken as the testsuite name unless it starts with a dash. +# +# Environment variables used as overrides: +# typo3DatabaseDriver database driver to test against, defaults to "pdo_sqlite" + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +requireBinary phpunit + +export typo3DatabaseDriver="${typo3DatabaseDriver:-pdo_sqlite}" + +runSuite() { + local suite="$1" + shift + + runPhp "${BIN_DIR}/phpunit" \ + -c Build/phpunit.xml.dist \ + --testsuite "${suite}" \ + --display-warnings \ + --display-deprecations \ + --display-errors \ + --display-notices \ + "$@" +} + +if [ $# -gt 0 ] && [ -n "$1" ] && [ "${1:0:1}" != "-" ]; then + TESTSUITE="$1" + shift + runSuite "${TESTSUITE}" "$@" + exit $? +fi + +mapfile -t SUITES < <(runPhp "${BIN_DIR}/phpunit" -c Build/phpunit.xml.dist --list-suites \ + | sed -n 's/^ - \(.*\) ([0-9]\{1,\} tests\{0,1\})$/\1/p') + +if [ ${#SUITES[@]} -eq 0 ]; then + echo "No testsuites found in Build/phpunit.xml.dist." >&2 + exit 1 +fi + +STATUS=0 +for suite in "${SUITES[@]}"; do + echo "Running testsuite \"${suite}\" ..." + runSuite "${suite}" "$@" || STATUS=$? +done + +exit "${STATUS}" diff --git a/Build/phpstan.neon b/Build/phpstan.neon index 871d987..13c6770 100644 --- a/Build/phpstan.neon +++ b/Build/phpstan.neon @@ -5,5 +5,6 @@ parameters: paths: - ../Classes - ../Configuration + - ../Tests - ../ext_emconf.php - ../ext_localconf.php diff --git a/Build/phpunit.xml.dist b/Build/phpunit.xml.dist new file mode 100644 index 0000000..37fceac --- /dev/null +++ b/Build/phpunit.xml.dist @@ -0,0 +1,33 @@ + + + + + + ../Tests/Functional/ + + + ../Tests/Unit/ + + + + + ../Classes/ + + + diff --git a/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php new file mode 100644 index 0000000..bbdf804 --- /dev/null +++ b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php @@ -0,0 +1,135 @@ + 'typo3conf/sites', + ]; + + protected array $configurationToUseInTestInstance = [ + 'FE' => [ + 'cacheHash' => [ + 'enforceValidation' => false, + ], + ], + 'MAIL' => [ + 'transport' => 'null', + ], + ]; + + protected function setUp(): void + { + parent::setUp(); + + $this->importPHPDataSet(__DIR__ . '/../../Fixtures/DataSets/Base.php'); + $this->importPHPDataSet(__DIR__ . '/../../Fixtures/DataSets/Order.php'); + + $cart = new Cart([]); + $cart->setBillingCountry('de'); + + $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_cart') + ->insert('tx_cart_domain_model_cart', [ + 'uid' => 1, + 'pid' => 2, + 's_hash' => self::CART_HASH, + 'order_item' => 1, + 'serialized_cart' => serialize($cart), + ]); + + EventRecorder::reset(); + } + + protected function sendNotification( + string $resultPayment, + string $secret, + string $cartHash = self::CART_HASH, + ): ResponseInterface { + $notification = [ + 'gcReference' => self::GC_REFERENCE, + 'gcMerchantTxId' => md5('ORD-2026-0001'), + 'gcBackendTxId' => 'gc-backend-tx-0001', + 'gcAmount' => '11900', + 'gcCurrency' => 'EUR', + 'gcResultPayment' => $resultPayment, + ]; + $notification['gcHash'] = hash_hmac('md5', implode('', $notification), $secret); + + // The controller reads the notification from $_GET, like the SDK of Girosolution expects it. + $_GET = $notification; + + return $this->executeFrontendSubRequest( + (new InternalRequest('http://localhost/')) + ->withPageId(1) + ->withQueryParameters([ + 'type' => 2278106, + 'tx_cartgirosolution_cart[controller]' => 'Order\\Payment', + 'tx_cartgirosolution_cart[action]' => 'notify', + 'tx_cartgirosolution_cart[hash]' => $cartHash, + ] + $notification) + ); + } + + protected function getPayment(): array + { + return $this->getRecord('tx_cart_domain_model_order_payment', ['status']); + } + + protected function getTransaction(): array + { + return $this->getRecord('tx_cart_domain_model_order_transaction', ['status', 'external_status_code', 'note']); + } + + private function getRecord(string $table, array $fields): array + { + $record = $this->get(ConnectionPool::class) + ->getConnectionForTable($table) + ->select($fields, $table, ['uid' => 1]) + ->fetchAssociative(); + + self::assertIsArray($record); + + return $record; + } +} diff --git a/Tests/Functional/Controller/Order/PaymentControllerTest.php b/Tests/Functional/Controller/Order/PaymentControllerTest.php new file mode 100644 index 0000000..5b0ac11 --- /dev/null +++ b/Tests/Functional/Controller/Order/PaymentControllerTest.php @@ -0,0 +1,131 @@ +sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame('paid', $this->getPayment()['status']); + self::assertSame( + [ + 'status' => 'paid', + 'external_status_code' => self::RESULT_PAYMENT_SUCCESSFUL, + 'note' => 'gc-backend-tx-0001', + ], + $this->getTransaction() + ); + } + + #[Test] + public function successfulPaymentDispatchesFinishEvent(): void + { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); + self::assertArrayNotHasKey(CancelEvent::class, EventRecorder::getEvents()); + + $event = EventRecorder::getEvents()[FinishEvent::class][0]; + self::assertInstanceOf(FinishEvent::class, $event); + self::assertSame('ORD-2026-0001', $event->getOrderItem()->getOrderNumber()); + self::assertSame('1', (string)$event->getSettings()['settings']['cart']['pid']); + } + + #[Test] + public function canceledPaymentMarksPaymentAndTransactionAsCanceled(): void + { + $this->sendNotification(self::RESULT_PAYMENT_CANCELED, self::TYPOSCRIPT_SECRET); + + self::assertSame('canceled', $this->getPayment()['status']); + self::assertSame( + [ + 'status' => 'canceled', + 'external_status_code' => self::RESULT_PAYMENT_CANCELED, + 'note' => 'gc-backend-tx-0001', + ], + $this->getTransaction() + ); + } + + #[Test] + public function canceledPaymentDispatchesCancelEvent(): void + { + $this->sendNotification(self::RESULT_PAYMENT_CANCELED, self::TYPOSCRIPT_SECRET); + + self::assertCount(1, EventRecorder::getEvents()[CancelEvent::class] ?? []); + self::assertArrayNotHasKey(FinishEvent::class, EventRecorder::getEvents()); + } + + #[Test] + public function repeatedNotificationDoesNotDispatchTheEventAgain(): void + { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame('paid', $this->getPayment()['status']); + self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); + } + + #[Test] + public function notificationWithWrongHashIsRejected(): void + { + try { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, 'wrong-secret'); + self::fail('The notification with a wrong hash has been accepted.'); + } catch (GiroCheckout_SDK_Exception_helper $exception) { + self::assertStringContainsString('hash mismatch', $exception->getMessage()); + } + + self::assertSame('open', $this->getPayment()['status']); + self::assertSame('created', $this->getTransaction()['status']); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function notificationForUnknownCartIsRejected(): void + { + try { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET, 'unknown-cart-hash'); + self::fail('The notification for an unknown cart has been accepted.'); + } catch (\InvalidArgumentException $exception) { + self::assertSame(1734097682, $exception->getCode()); + } + + self::assertSame('open', $this->getPayment()['status']); + self::assertSame([], EventRecorder::getEvents()); + } + + #[Test] + public function notifyActionRespondsWithEmptyBody(): void + { + $response = $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame(200, $response->getStatusCode()); + self::assertSame('', trim((string)$response->getBody())); + } +} diff --git a/Tests/Functional/Controller/Order/PaymentControllerWithCredentialsFromConfVarsTest.php b/Tests/Functional/Controller/Order/PaymentControllerWithCredentialsFromConfVarsTest.php new file mode 100644 index 0000000..eb09264 --- /dev/null +++ b/Tests/Functional/Controller/Order/PaymentControllerWithCredentialsFromConfVarsTest.php @@ -0,0 +1,61 @@ +configurationToUseInTestInstance['EXTENSIONS']['cart_girosolution'] = [ + 'credentials' => [ + 'creditCard' => [ + 'password' => self::CONF_VARS_SECRET, + ], + ], + ]; + + parent::setUp(); + } + + #[Test] + public function acceptsNotificationSignedWithPasswordOfConfVars(): void + { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::CONF_VARS_SECRET); + + self::assertSame('paid', $this->getPayment()['status']); + } + + #[Test] + public function rejectsNotificationSignedWithPasswordOfTypoScript(): void + { + $this->expectException(GiroCheckout_SDK_Exception_helper::class); + + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + } +} diff --git a/Tests/Functional/Fixtures/DataSets/Base.php b/Tests/Functional/Fixtures/DataSets/Base.php new file mode 100644 index 0000000..36972b5 --- /dev/null +++ b/Tests/Functional/Fixtures/DataSets/Base.php @@ -0,0 +1,49 @@ + [ + [ + 'uid' => 1, + 'pid' => 0, + 'title' => 'Cart', + 'doktype' => PageRepository::DOKTYPE_DEFAULT, + 'slug' => '/', + 'is_siteroot' => 1, + ], + [ + 'uid' => 2, + 'pid' => 1, + 'title' => 'Orders', + 'doktype' => PageRepository::DOKTYPE_SYSFOLDER, + 'slug' => '/orders', + ], + ], + 'sys_template' => [ + [ + 'uid' => 1, + 'pid' => 1, + 'title' => 'Root', + 'root' => 1, + 'clear' => 3, + 'include_static_file' => implode(',', [ + 'EXT:cart/Configuration/TypoScript', + 'EXT:cart_girosolution/Configuration/TypoScript', + ]), + 'constants' => implode(PHP_EOL, [ + 'plugin.tx_cart.settings.cart.pid = 1', + 'plugin.tx_cart.settings.order.pid = 2', + ]), + 'config' => implode(PHP_EOL, [ + 'plugin.tx_cartgirosolution.credentials.creditCard {', + ' merchantId = 1234', + ' projectId = 5678', + ' password = credit-card-secret', + '}', + ]), + ], + ], +]; diff --git a/Tests/Functional/Fixtures/DataSets/Order.php b/Tests/Functional/Fixtures/DataSets/Order.php new file mode 100644 index 0000000..6089abc --- /dev/null +++ b/Tests/Functional/Fixtures/DataSets/Order.php @@ -0,0 +1,37 @@ + [ + [ + 'uid' => 1, + 'pid' => 2, + 'order_number' => 'ORD-2026-0001', + 'currency_code' => 'EUR', + 'total_gross' => 119.0, + 'payment' => 1, + ], + ], + 'tx_cart_domain_model_order_payment' => [ + [ + 'uid' => 1, + 'pid' => 2, + 'item' => 1, + 'service_id' => 1, + 'name' => 'Credit Card', + 'provider' => 'GIROSOLUTION_CREDITCARD', + 'status' => 'open', + 'transactions' => 1, + ], + ], + 'tx_cart_domain_model_order_transaction' => [ + [ + 'uid' => 1, + 'pid' => 2, + 'payment' => 1, + 'txn_id' => 'gc-reference-0001', + 'status' => 'created', + ], + ], +]; diff --git a/Tests/Functional/Fixtures/Extensions/girosolution_test/Classes/EventListener/EventRecorder.php b/Tests/Functional/Fixtures/Extensions/girosolution_test/Classes/EventListener/EventRecorder.php new file mode 100644 index 0000000..86ec141 --- /dev/null +++ b/Tests/Functional/Fixtures/Extensions/girosolution_test/Classes/EventListener/EventRecorder.php @@ -0,0 +1,45 @@ + + */ + private static array $events = []; + + public function __invoke(object $event): void + { + self::$events[$event::class][] = $event; + } + + /** + * @return array + */ + public static function getEvents(): array + { + return self::$events; + } + + public static function reset(): void + { + self::$events = []; + } +} diff --git a/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.yaml b/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.yaml new file mode 100644 index 0000000..26ce00e --- /dev/null +++ b/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.yaml @@ -0,0 +1,14 @@ +services: + _defaults: + autowire: true + autoconfigure: true + public: false + + Extcode\GirosolutionTest\EventListener\EventRecorder: + tags: + - name: event.listener + identifier: 'girosolution-test--order--finish--event-recorder' + event: Extcode\CartGirosolution\Event\Order\FinishEvent + - name: event.listener + identifier: 'girosolution-test--order--cancel--event-recorder' + event: Extcode\CartGirosolution\Event\Order\CancelEvent diff --git a/Tests/Functional/Fixtures/Extensions/girosolution_test/composer.json b/Tests/Functional/Fixtures/Extensions/girosolution_test/composer.json new file mode 100644 index 0000000..84533a5 --- /dev/null +++ b/Tests/Functional/Fixtures/Extensions/girosolution_test/composer.json @@ -0,0 +1,21 @@ +{ + "name": "extcode/girosolution-test", + "type": "typo3-cms-extension", + "description": "Records the events of cart_girosolution in functional tests", + "license": [ + "GPL-2.0-or-later" + ], + "autoload": { + "psr-4": { + "Extcode\\GirosolutionTest\\": "Classes/" + } + }, + "require": { + "extcode/cart-girosolution": "*" + }, + "extra": { + "typo3/cms": { + "extension-key": "girosolution_test" + } + } +} diff --git a/Tests/Functional/Fixtures/Sites/default/config.yaml b/Tests/Functional/Fixtures/Sites/default/config.yaml new file mode 100644 index 0000000..be8cc08 --- /dev/null +++ b/Tests/Functional/Fixtures/Sites/default/config.yaml @@ -0,0 +1,13 @@ +base: 'http://localhost/' +languages: + - + title: English + enabled: true + base: / + typo3Language: default + locale: en_US.UTF-8 + navigationTitle: English + flag: us + languageId: 0 +rootPageId: 1 +websiteTitle: tests diff --git a/Tests/Unit/Configuration/CredentialLoaderRegistryTest.php b/Tests/Unit/Configuration/CredentialLoaderRegistryTest.php new file mode 100644 index 0000000..c907c51 --- /dev/null +++ b/Tests/Unit/Configuration/CredentialLoaderRegistryTest.php @@ -0,0 +1,129 @@ +getCredentials()); + } + + #[Test] + public function returnsCredentialsOfASingleLoader(): void + { + $credentials = [ + 'creditCard' => [ + 'merchantId' => '1234', + 'projectId' => '5678', + 'password' => 'secret', + ], + ]; + + $subject = new CredentialLoaderRegistry([ + $this->createLoader($credentials), + ]); + + self::assertSame($credentials, $subject->getCredentials()); + } + + #[Test] + public function ignoresLoadersWithoutCredentials(): void + { + $credentials = [ + 'paypal' => [ + 'password' => 'secret', + ], + ]; + + $subject = new CredentialLoaderRegistry([ + $this->createLoader([]), + $this->createLoader($credentials), + $this->createLoader([]), + ]); + + self::assertSame($credentials, $subject->getCredentials()); + } + + /** + * The loaders are passed ordered by priority, the loader with the highest + * priority comes first. Its values win, the following loaders only add + * values which are missing so far. + */ + #[Test] + public function valuesOfEarlierLoadersOverrideValuesOfLaterLoaders(): void + { + $subject = new CredentialLoaderRegistry([ + $this->createLoader([ + 'creditCard' => [ + 'password' => 'secret-from-first-loader', + ], + ]), + $this->createLoader([ + 'creditCard' => [ + 'merchantId' => '1234', + 'password' => 'secret-from-second-loader', + ], + 'giropay' => [ + 'password' => 'giropay-secret', + ], + ]), + ]); + + self::assertSame( + [ + 'creditCard' => [ + 'merchantId' => '1234', + 'password' => 'secret-from-first-loader', + ], + 'giropay' => [ + 'password' => 'giropay-secret', + ], + ], + $subject->getCredentials() + ); + } + + #[Test] + public function acceptsTraversableOfLoaders(): void + { + $credentials = [ + 'paydirekt' => [ + 'password' => 'secret', + ], + ]; + + $subject = new CredentialLoaderRegistry( + new \ArrayIterator([$this->createLoader($credentials)]) + ); + + self::assertSame($credentials, $subject->getCredentials()); + } + + private function createLoader(array $credentials): CredentialLoaderInterface + { + $loader = self::createStub(CredentialLoaderInterface::class); + $loader->method('getCredentials')->willReturn($credentials); + + return $loader; + } +} diff --git a/Tests/Unit/Configuration/CredentialsFromConfVarsTest.php b/Tests/Unit/Configuration/CredentialsFromConfVarsTest.php new file mode 100644 index 0000000..74e702d --- /dev/null +++ b/Tests/Unit/Configuration/CredentialsFromConfVarsTest.php @@ -0,0 +1,100 @@ +createMock(ExtensionConfiguration::class); + $extensionConfiguration + ->expects(self::once()) + ->method('get') + ->with('cart_girosolution') + ->willReturn([]); + + new CredentialsFromConfVars($extensionConfiguration); + } + + #[Test] + public function returnsCredentialsOfTheExtensionConfiguration(): void + { + $credentials = [ + 'creditCard' => [ + 'merchantId' => '1234', + 'projectId' => '5678', + 'password' => 'secret', + ], + ]; + + $subject = new CredentialsFromConfVars( + $this->createExtensionConfiguration(['credentials' => $credentials]) + ); + + self::assertSame($credentials, $subject->getCredentials()); + } + + public static function configurationWithoutCredentialsDataProvider(): \Generator + { + yield 'empty configuration' => [[]]; + yield 'configuration without credentials' => [['someOtherSetting' => '1']]; + yield 'credentials as string' => [['credentials' => 'secret']]; + } + + #[Test] + #[DataProvider('configurationWithoutCredentialsDataProvider')] + public function returnsEmptyCredentialsWithoutCredentialsInConfiguration(array $configuration): void + { + $subject = new CredentialsFromConfVars( + $this->createExtensionConfiguration($configuration) + ); + + self::assertSame([], $subject->getCredentials()); + } + + #[Test] + public function returnsEmptyCredentialsIfTheExtensionIsNotConfigured(): void + { + $extensionConfiguration = self::createStub(ExtensionConfiguration::class); + $extensionConfiguration + ->method('get') + ->willThrowException(new ExtensionConfigurationExtensionNotConfiguredException('not configured', 1509654728)); + + $subject = new CredentialsFromConfVars($extensionConfiguration); + + self::assertSame([], $subject->getCredentials()); + } + + private function createExtensionConfiguration(array $configuration): ExtensionConfiguration + { + $extensionConfiguration = self::createStub(ExtensionConfiguration::class); + $extensionConfiguration->method('get')->willReturn($configuration); + + return $extensionConfiguration; + } +} diff --git a/Tests/Unit/Configuration/CredentialsFromTypoScriptTest.php b/Tests/Unit/Configuration/CredentialsFromTypoScriptTest.php new file mode 100644 index 0000000..14ee862 --- /dev/null +++ b/Tests/Unit/Configuration/CredentialsFromTypoScriptTest.php @@ -0,0 +1,90 @@ +createMock(ConfigurationManager::class); + $configurationManager + ->expects(self::once()) + ->method('getConfiguration') + ->with(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, 'CartGirosolution') + ->willReturn([]); + + new CredentialsFromTypoScript($configurationManager); + } + + #[Test] + public function returnsCredentialsOfTheTypoScript(): void + { + $credentials = [ + 'giropay' => [ + 'merchantId' => '1234', + 'projectId' => '5678', + 'password' => 'secret', + ], + ]; + + $subject = new CredentialsFromTypoScript( + $this->createConfigurationManager([ + 'redirectTypeNum' => '2278106', + 'credentials' => $credentials, + ]) + ); + + self::assertSame($credentials, $subject->getCredentials()); + } + + public static function configurationWithoutCredentialsDataProvider(): \Generator + { + yield 'empty configuration' => [[]]; + yield 'configuration without credentials' => [['redirectTypeNum' => '2278106']]; + yield 'credentials as string' => [['credentials' => 'secret']]; + } + + #[Test] + #[DataProvider('configurationWithoutCredentialsDataProvider')] + public function returnsEmptyCredentialsWithoutCredentialsInTypoScript(array $configuration): void + { + $subject = new CredentialsFromTypoScript( + $this->createConfigurationManager($configuration) + ); + + self::assertSame([], $subject->getCredentials()); + } + + private function createConfigurationManager(array $configuration): ConfigurationManager + { + $configurationManager = self::createStub(ConfigurationManager::class); + $configurationManager->method('getConfiguration')->willReturn($configuration); + + return $configurationManager; + } +} diff --git a/Tests/Unit/Event/Order/CancelEventTest.php b/Tests/Unit/Event/Order/CancelEventTest.php new file mode 100644 index 0000000..fa47103 --- /dev/null +++ b/Tests/Unit/Event/Order/CancelEventTest.php @@ -0,0 +1,92 @@ +cart = self::createStub(Cart::class); + $this->orderItem = new OrderItem(); + } + + #[Test] + public function implementsTheOrderEventInterfaces(): void + { + $subject = new CancelEvent($this->cart, $this->orderItem); + + self::assertInstanceOf(EventInterface::class, $subject); + self::assertInstanceOf(StoppableEventInterface::class, $subject); + } + + #[Test] + public function returnsGivenCartOrderItemAndSettings(): void + { + $settings = [ + 'settings' => [ + 'cart' => [ + 'pid' => '3', + ], + ], + ]; + + $subject = new CancelEvent($this->cart, $this->orderItem, $settings); + + self::assertSame($this->cart, $subject->getCart()); + self::assertSame($this->orderItem, $subject->getOrderItem()); + self::assertSame($settings, $subject->getSettings()); + } + + #[Test] + public function settingsAreEmptyByDefault(): void + { + $subject = new CancelEvent($this->cart, $this->orderItem); + + self::assertSame([], $subject->getSettings()); + } + + #[Test] + public function propagationIsNotStoppedByDefault(): void + { + $subject = new CancelEvent($this->cart, $this->orderItem); + + self::assertFalse($subject->isPropagationStopped()); + } + + #[Test] + public function propagationCanBeStoppedAndResumed(): void + { + $subject = new CancelEvent($this->cart, $this->orderItem); + + $subject->setPropagationStopped(true); + self::assertTrue($subject->isPropagationStopped()); + + $subject->setPropagationStopped(false); + self::assertFalse($subject->isPropagationStopped()); + } +} diff --git a/Tests/Unit/Event/Order/FinishEventTest.php b/Tests/Unit/Event/Order/FinishEventTest.php new file mode 100644 index 0000000..b1fb4e7 --- /dev/null +++ b/Tests/Unit/Event/Order/FinishEventTest.php @@ -0,0 +1,92 @@ +cart = self::createStub(Cart::class); + $this->orderItem = new OrderItem(); + } + + #[Test] + public function implementsTheOrderEventInterfaces(): void + { + $subject = new FinishEvent($this->cart, $this->orderItem); + + self::assertInstanceOf(EventInterface::class, $subject); + self::assertInstanceOf(StoppableEventInterface::class, $subject); + } + + #[Test] + public function returnsGivenCartOrderItemAndSettings(): void + { + $settings = [ + 'settings' => [ + 'cart' => [ + 'pid' => '3', + ], + ], + ]; + + $subject = new FinishEvent($this->cart, $this->orderItem, $settings); + + self::assertSame($this->cart, $subject->getCart()); + self::assertSame($this->orderItem, $subject->getOrderItem()); + self::assertSame($settings, $subject->getSettings()); + } + + #[Test] + public function settingsAreEmptyByDefault(): void + { + $subject = new FinishEvent($this->cart, $this->orderItem); + + self::assertSame([], $subject->getSettings()); + } + + #[Test] + public function propagationIsNotStoppedByDefault(): void + { + $subject = new FinishEvent($this->cart, $this->orderItem); + + self::assertFalse($subject->isPropagationStopped()); + } + + #[Test] + public function propagationCanBeStoppedAndResumed(): void + { + $subject = new FinishEvent($this->cart, $this->orderItem); + + $subject->setPropagationStopped(true); + self::assertTrue($subject->isPropagationStopped()); + + $subject->setPropagationStopped(false); + self::assertFalse($subject->isPropagationStopped()); + } +} diff --git a/Tests/Unit/EventListener/Order/Payment/ClearCartTest.php b/Tests/Unit/EventListener/Order/Payment/ClearCartTest.php new file mode 100644 index 0000000..b5adc06 --- /dev/null +++ b/Tests/Unit/EventListener/Order/Payment/ClearCartTest.php @@ -0,0 +1,204 @@ + [ + 'cart' => [ + 'pid' => '3', + ], + ], + ]; + + private CartUtility&MockObject $cartUtility; + + private PaymentMethodsFromTypoScriptService&MockObject $paymentMethodsService; + + private SessionHandler&MockObject $sessionHandler; + + private Cart $cart; + + private ClearCart $subject; + + protected function setUp(): void + { + parent::setUp(); + + $this->cartUtility = $this->createMock(CartUtility::class); + $this->paymentMethodsService = $this->createMock(PaymentMethodsFromTypoScriptService::class); + $this->sessionHandler = $this->createMock(SessionHandler::class); + + $payment = self::createStub(ServiceInterface::class); + $payment->method('getId')->willReturn(self::PAYMENT_ID); + + $this->cart = self::createStub(Cart::class); + $this->cart->method('getPayment')->willReturn($payment); + $this->cart->method('getBillingCountry')->willReturn(self::BILLING_COUNTRY); + + $this->subject = new ClearCart( + $this->cartUtility, + $this->paymentMethodsService, + $this->sessionHandler, + ); + } + + public static function otherProviderDataProvider(): \Generator + { + yield 'no provider' => ['']; + yield 'provider of another extension' => ['PAYPAL']; + yield 'provider of another extension with clearing type' => ['PAYONE_CREDITCARD']; + } + + #[Test] + #[DataProvider('otherProviderDataProvider')] + public function doesNothingForPaymentsOfOtherProviders(string $provider): void + { + $this->paymentMethodsService->expects(self::never())->method('getConfigurationsForType'); + $this->cartUtility->expects(self::never())->method('getNewCart'); + $this->sessionHandler->expects(self::never())->method('writeCart'); + $this->sessionHandler->expects(self::never())->method('writeAddress'); + + ($this->subject)($this->createEvent($provider)); + } + + #[Test] + public function doesNothingIfThePaymentMethodsServiceProvidesNoConfiguration(): void + { + $this->cartUtility->expects(self::never())->method('getNewCart'); + $this->sessionHandler->expects(self::never())->method('writeCart'); + $this->sessionHandler->expects(self::never())->method('writeAddress'); + + $subject = new ClearCart( + $this->cartUtility, + self::createStub(PaymentMethodsServiceInterface::class), + $this->sessionHandler, + ); + + $subject($this->createEvent('GIROSOLUTION_CREDITCARD')); + } + + #[Test] + public function doesNotClearTheCartIfPreventClearCartIsSet(): void + { + $this->paymentMethodsService + ->method('getConfigurationsForType') + ->willReturn([ + 'options' => [ + self::PAYMENT_ID => [ + 'preventClearCart' => '1', + ], + ], + ]); + + $this->cartUtility->expects(self::never())->method('getNewCart'); + $this->sessionHandler->expects(self::never())->method('writeCart'); + $this->sessionHandler->expects(self::never())->method('writeAddress'); + + ($this->subject)($this->createEvent('GIROSOLUTION_CREDITCARD')); + } + + public static function paymentConfigurationWithoutPreventClearCartDataProvider(): \Generator + { + yield 'no payment configuration' => [null]; + yield 'no options' => [['options' => []]]; + yield 'preventClearCart not set' => [['options' => [self::PAYMENT_ID => []]]]; + yield 'preventClearCart disabled' => [['options' => [self::PAYMENT_ID => ['preventClearCart' => '0']]]]; + yield 'preventClearCart set for another payment' => [['options' => [self::PAYMENT_ID + 1 => ['preventClearCart' => '1']]]]; + } + + #[Test] + #[DataProvider('paymentConfigurationWithoutPreventClearCartDataProvider')] + public function clearsCartAndAddressesForGirosolutionPayments(?array $paymentConfiguration): void + { + $this->paymentMethodsService + ->expects(self::once()) + ->method('getConfigurationsForType') + ->with('payments', self::BILLING_COUNTRY) + ->willReturn($paymentConfiguration); + + $newCart = self::createStub(Cart::class); + $this->cartUtility + ->expects(self::once()) + ->method('getNewCart') + ->with(self::SETTINGS) + ->willReturn($newCart); + + $this->sessionHandler + ->expects(self::once()) + ->method('writeCart') + ->with('3', $newCart); + + $writtenAddresses = []; + $this->sessionHandler + ->expects(self::exactly(2)) + ->method('writeAddress') + ->willReturnCallback(function (string $key, object $address) use (&$writtenAddresses): void { + $writtenAddresses[$key] = $address::class; + }); + + ($this->subject)($this->createEvent('GIROSOLUTION_GIROPAY')); + + self::assertSame( + [ + 'billing_address_3' => BillingAddress::class, + 'shipping_address_3' => ShippingAddress::class, + ], + $writtenAddresses + ); + } + + #[Test] + public function doesNotStopThePropagationOfTheEvent(): void + { + $event = $this->createEvent('GIROSOLUTION_PAYPAL'); + + ($this->subject)($event); + + self::assertFalse($event->isPropagationStopped()); + } + + private function createEvent(string $provider): PaymentEvent + { + $payment = new Payment(); + $payment->setProvider($provider); + + $orderItem = new OrderItem(); + $orderItem->setPayment($payment); + + return new PaymentEvent($this->cart, $orderItem, self::SETTINGS); + } +} diff --git a/Tests/Unit/EventListener/Order/Payment/ProviderRedirectTest.php b/Tests/Unit/EventListener/Order/Payment/ProviderRedirectTest.php new file mode 100644 index 0000000..de4b5b0 --- /dev/null +++ b/Tests/Unit/EventListener/Order/Payment/ProviderRedirectTest.php @@ -0,0 +1,147 @@ +persistenceManager = $this->createMock(PersistenceManager::class); + $this->cartRepository = $this->createMock(CartRepository::class); + $this->paymentRepository = $this->createMock(PaymentRepository::class); + + $site = self::createStub(Site::class); + $site->method('getRouter')->willReturn(self::createStub(RouterInterface::class)); + + $this->siteFinder = $this->createMock(SiteFinder::class); + $this->siteFinder->method('getSiteByPageId')->willReturn($site); + } + + #[Test] + public function usesTheSiteOfTheCartPage(): void + { + $this->siteFinder + ->expects(self::once()) + ->method('getSiteByPageId') + ->with(3); + + $this->createSubject(); + } + + public static function otherProviderDataProvider(): \Generator + { + yield 'no provider' => ['']; + yield 'provider of another extension' => ['PAYPAL']; + yield 'provider of another extension with clearing type' => ['PAYONE_CREDITCARD']; + } + + #[Test] + #[DataProvider('otherProviderDataProvider')] + public function doesNothingForPaymentsOfOtherProviders(string $provider): void + { + $this->cartRepository->expects(self::never())->method('add'); + $this->paymentRepository->expects(self::never())->method('update'); + $this->persistenceManager->expects(self::never())->method('persistAll'); + + $event = $this->createEvent($provider); + + ($this->createSubject())($event); + + self::assertFalse($event->isPropagationStopped()); + } + + #[Test] + public function throwsExceptionForUnknownClearingType(): void + { + $this->cartRepository->expects(self::never())->method('add'); + + $this->expectExceptionObject(new \InvalidArgumentException('Invalid Clearint Type', 1734099627)); + + ($this->createSubject())($this->createEvent('GIROSOLUTION_UNKNOWN')); + } + + private function createSubject(): ProviderRedirect + { + $configurationManager = self::createStub(ConfigurationManager::class); + $configurationManager + ->method('getConfiguration') + ->willReturnMap([ + [ + ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, + 'CartGirosolution', + null, + ['redirectTypeNum' => '2278106'], + ], + [ + ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, + 'Cart', + null, + ['settings' => ['cart' => ['pid' => '3'], 'order' => ['pid' => '4']]], + ], + ]); + + return new ProviderRedirect( + $configurationManager, + $this->persistenceManager, + $this->siteFinder, + $this->cartRepository, + $this->paymentRepository, + new CredentialLoaderRegistry([]), + ); + } + + private function createEvent(string $provider): PaymentEvent + { + $payment = new Payment(); + $payment->setProvider($provider); + + $orderItem = new OrderItem(); + $orderItem->setPayment($payment); + + return new PaymentEvent(self::createStub(Cart::class), $orderItem); + } +} diff --git a/composer.json b/composer.json index 0a5488d..6505b6d 100644 --- a/composer.json +++ b/composer.json @@ -28,6 +28,12 @@ "Extcode\\CartGirosolution\\": "Classes" } }, + "autoload-dev": { + "psr-4": { + "Extcode\\CartGirosolution\\Tests\\": "Tests/", + "Extcode\\GirosolutionTest\\": "Tests/Functional/Fixtures/Extensions/girosolution_test/Classes/" + } + }, "config": { "bin-dir": ".Build/bin", "vendor-dir": ".Build/vendor", @@ -52,10 +58,12 @@ "typo3/cms-fluid": "^13.4" }, "require-dev": { + "codappix/typo3-php-datasets": "^2.1", "friendsofphp/php-cs-fixer": "^3.64", "helmich/typo3-typoscript-lint": "^3.1", "phpstan/phpstan": "^2.1", - "ssch/typo3-rector": "^3.13" + "ssch/typo3-rector": "^3.13", + "typo3/testing-framework": "^9.5" }, "scripts": { "project:cgl": "Build/Scripts/cgl.sh", @@ -70,6 +78,8 @@ "project:lint:typoscript": "Build/Scripts/lint-typoscript.sh", "project:lint:xml": "Build/Scripts/lint-xml.sh", "project:lint:yaml": "Build/Scripts/lint-yaml.sh", - "project:phpstan": "Build/Scripts/phpstan.sh" + "project:phpstan": "Build/Scripts/phpstan.sh", + "project:test:unit": "Build/Scripts/phpunit.sh unit", + "project:test:functional": "Build/Scripts/phpunit.sh functional" } } diff --git a/shell.nix b/shell.nix index 0c0ad43..f2ce065 100644 --- a/shell.nix +++ b/shell.nix @@ -130,6 +130,26 @@ let ''; }; + projectTestUnit = pkgs.writeShellApplication { + name = "project-test-unit"; + runtimeInputs = [ + php + ]; + text = '' + "$PROJECT_ROOT/Build/Scripts/phpunit.sh" unit + ''; + }; + + projectTestFunctional = pkgs.writeShellApplication { + name = "project-test-functional"; + runtimeInputs = [ + php + ]; + text = '' + "$PROJECT_ROOT/Build/Scripts/phpunit.sh" functional + ''; + }; + in pkgs.mkShellNoCC { name = "TYPO3 Extension extcode/cart-girosolution"; buildInputs = [ @@ -147,6 +167,8 @@ in pkgs.mkShellNoCC { projectLintXml projectLintYaml projectPhpstan + projectTestUnit + projectTestFunctional ]; shellHook = '' From e8bd4a2967dbbcba85f35eda6884cbbbc8896804 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 12:41:01 +0100 Subject: [PATCH 04/12] [TASK] Add command to measure the test coverage Build/Scripts/coverage.sh runs every testsuite in its own phpunit process like phpunit.sh, merges the coverage with phpcov, prints the summary and writes the html report to .Build/coverage. It is available as composer script project:test:coverage and as project-test-coverage in shell.nix, which provides php with xdebug. Co-Authored-By: Claude Opus 5.5 --- Build/Scripts/coverage.sh | 63 +++++++++++++++++++++++++++++++++++++++ composer.json | 4 ++- shell.nix | 11 +++++++ 3 files changed, 77 insertions(+), 1 deletion(-) create mode 100755 Build/Scripts/coverage.sh diff --git a/Build/Scripts/coverage.sh b/Build/Scripts/coverage.sh new file mode 100755 index 0000000..21e6452 --- /dev/null +++ b/Build/Scripts/coverage.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# +# Runs all phpunit tests and measures the code coverage of Classes/. +# +# Usage: +# Build/Scripts/coverage.sh [additional phpunit arguments] +# +# Every testsuite defined in Build/phpunit.xml.dist runs in its own phpunit +# process, like in phpunit.sh, the functional bootstrap leaks global state +# into the unit tests. The coverage of all suites is merged with phpcov, the +# summary is printed and the html report is written to +# .Build/coverage/index.html. +# +# Requirements: +# - php with xdebug or pcov +# +# Environment variables used as overrides: +# typo3DatabaseDriver database driver to test against, defaults to "pdo_sqlite" + +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +requireBinary phpunit +requireBinary phpcov + +if ! runPhp -r 'exit(extension_loaded("xdebug") || extension_loaded("pcov") ? 0 : 1);'; then + echo "Missing coverage driver, please enable xdebug or pcov." >&2 + exit 1 +fi + +export typo3DatabaseDriver="${typo3DatabaseDriver:-pdo_sqlite}" +export XDEBUG_MODE=coverage + +COVERAGE_PATH="${PROJECT_ROOT}/.Build/coverage" +COVERAGE_DATA_PATH="${COVERAGE_PATH}/data" +rm -rf "${COVERAGE_PATH}" +mkdir -p "${COVERAGE_DATA_PATH}" + +mapfile -t SUITES < <(runPhp "${BIN_DIR}/phpunit" -c Build/phpunit.xml.dist --list-suites \ + | sed -n 's/^ - \(.*\) ([0-9]\{1,\} tests\{0,1\})$/\1/p') + +if [ ${#SUITES[@]} -eq 0 ]; then + echo "No testsuites found in Build/phpunit.xml.dist." >&2 + exit 1 +fi + +STATUS=0 +for suite in "${SUITES[@]}"; do + echo "Running testsuite \"${suite}\" ..." + runPhp "${BIN_DIR}/phpunit" \ + -c Build/phpunit.xml.dist \ + --testsuite "${suite}" \ + --coverage-php "${COVERAGE_DATA_PATH}/${suite}.cov" \ + "$@" || STATUS=$? +done + +runPhp "${BIN_DIR}/phpcov" merge \ + --text php://stdout \ + --html "${COVERAGE_PATH}" \ + "${COVERAGE_DATA_PATH}" + +echo "HTML report: ${COVERAGE_PATH}/index.html" + +exit "${STATUS}" diff --git a/composer.json b/composer.json index 6505b6d..c6ee547 100644 --- a/composer.json +++ b/composer.json @@ -62,6 +62,7 @@ "friendsofphp/php-cs-fixer": "^3.64", "helmich/typo3-typoscript-lint": "^3.1", "phpstan/phpstan": "^2.1", + "phpunit/phpcov": "^10.0 || ^11.0 || ^12.0", "ssch/typo3-rector": "^3.13", "typo3/testing-framework": "^9.5" }, @@ -80,6 +81,7 @@ "project:lint:yaml": "Build/Scripts/lint-yaml.sh", "project:phpstan": "Build/Scripts/phpstan.sh", "project:test:unit": "Build/Scripts/phpunit.sh unit", - "project:test:functional": "Build/Scripts/phpunit.sh functional" + "project:test:functional": "Build/Scripts/phpunit.sh functional", + "project:test:coverage": "Build/Scripts/coverage.sh" } } diff --git a/shell.nix b/shell.nix index f2ce065..7722982 100644 --- a/shell.nix +++ b/shell.nix @@ -150,6 +150,16 @@ let ''; }; + projectTestCoverage = pkgs.writeShellApplication { + name = "project-test-coverage"; + runtimeInputs = [ + php + ]; + text = '' + "$PROJECT_ROOT/Build/Scripts/coverage.sh" "$@" + ''; + }; + in pkgs.mkShellNoCC { name = "TYPO3 Extension extcode/cart-girosolution"; buildInputs = [ @@ -169,6 +179,7 @@ in pkgs.mkShellNoCC { projectPhpstan projectTestUnit projectTestFunctional + projectTestCoverage ]; shellHook = '' From 5ead913cbce0cc41f193de0c4299a7ec8cd822e7 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 12:41:01 +0100 Subject: [PATCH 05/12] [TASK] Add functional tests for the redirect action Girosolution redirects the customer to the redirectAction after the payment. The tests check the redirect to the order or back to the cart, the stored payment and transaction, the dispatched events, the cart and flash message restored in the session after a canceled payment and the rejection of requests with a wrong hash or without cart hash. The tests of the notifyAction are moved to their own class and cover PayPal payments, unknown clearing types and payments without transaction as well. TYPO3 v13 sends the redirect of an Extbase plugin via header() instead of the response, so the target of the redirect is not checked on this branch. Co-Authored-By: Claude Opus 5.5 --- .../AbstractPaymentControllerTestCase.php | 53 ++++- ... => PaymentControllerNotifyActionTest.php} | 73 ++++++- .../PaymentControllerRedirectActionTest.php | 185 ++++++++++++++++++ Tests/Functional/Fixtures/DataSets/Base.php | 5 + 4 files changed, 308 insertions(+), 8 deletions(-) rename Tests/Functional/Controller/Order/{PaymentControllerTest.php => PaymentControllerNotifyActionTest.php} (62%) create mode 100644 Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php diff --git a/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php index bbdf804..ffaa220 100644 --- a/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php +++ b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php @@ -67,6 +67,7 @@ protected function setUp(): void $cart = new Cart([]); $cart->setBillingCountry('de'); + $cart->setOrderNumber('ORD-2026-0001'); $this->get(ConnectionPool::class) ->getConnectionForTable('tx_cart_domain_model_cart') @@ -81,10 +82,38 @@ protected function setUp(): void EventRecorder::reset(); } + /** + * Sends the notification, Girosolution calls the notify URL in the + * background after the payment. + */ protected function sendNotification( string $resultPayment, string $secret, - string $cartHash = self::CART_HASH, + ?string $cartHash = self::CART_HASH, + ): ResponseInterface { + return $this->callPaymentController('notify', $resultPayment, $secret, $cartHash); + } + + /** + * Sends the redirect, Girosolution redirects the customer to the redirect + * URL after the payment. + */ + protected function sendRedirect( + string $resultPayment, + string $secret, + ?string $cartHash = self::CART_HASH, + ): ResponseInterface { + return $this->callPaymentController('redirect', $resultPayment, $secret, $cartHash); + } + + /** + * @param string|null $cartHash null omits the hash argument + */ + private function callPaymentController( + string $action, + string $resultPayment, + string $secret, + ?string $cartHash, ): ResponseInterface { $notification = [ 'gcReference' => self::GC_REFERENCE, @@ -99,18 +128,28 @@ protected function sendNotification( // The controller reads the notification from $_GET, like the SDK of Girosolution expects it. $_GET = $notification; + $pluginArguments = [ + 'tx_cartgirosolution_cart[controller]' => 'Order\\Payment', + 'tx_cartgirosolution_cart[action]' => $action, + ]; + if ($cartHash !== null) { + $pluginArguments['tx_cartgirosolution_cart[hash]'] = $cartHash; + } + return $this->executeFrontendSubRequest( (new InternalRequest('http://localhost/')) ->withPageId(1) - ->withQueryParameters([ - 'type' => 2278106, - 'tx_cartgirosolution_cart[controller]' => 'Order\\Payment', - 'tx_cartgirosolution_cart[action]' => 'notify', - 'tx_cartgirosolution_cart[hash]' => $cartHash, - ] + $notification) + ->withQueryParameters(['type' => 2278106] + $pluginArguments + $notification) ); } + protected function setPaymentProvider(string $provider): void + { + $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_payment') + ->update('tx_cart_domain_model_order_payment', ['provider' => $provider], ['uid' => 1]); + } + protected function getPayment(): array { return $this->getRecord('tx_cart_domain_model_order_payment', ['status']); diff --git a/Tests/Functional/Controller/Order/PaymentControllerTest.php b/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php similarity index 62% rename from Tests/Functional/Controller/Order/PaymentControllerTest.php rename to Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php index 5b0ac11..fcc7ee9 100644 --- a/Tests/Functional/Controller/Order/PaymentControllerTest.php +++ b/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php @@ -18,13 +18,14 @@ use girosolution\GiroCheckout_SDK\helper\GiroCheckout_SDK_Exception_helper; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; +use TYPO3\CMS\Core\Database\ConnectionPool; /** * Checks the stored payment, the transaction and the dispatched events after * the notification of Girosolution. */ #[CoversClass(PaymentController::class)] -final class PaymentControllerTest extends AbstractPaymentControllerTestCase +final class PaymentControllerNotifyActionTest extends AbstractPaymentControllerTestCase { #[Test] public function successfulPaymentMarksPaymentAndTransactionAsPaid(): void @@ -120,6 +121,76 @@ public function notificationForUnknownCartIsRejected(): void self::assertSame([], EventRecorder::getEvents()); } + #[Test] + public function notificationWithoutCartHashIsRejected(): void + { + try { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET, null); + self::fail('The notification without cart hash has been accepted.'); + } catch (\InvalidArgumentException $exception) { + self::assertSame(1734098478, $exception->getCode()); + } + + self::assertSame('open', $this->getPayment()['status']); + } + + #[Test] + public function paypalPaymentIsVerifiedWithPaypalCredentials(): void + { + $this->setPaymentProvider('GIROSOLUTION_PAYPAL'); + + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, 'paypal-secret'); + + self::assertSame('paid', $this->getPayment()['status']); + self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); + } + + #[Test] + public function paypalPaymentIsNotVerifiedWithCreditCardCredentials(): void + { + $this->setPaymentProvider('GIROSOLUTION_PAYPAL'); + + $this->expectException(GiroCheckout_SDK_Exception_helper::class); + + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + } + + #[Test] + public function notificationForUnknownClearingTypeIsRejected(): void + { + $this->setPaymentProvider('GIROSOLUTION_UNKNOWN'); + + try { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + self::fail('The notification for an unknown clearing type has been accepted.'); + } catch (\InvalidArgumentException $exception) { + self::assertSame(1734099627, $exception->getCode()); + } + + self::assertSame('open', $this->getPayment()['status']); + } + + #[Test] + public function notificationForPaymentWithoutTransactionIsRejected(): void + { + $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_transaction') + ->delete('tx_cart_domain_model_order_transaction', ['uid' => 1]); + $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_payment') + ->update('tx_cart_domain_model_order_payment', ['transactions' => 0], ['uid' => 1]); + + try { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + self::fail('The notification for a payment without transaction has been accepted.'); + } catch (\Exception $exception) { + self::assertSame(1731616906, $exception->getCode()); + } + + self::assertSame('open', $this->getPayment()['status']); + self::assertSame([], EventRecorder::getEvents()); + } + #[Test] public function notifyActionRespondsWithEmptyBody(): void { diff --git a/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php b/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php new file mode 100644 index 0000000..104cd9a --- /dev/null +++ b/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php @@ -0,0 +1,185 @@ +sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame('paid', $this->getPayment()['status']); + self::assertSame( + [ + 'status' => 'paid', + 'external_status_code' => self::RESULT_PAYMENT_SUCCESSFUL, + 'note' => 'gc-backend-tx-0001', + ], + $this->getTransaction() + ); + } + + #[Test] + public function successfulPaymentDispatchesFinishEvent(): void + { + $this->sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); + self::assertArrayNotHasKey(CancelEvent::class, EventRecorder::getEvents()); + } + + #[Test] + public function successfulPaymentDoesNotRestoreTheCart(): void + { + $this->sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame([], $this->getSessionData()); + } + + /** + * Girosolution usually sends the notification before the customer is + * redirected. The event must not be dispatched a second time. + */ + #[Test] + public function redirectAfterNotificationDoesNotDispatchTheEventAgain(): void + { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + $this->sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame('paid', $this->getPayment()['status']); + self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); + } + + #[Test] + public function canceledPaymentMarksPaymentAndTransactionAsCanceled(): void + { + $this->sendRedirect(self::RESULT_PAYMENT_CANCELED, self::TYPOSCRIPT_SECRET); + + self::assertSame('canceled', $this->getPayment()['status']); + self::assertSame( + [ + 'status' => 'canceled', + 'external_status_code' => self::RESULT_PAYMENT_CANCELED, + 'note' => 'gc-backend-tx-0001', + ], + $this->getTransaction() + ); + } + + #[Test] + public function canceledPaymentDispatchesCancelEvent(): void + { + $this->sendRedirect(self::RESULT_PAYMENT_CANCELED, self::TYPOSCRIPT_SECRET); + + self::assertCount(1, EventRecorder::getEvents()[CancelEvent::class] ?? []); + self::assertArrayNotHasKey(FinishEvent::class, EventRecorder::getEvents()); + } + + #[Test] + public function canceledPaymentRestoresTheCartInTheSession(): void + { + $this->sendRedirect(self::RESULT_PAYMENT_CANCELED, self::TYPOSCRIPT_SECRET); + + $sessionData = $this->getSessionData(); + self::assertArrayHasKey('cart_1', $sessionData); + + $cart = unserialize($sessionData['cart_1']); + self::assertInstanceOf(Cart::class, $cart); + self::assertSame('de', $cart->getBillingCountry()); + self::assertSame('', $cart->getOrderNumber()); + } + + #[Test] + public function canceledPaymentAddsFlashMessageForTheCart(): void + { + $this->sendRedirect(self::RESULT_PAYMENT_CANCELED, self::TYPOSCRIPT_SECRET); + + $sessionData = $this->getSessionData(); + self::assertArrayHasKey('extbase.flashmessages.tx_cart_cart', $sessionData); + self::assertStringContainsString( + 'The payment process was aborted.', + json_encode($sessionData['extbase.flashmessages.tx_cart_cart'], JSON_THROW_ON_ERROR) + ); + } + + #[Test] + public function redirectWithWrongHashIsRejected(): void + { + try { + $this->sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, 'wrong-secret'); + self::fail('The redirect with a wrong hash has been accepted.'); + } catch (GiroCheckout_SDK_Exception_helper $exception) { + self::assertStringContainsString('hash mismatch', $exception->getMessage()); + } + + self::assertSame('open', $this->getPayment()['status']); + self::assertSame([], EventRecorder::getEvents()); + self::assertSame([], $this->getSessionData()); + } + + #[Test] + public function redirectWithoutCartHashIsRejected(): void + { + try { + $this->sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET, null); + self::fail('The redirect without cart hash has been accepted.'); + } catch (\InvalidArgumentException $exception) { + self::assertSame(1734098478, $exception->getCode()); + } + + self::assertSame('open', $this->getPayment()['status']); + } + + /** + * Returns the session data of the frontend user, the test sends one + * request, so there is at most one session. + */ + private function getSessionData(): array + { + $sessions = $this->get(ConnectionPool::class) + ->getConnectionForTable('fe_sessions') + ->select(['ses_data'], 'fe_sessions') + ->fetchAllAssociative(); + + self::assertLessThanOrEqual(1, count($sessions)); + + if ($sessions === []) { + return []; + } + + $sessionData = unserialize($sessions[0]['ses_data'], ['allowed_classes' => false]); + self::assertIsArray($sessionData); + + return $sessionData; + } +} diff --git a/Tests/Functional/Fixtures/DataSets/Base.php b/Tests/Functional/Fixtures/DataSets/Base.php index 36972b5..8526419 100644 --- a/Tests/Functional/Fixtures/DataSets/Base.php +++ b/Tests/Functional/Fixtures/DataSets/Base.php @@ -43,6 +43,11 @@ ' projectId = 5678', ' password = credit-card-secret', '}', + 'plugin.tx_cartgirosolution.credentials.paypal {', + ' merchantId = 1234', + ' projectId = 9012', + ' password = paypal-secret', + '}', ]), ], ], From 0f9850b36c6e8c2c3cab8b4c1b20ab4cd3abba84 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 15:22:41 +0100 Subject: [PATCH 06/12] [TASK] Register the event recorder of the tests via Services.php The test extension girosolution_test registers its listener in Services.php instead of Services.yaml. The classes are referenced by their class constants, so a renamed or moved class is found by the IDE and PHPStan. Co-Authored-By: Claude Opus 5.5 --- .../Configuration/Services.php | 28 +++++++++++++++++++ .../Configuration/Services.yaml | 14 ---------- 2 files changed, 28 insertions(+), 14 deletions(-) create mode 100644 Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.php delete mode 100644 Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.yaml diff --git a/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.php b/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.php new file mode 100644 index 0000000..acf5c45 --- /dev/null +++ b/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.php @@ -0,0 +1,28 @@ +services(); + + $services + ->defaults() + ->autowire() + ->autoconfigure() + ->private(); + + $services->set(EventRecorder::class) + ->tag('event.listener', [ + 'identifier' => 'girosolution-test--order--finish--event-recorder', + 'event' => FinishEvent::class, + ]) + ->tag('event.listener', [ + 'identifier' => 'girosolution-test--order--cancel--event-recorder', + 'event' => CancelEvent::class, + ]); +}; diff --git a/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.yaml b/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.yaml deleted file mode 100644 index 26ce00e..0000000 --- a/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.yaml +++ /dev/null @@ -1,14 +0,0 @@ -services: - _defaults: - autowire: true - autoconfigure: true - public: false - - Extcode\GirosolutionTest\EventListener\EventRecorder: - tags: - - name: event.listener - identifier: 'girosolution-test--order--finish--event-recorder' - event: Extcode\CartGirosolution\Event\Order\FinishEvent - - name: event.listener - identifier: 'girosolution-test--order--cancel--event-recorder' - event: Extcode\CartGirosolution\Event\Order\CancelEvent From 76462733218660318980e0bad6fd9dd064825ccb Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 15:49:19 +0100 Subject: [PATCH 07/12] [TASK] Declare strict types in all PHP files The PaymentController, ext_localconf.php and the TCA override were the only PHP files without strict types. The tests cover the controller, so type errors in calls from it are detected now. ext_emconf.php is left untouched, it only returns the configuration for the TYPO3 Extension Repository. Co-Authored-By: Claude Opus 5.5 --- Classes/Controller/Order/PaymentController.php | 2 ++ Configuration/TCA/Overrides/sys_template.php | 2 ++ ext_localconf.php | 2 ++ 3 files changed, 6 insertions(+) diff --git a/Classes/Controller/Order/PaymentController.php b/Classes/Controller/Order/PaymentController.php index bb8d52e..722fcd8 100644 --- a/Classes/Controller/Order/PaymentController.php +++ b/Classes/Controller/Order/PaymentController.php @@ -1,5 +1,7 @@ Date: Sat, 14 Nov 2026 15:52:49 +0100 Subject: [PATCH 08/12] [TASK] Remove ext_emconf.php The extension can only be installed with Composer, because the dependency girosolution/girocheckout-sdk cannot be installed by the extension manager. In Composer mode TYPO3 uses composer.json, so ext_emconf.php is not needed. Co-Authored-By: Claude Opus 5.5 --- Build/phpstan.neon | 1 - ext_emconf.php | 20 -------------------- rector.php | 1 - 3 files changed, 22 deletions(-) delete mode 100644 ext_emconf.php diff --git a/Build/phpstan.neon b/Build/phpstan.neon index 13c6770..30b0b9a 100644 --- a/Build/phpstan.neon +++ b/Build/phpstan.neon @@ -6,5 +6,4 @@ parameters: - ../Classes - ../Configuration - ../Tests - - ../ext_emconf.php - ../ext_localconf.php diff --git a/ext_emconf.php b/ext_emconf.php deleted file mode 100644 index 8be7d58..0000000 --- a/ext_emconf.php +++ /dev/null @@ -1,20 +0,0 @@ - 'Cart - Girosolution', - 'description' => 'Shopping Cart(s) for TYPO3 - Girosolution Payment Provider', - 'category' => 'services', - 'author' => 'Daniel Gohlke', - 'author_email' => 'ext@extco.de', - 'author_company' => 'extco.de UG (haftungsbeschränkt)', - 'state' => 'stable', - 'version' => '6.0.0', - 'constraints' => [ - 'depends' => [ - 'typo3' => '13.4.0-13.4.99', - 'cart' => '10.0.0', - ], - 'conflicts' => [], - 'suggests' => [], - ], -]; diff --git a/rector.php b/rector.php index 75f141d..6d7eddd 100644 --- a/rector.php +++ b/rector.php @@ -19,7 +19,6 @@ ->withPaths([ __DIR__ . '/Classes', __DIR__ . '/Configuration', - __DIR__ . '/ext_emconf.php', __DIR__ . '/ext_localconf.php', ]) // uncomment to reach your current PHP version From 47fc5158c44e7ff9b671a7e9c40379110572e1ec Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 15:53:18 +0100 Subject: [PATCH 09/12] [TASK] Check strict types declaration with php-cs-fixer The rule declare_strict_types reports PHP files without strict types, project:cgl:fix adds the declaration. Co-Authored-By: Claude Opus 5.5 --- Build/.php-cs-fixer.dist.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Build/.php-cs-fixer.dist.php b/Build/.php-cs-fixer.dist.php index 58818f6..e04f9fa 100644 --- a/Build/.php-cs-fixer.dist.php +++ b/Build/.php-cs-fixer.dist.php @@ -21,6 +21,7 @@ 'concat_space' => ['spacing' => 'one'], 'declare_equal_normalize' => ['space' => 'none'], 'declare_parentheses' => true, + 'declare_strict_types' => true, 'dir_constant' => true, 'function_to_constant' => ['functions' => ['get_called_class', 'get_class', 'get_class_this', 'php_sapi_name', 'phpversion', 'pi']], 'modernize_strpos' => true, From 7d295134e659c6fa18643d7664c14e089b144541 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 15:56:58 +0100 Subject: [PATCH 10/12] [TASK] Move service configuration to Services.php The services were configured partly in Services.yaml and partly in Services.php. All services are configured in Services.php now, the classes are referenced by their class constants, so a renamed or moved class is found by the IDE and PHPStan. A functional test checks the registered event listeners and that the cart is cleared before the customer is redirected to Girosolution. Co-Authored-By: Claude Opus 5.5 --- Configuration/Services.php | 41 ++++++++--- Configuration/Services.yaml | 30 -------- .../EventListenerRegistrationTest.php | 73 +++++++++++++++++++ 3 files changed, 105 insertions(+), 39 deletions(-) delete mode 100644 Configuration/Services.yaml create mode 100644 Tests/Functional/Configuration/EventListenerRegistrationTest.php diff --git a/Configuration/Services.php b/Configuration/Services.php index c3e4176..7743ce2 100644 --- a/Configuration/Services.php +++ b/Configuration/Services.php @@ -4,28 +4,51 @@ namespace Extcode\CartGirosolution\Configuration; +use Extcode\Cart\Event\Order\PaymentEvent; +use Extcode\Cart\EventListener\Order\Finish\Email; +use Extcode\CartGirosolution\Event\Order\FinishEvent; +use Extcode\CartGirosolution\EventListener\Order\Payment\ClearCart; +use Extcode\CartGirosolution\EventListener\Order\Payment\ProviderRedirect; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use function Symfony\Component\DependencyInjection\Loader\Configurator\tagged_iterator; -return static function (ContainerConfigurator $containerConfigurator, ContainerBuilder $container) { +return static function (ContainerConfigurator $containerConfigurator, ContainerBuilder $container): void { $services = $containerConfigurator->services(); - $services - ->instanceof(CredentialLoaderInterface::class) - ->tag('cartGirosolution.credentialLoader'); $services ->defaults() ->autowire() - ->autoconfigure(); + ->autoconfigure() + ->private(); + + $services + ->instanceof(CredentialLoaderInterface::class) + ->tag('cartGirosolution.credentialLoader'); $services - ->load( - 'Extcode\\CartGirosolution\\Configuration\\', - '../Classes/Configuration/' - ); + ->load('Extcode\\CartGirosolution\\', '../Classes/*'); $services->set(CredentialLoaderRegistry::class) ->arg('$credentialLoaders', tagged_iterator('cartGirosolution.credentialLoader')); + + $services->set(ClearCart::class) + ->tag('event.listener', [ + 'identifier' => 'cart-girosolution--order--payment--clear-cart', + 'event' => PaymentEvent::class, + 'before' => 'cart-girosolution--order--payment--provider-redirect', + ]); + + $services->set(ProviderRedirect::class) + ->tag('event.listener', [ + 'identifier' => 'cart-girosolution--order--payment--provider-redirect', + 'event' => PaymentEvent::class, + ]); + + $services->set('Extcode\\CartGirosolution\\EventListener\\Order\\Finish\\Email', Email::class) + ->tag('event.listener', [ + 'identifier' => 'cart-girosolution--order--finish--email', + 'event' => FinishEvent::class, + ]); }; diff --git a/Configuration/Services.yaml b/Configuration/Services.yaml deleted file mode 100644 index ff5a9ba..0000000 --- a/Configuration/Services.yaml +++ /dev/null @@ -1,30 +0,0 @@ -services: - _defaults: - autowire: true - autoconfigure: true - public: false - - Extcode\CartGirosolution\: - resource: '../Classes/*' - exclude: - - '../Classes/Configuration/*' - - Extcode\CartGirosolution\EventListener\Order\Payment\ClearCart: - tags: - - name: event.listener - identifier: 'cart-girosolution--order--payment--clear-cart' - event: Extcode\Cart\Event\Order\PaymentEvent - before: 'cart-girosolution--order--payment--provider-redirect' - - Extcode\CartGirosolution\EventListener\Order\Payment\ProviderRedirect: - tags: - - name: event.listener - identifier: 'cart-girosolution--order--payment--provider-redirect' - event: Extcode\Cart\Event\Order\PaymentEvent - - Extcode\CartGirosolution\EventListener\Order\Finish\Email: - class: 'Extcode\Cart\EventListener\Order\Finish\Email' - tags: - - name: event.listener - identifier: 'cart-girosolution--order--finish--email' - event: Extcode\CartGirosolution\Event\Order\FinishEvent diff --git a/Tests/Functional/Configuration/EventListenerRegistrationTest.php b/Tests/Functional/Configuration/EventListenerRegistrationTest.php new file mode 100644 index 0000000..3f3fae3 --- /dev/null +++ b/Tests/Functional/Configuration/EventListenerRegistrationTest.php @@ -0,0 +1,73 @@ +getListenerDefinitions(PaymentEvent::class), + array_flip([ + 'cart-girosolution--order--payment--clear-cart', + 'cart-girosolution--order--payment--provider-redirect', + ]) + ); + + self::assertSame( + [ + 'cart-girosolution--order--payment--clear-cart' => ClearCart::class, + 'cart-girosolution--order--payment--provider-redirect' => ProviderRedirect::class, + ], + array_map(static fn(array $listener): string => $listener['service'], $listeners) + ); + } + + #[Test] + public function sendsTheMailsOfCartAfterTheFinishedPayment(): void + { + $listeners = $this->getListenerDefinitions(FinishEvent::class); + + self::assertArrayHasKey('cart-girosolution--order--finish--email', $listeners); + self::assertSame( + 'Extcode\\CartGirosolution\\EventListener\\Order\\Finish\\Email', + $listeners['cart-girosolution--order--finish--email']['service'] + ); + } + + /** + * @return array + */ + private function getListenerDefinitions(string $event): array + { + return $this->get(ListenerProvider::class)->getAllListenerDefinitions()[$event] ?? []; + } +} From 6ac2c7e92cf7bb22acbb80d0e6438bb44e617b41 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 16:43:10 +0100 Subject: [PATCH 11/12] [TASK] Use a descriptive service id for the email listener The email listener of cart is registered a second time for the FinishEvent of this extension, because the FinishEvent of cart is not dispatched for payments with Girosolution. The service id looked like a class of this extension that does not exist. It is a descriptive id now, the class of the service is the listener of cart. The identifier of the event listener is unchanged. The change is documented as breaking change in the changelog of 6.0, the release which introduces it. Co-Authored-By: Claude Opus 5.5 --- Configuration/Services.php | 2 +- ...king-35-RenameServiceIdOfEmailListener.rst | 39 +++++++++++++++++++ Documentation/Changelog/6.0/Index.rst | 18 ++++++++- .../EventListenerRegistrationTest.php | 2 +- 4 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 Documentation/Changelog/6.0/Breaking-35-RenameServiceIdOfEmailListener.rst diff --git a/Configuration/Services.php b/Configuration/Services.php index 7743ce2..1e7d972 100644 --- a/Configuration/Services.php +++ b/Configuration/Services.php @@ -46,7 +46,7 @@ 'event' => PaymentEvent::class, ]); - $services->set('Extcode\\CartGirosolution\\EventListener\\Order\\Finish\\Email', Email::class) + $services->set('cart-girosolution--event-listener--order--finish--email', Email::class) ->tag('event.listener', [ 'identifier' => 'cart-girosolution--order--finish--email', 'event' => FinishEvent::class, diff --git a/Documentation/Changelog/6.0/Breaking-35-RenameServiceIdOfEmailListener.rst b/Documentation/Changelog/6.0/Breaking-35-RenameServiceIdOfEmailListener.rst new file mode 100644 index 0000000..cb3b5ab --- /dev/null +++ b/Documentation/Changelog/6.0/Breaking-35-RenameServiceIdOfEmailListener.rst @@ -0,0 +1,39 @@ +.. include:: ../../Includes.rst.txt + +======================================================= +Breaking: #35 - Rename Service Id of the Email Listener +======================================================= + +See `Pull Request 35 `__ + +Description +=========== + +After a payment with Girosolution the extension dispatches its own +``Extcode\CartGirosolution\Event\Order\FinishEvent``. The email listener of +EXT:cart is registered for this event, so the mails to the buyer and the +seller are sent. + +The service of this listener had the id +``Extcode\CartGirosolution\EventListener\Order\Finish\Email``, which looked +like a class of this extension, but no such class exists. The service id was +renamed to ``cart-girosolution--event-listener--order--finish--email``. + +The identifier of the event listener +``cart-girosolution--order--finish--email`` is unchanged. + +Affected Installations +====================== + +Installations which reference the service by its id, e.g. to replace or to +remove the listener in their own service configuration. + +Migration +========= + +Use the new service id +``cart-girosolution--event-listener--order--finish--email``. Listeners which +use the identifier of the event listener in ``before`` or ``after`` do not +need to be changed. + +.. index:: Frontend diff --git a/Documentation/Changelog/6.0/Index.rst b/Documentation/Changelog/6.0/Index.rst index 0f79465..383bc70 100644 --- a/Documentation/Changelog/6.0/Index.rst +++ b/Documentation/Changelog/6.0/Index.rst @@ -4,4 +4,20 @@ 6.0 Changes =========== -The version 6.x is a release for extcode/cart 10.x. \ No newline at end of file +The version 6.x is a release for extcode/cart 10.x. + +**Table of contents** + +.. contents:: + :local: + :depth: 1 + +Breaking +-------- + +.. toctree:: + :maxdepth: 1 + :titlesonly: + :glob: + + Breaking-* diff --git a/Tests/Functional/Configuration/EventListenerRegistrationTest.php b/Tests/Functional/Configuration/EventListenerRegistrationTest.php index 3f3fae3..f552715 100644 --- a/Tests/Functional/Configuration/EventListenerRegistrationTest.php +++ b/Tests/Functional/Configuration/EventListenerRegistrationTest.php @@ -58,7 +58,7 @@ public function sendsTheMailsOfCartAfterTheFinishedPayment(): void self::assertArrayHasKey('cart-girosolution--order--finish--email', $listeners); self::assertSame( - 'Extcode\\CartGirosolution\\EventListener\\Order\\Finish\\Email', + 'cart-girosolution--event-listener--order--finish--email', $listeners['cart-girosolution--order--finish--email']['service'] ); } From dd6d28f469db451214e82b763a9f360866270f25 Mon Sep 17 00:00:00 2001 From: Daniel Gohlke Date: Sat, 14 Nov 2026 16:48:15 +0100 Subject: [PATCH 12/12] [DOCS] Fix required cart version in changelog of 6.0 The version 6.x requires extcode/cart 11.x, not 10.x. Co-Authored-By: Claude Opus 5.5 --- Documentation/Changelog/6.0/Index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/Changelog/6.0/Index.rst b/Documentation/Changelog/6.0/Index.rst index 383bc70..9e483da 100644 --- a/Documentation/Changelog/6.0/Index.rst +++ b/Documentation/Changelog/6.0/Index.rst @@ -4,7 +4,7 @@ 6.0 Changes =========== -The version 6.x is a release for extcode/cart 10.x. +The version 6.x is a release for extcode/cart 11.x. **Table of contents**