Skip to content

Commit

Permalink
Add proper logging
Browse files Browse the repository at this point in the history
  • Loading branch information
LucaGallinari committed Sep 12, 2024
1 parent 4ffa8cd commit ced6594
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 107 deletions.
1 change: 1 addition & 0 deletions config/services/controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
service('payum.security.token_storage'),
service('router'),
service('sylius.repository.payment'),
service('webgriffe_sylius_pausepay.logger'),
])
->call('setContainer', [service('service_container')])
->tag('controller.service_arguments')
Expand Down
44 changes: 26 additions & 18 deletions src/Controller/PaymentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Payum\Core\Model\Identity;
use Payum\Core\Security\TokenInterface;
use Payum\Core\Storage\StorageInterface;
use Psr\Log\LoggerInterface;
use Sylius\Bundle\PayumBundle\Model\GatewayConfigInterface;
use Sylius\Component\Core\Model\PaymentInterface;
use Sylius\Component\Core\Model\PaymentMethodInterface;
Expand All @@ -16,6 +17,7 @@
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Webgriffe\SyliusPausePayPlugin\Helper\PaymentDetailsHelper;
use Webgriffe\SyliusPausePayPlugin\Logger\LoggingHelperTrait;
use Webgriffe\SyliusPausePayPlugin\Payum\PausePayApi;
use Webmozart\Assert\Assert;

Expand All @@ -26,12 +28,14 @@
*/
final class PaymentController extends AbstractController
{
use LoggingHelperTrait;

public function __construct(
private StorageInterface $tokenStorage,
private RouterInterface $router,
private PaymentRepositoryInterface $paymentRepository,
private LoggerInterface $logger,
) {
// todo: logging
}

public function processAction(string $payumToken): Response
Expand All @@ -45,20 +49,25 @@ public function processAction(string $payumToken): Response
throw $this->createNotFoundException();
}

$paymentDetails = $this->retrieveDetailsFromToken($token);
$syliusPayment = $this->retrievePaymentFromToken($token);
$paymentDetails = $syliusPayment->getDetails();
if (!PaymentDetailsHelper::areValid($paymentDetails)) {
throw $this->createAccessDeniedException();
}

$redirectUrl = PaymentDetailsHelper::getRedirectUrl($paymentDetails);
$paymentStatusUrl = $this->router->generate(
'webgriffe_sylius_pausepay_plugin_payment_status',
['payumToken' => $payumToken],
UrlGeneratorInterface::ABSOLUTE_URL,
);

return $this->render('@WebgriffeSyliusPausePayPlugin/Process/index.html.twig', [
$params = [
'afterUrl' => $token->getAfterUrl(),
'paymentStatusUrl' => $paymentStatusUrl,
'redirectUrl' => $redirectUrl,
]);
'redirectUrl' => PaymentDetailsHelper::getRedirectUrl($paymentDetails),
];
$this->logInfo($syliusPayment, 'Showing process page to user.', $params);

return $this->render('@WebgriffeSyliusPausePayPlugin/Process/index.html.twig', $params);
}

public function statusAction(string $payumToken): Response
Expand All @@ -72,16 +81,20 @@ public function statusAction(string $payumToken): Response
throw $this->createNotFoundException();
}

$paymentDetails = $this->retrieveDetailsFromToken($token);
$syliusPayment = $this->retrievePaymentFromToken($token);
$paymentDetails = $syliusPayment->getDetails();
if (!PaymentDetailsHelper::areValid($paymentDetails)) {
throw $this->createAccessDeniedException();
}

$paymentStatus = PaymentDetailsHelper::getPaymentStatus($paymentDetails);

$this->logInfo($syliusPayment, sprintf('Retrieved status "%s"', $paymentStatus ?? 'null'));

return $this->json(['captured' => $paymentStatus !== null]);
}

/**
* @return PaymentDetails
*/
private function retrieveDetailsFromToken(TokenInterface $token): array
private function retrievePaymentFromToken(TokenInterface $token): PaymentInterface
{
$paymentIdentity = $token->getDetails();
Assert::isInstanceOf($paymentIdentity, Identity::class);
Expand All @@ -94,12 +107,7 @@ private function retrieveDetailsFromToken(TokenInterface $token): array

$this->assertPausePayPayment($syliusPayment);

$paymentDetails = $syliusPayment->getDetails();
if (!PaymentDetailsHelper::areValid($paymentDetails)) {
throw $this->createAccessDeniedException();
}

return $paymentDetails;
return $syliusPayment;
}

private function assertPausePayPayment(PaymentInterface $syliusPayment): void
Expand Down
2 changes: 1 addition & 1 deletion src/Helper/PaymentDetailsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ final class PaymentDetailsHelper
/**
* @return PaymentDetails
*/
public static function createFromContractCreateResult(CreateOrderResult $result): array
public static function createFromCreateOrderResult(CreateOrderResult $result): array
{
return [
self::UUID_KEY => $result->getUuid(),
Expand Down
20 changes: 20 additions & 0 deletions src/Logger/LoggingHelperTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace Webgriffe\SyliusPausePayPlugin\Logger;

use Sylius\Component\Core\Model\PaymentInterface as SyliusPaymentInterface;

trait LoggingHelperTrait
{
private function logInfo(SyliusPaymentInterface $payment, string $message, array $context = []): void
{
$this->logger->info(sprintf('[Payment #%s]: %s.', (string) $payment->getId(), $message, ), $context);
}

private function logError(SyliusPaymentInterface $payment, string $message, array $context = []): void
{
$this->logger->error(sprintf('[Payment #%s]: %s.', (string) $payment->getId(), $message, ), $context);
}
}
22 changes: 6 additions & 16 deletions src/Payum/Action/CancelAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@
use Symfony\Component\Routing\RouterInterface;
use Webgriffe\SyliusPausePayPlugin\Client\PaymentState;
use Webgriffe\SyliusPausePayPlugin\Helper\PaymentDetailsHelper;
use Webgriffe\SyliusPausePayPlugin\Logger\LoggingHelperTrait;
use Webmozart\Assert\Assert;

/**
* @psalm-type PaymentDetails array{uuid: string, redirect_url: string, created_at: string, status?: string}
*/
final class CancelAction implements ActionInterface
{
use LoggingHelperTrait;

public function __construct(
private LoggerInterface $logger,
private RouterInterface $router,
Expand All @@ -34,10 +37,8 @@ public function execute($request): void
{
RequestNotSupportedException::assertSupports($this, $request);
Assert::isInstanceOf($request, Cancel::class);

$payment = $request->getModel();
Assert::isInstanceOf($payment, SyliusPaymentInterface::class);

$order = $payment->getOrder();
Assert::isInstanceOf($order, OrderInterface::class);

Expand All @@ -47,17 +48,11 @@ public function execute($request): void
$paymentDetails = $payment->getDetails();
PaymentDetailsHelper::assertPaymentDetailsAreValid($paymentDetails);

$this->logInfo($payment, 'Redirecting the user to the Sylius PausePay waiting page.');

$order = $payment->getOrder();
Assert::isInstanceOf($order, OrderInterface::class);

$paymentDetails = PaymentDetailsHelper::addPaymentStatus(
$paymentDetails,
PaymentState::CANCELLED,
);
$paymentDetails = PaymentDetailsHelper::addPaymentStatus($paymentDetails, PaymentState::CANCELLED);
$payment->setDetails($paymentDetails);

$this->logInfo($payment, 'Redirecting the user to the Sylius PausePay waiting page.');

throw new HttpRedirect(
$this->router->generate('webgriffe_sylius_pausepay_plugin_payment_process', [
'payumToken' => $order->getTokenValue(),
Expand All @@ -70,9 +65,4 @@ public function supports($request): bool
{
return $request instanceof Cancel && $request->getModel() instanceof SyliusPaymentInterface;
}

private function logInfo(SyliusPaymentInterface $payment, string $message, array $context = []): void
{
$this->logger->info(sprintf('[Payment #%s]: %s.', (string) $payment->getId(), $message, ), $context);
}
}
74 changes: 37 additions & 37 deletions src/Payum/Action/CaptureAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Webgriffe\SyliusPausePayPlugin\Client\ValueObject\Response\CreateOrderResult;
use Webgriffe\SyliusPausePayPlugin\Factory\PaymentOrderFactoryInterface;
use Webgriffe\SyliusPausePayPlugin\Helper\PaymentDetailsHelper;
use Webgriffe\SyliusPausePayPlugin\Logger\LoggingHelperTrait;
use Webgriffe\SyliusPausePayPlugin\Mapper\OrderMapperInterface;
use Webgriffe\SyliusPausePayPlugin\Payum\PausePayApi;
use Webgriffe\SyliusPausePayPlugin\Repository\PaymentOrderRepositoryInterface;
Expand All @@ -35,7 +36,7 @@
*/
final class CaptureAction implements ActionInterface, GatewayAwareInterface, GenericTokenFactoryAwareInterface, ApiAwareInterface
{
use GatewayAwareTrait, GenericTokenFactoryAwareTrait, ApiAwareTrait;
use GatewayAwareTrait, GenericTokenFactoryAwareTrait, ApiAwareTrait, LoggingHelperTrait;

public function __construct(
private RouterInterface $router,
Expand All @@ -55,42 +56,16 @@ public function execute($request): void
{
RequestNotSupportedException::assertSupports($this, $request);
Assert::isInstanceOf($request, Capture::class);

/** @var SyliusPaymentInterface $payment */
$payment = $request->getModel();

$this->logInfo($payment, 'Start capture action', );

Assert::isInstanceOf($payment, SyliusPaymentInterface::class);
$captureToken = $request->getToken();
Assert::isInstanceOf($captureToken, TokenInterface::class);

$this->logInfo($payment, 'Start capture action');

$paymentDetails = $payment->getDetails();
if ($paymentDetails !== []) {
if (!PaymentDetailsHelper::areValid($paymentDetails)) {
$this->logger->error('Payment details are already populated with others data. Maybe this payment should be marked as error');
$payment->setDetails(PaymentDetailsHelper::addPaymentStatus(
$paymentDetails,
PaymentState::CANCELLED,
));

return;
}

$this->logInfo(
$payment,
'PausePay payment details are already valued, so no need to continue here.' .
' Redirecting the user to the Sylius PausePay Payments waiting page.',
);

$order = $payment->getOrder();
Assert::isInstanceOf($order, OrderInterface::class);

throw new HttpRedirect(
$this->router->generate('webgriffe_sylius_pausepay_plugin_payment_process', [
'payumToken' => $captureToken->getHash(),
'_locale' => $order->getLocaleCode(),
]),
);
$this->redirectToPaymentProcessPage($payment, $captureToken, $paymentDetails);
}

$cancelToken = $this->createCancelToken($captureToken);
Expand All @@ -111,7 +86,7 @@ public function execute($request): void
);

$this->createNotifyTokenAndPersistAssociationWithPausePayPayment($payment, $captureToken, $createOrderResult);
$payment->setDetails(PaymentDetailsHelper::createFromContractCreateResult($createOrderResult));
$payment->setDetails(PaymentDetailsHelper::createFromCreateOrderResult($createOrderResult));

$redirectUrl = $createOrderResult->getRedirectUrl();
$this->logInfo($payment, sprintf('Redirecting the user to the PausePay redirect URL "%s".', $redirectUrl));
Expand All @@ -126,11 +101,6 @@ public function supports($request): bool
$request->getModel() instanceof SyliusPaymentInterface;
}

private function logInfo(SyliusPaymentInterface $payment, string $message, array $context = []): void
{
$this->logger->info(sprintf('[Payment #%s]: %s.', (string) $payment->getId(), $message, ), $context);
}

private function createNotifyTokenAndPersistAssociationWithPausePayPayment(
SyliusPaymentInterface $payment,
TokenInterface $captureToken,
Expand All @@ -155,4 +125,34 @@ private function createCancelToken(TokenInterface $captureToken): TokenInterface
$captureToken->getAfterUrl(),
);
}

private function redirectToPaymentProcessPage(
SyliusPaymentInterface $payment,
TokenInterface $captureToken,
array $paymentDetails,
): void {
if (!PaymentDetailsHelper::areValid($paymentDetails)) {
// todo: is it ok to cancel the payment here?
$this->logError($payment, 'Payment details are already populated with others data. Cancel the payment.');
$payment->setDetails(PaymentDetailsHelper::addPaymentStatus($paymentDetails, PaymentState::CANCELLED));

return;
}

$this->logInfo(
$payment,
'PausePay payment details are already valued, so no need to continue here.' .
' Redirecting the user to the Sylius PausePay Payments waiting page.',
);

$order = $payment->getOrder();
Assert::isInstanceOf($order, OrderInterface::class);

throw new HttpRedirect(
$this->router->generate('webgriffe_sylius_pausepay_plugin_payment_process', [
'payumToken' => $captureToken->getHash(),
'_locale' => $order->getLocaleCode(),
]),
);
}
}
Loading

0 comments on commit ced6594

Please sign in to comment.