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/.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, 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/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..30b0b9a 100644 --- a/Build/phpstan.neon +++ b/Build/phpstan.neon @@ -5,5 +5,5 @@ parameters: paths: - ../Classes - ../Configuration - - ../ext_emconf.php + - ../Tests - ../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/Classes/Controller/Order/PaymentController.php b/Classes/Controller/Order/PaymentController.php index b484f5e..722fcd8 100644 --- a/Classes/Controller/Order/PaymentController.php +++ b/Classes/Controller/Order/PaymentController.php @@ -1,5 +1,7 @@ sendOkStatus(); - return $this->htmlResponse(); + return $this->htmlResponse(''); } private function updatePaymentAndTransaction($notify, Item $orderItem, string $status): bool 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; diff --git a/Configuration/Services.php b/Configuration/Services.php index c3e4176..1e7d972 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('cart-girosolution--event-listener--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/Configuration/TCA/Overrides/sys_template.php b/Configuration/TCA/Overrides/sys_template.php index 8564cef..9b8c57c 100644 --- a/Configuration/TCA/Overrides/sys_template.php +++ b/Configuration/TCA/Overrides/sys_template.php @@ -1,5 +1,7 @@ `__ + +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..9e483da 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 11.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 new file mode 100644 index 0000000..f552715 --- /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( + 'cart-girosolution--event-listener--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] ?? []; + } +} diff --git a/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php new file mode 100644 index 0000000..ffaa220 --- /dev/null +++ b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php @@ -0,0 +1,174 @@ + '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'); + $cart->setOrderNumber('ORD-2026-0001'); + + $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(); + } + + /** + * 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, + ): 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, + '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; + + $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] + $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']); + } + + 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/PaymentControllerNotifyActionTest.php b/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php new file mode 100644 index 0000000..fcc7ee9 --- /dev/null +++ b/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php @@ -0,0 +1,202 @@ +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 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 + { + $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/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/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..8526419 --- /dev/null +++ b/Tests/Functional/Fixtures/DataSets/Base.php @@ -0,0 +1,54 @@ + [ + [ + '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', + '}', + 'plugin.tx_cartgirosolution.credentials.paypal {', + ' merchantId = 1234', + ' projectId = 9012', + ' password = paypal-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.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/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..c6ee547 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,13 @@ "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" + "phpunit/phpcov": "^10.0 || ^11.0 || ^12.0", + "ssch/typo3-rector": "^3.13", + "typo3/testing-framework": "^9.5" }, "scripts": { "project:cgl": "Build/Scripts/cgl.sh", @@ -70,6 +79,9 @@ "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", + "project:test:coverage": "Build/Scripts/coverage.sh" } } 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/ext_localconf.php b/ext_localconf.php index dded661..ec3a397 100644 --- a/ext_localconf.php +++ b/ext_localconf.php @@ -1,5 +1,7 @@ withPaths([ __DIR__ . '/Classes', __DIR__ . '/Configuration', - __DIR__ . '/ext_emconf.php', __DIR__ . '/ext_localconf.php', ]) // uncomment to reach your current PHP version diff --git a/shell.nix b/shell.nix index 0c0ad43..7722982 100644 --- a/shell.nix +++ b/shell.nix @@ -130,6 +130,36 @@ 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 + ''; + }; + + 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 = [ @@ -147,6 +177,9 @@ in pkgs.mkShellNoCC { projectLintXml projectLintYaml projectPhpstan + projectTestUnit + projectTestFunctional + projectTestCoverage ]; shellHook = ''