<?php
namespace Harmonizely\Service\Simplypay\Subscribers;
use Harmonizely\Service\Simplypay\Contract\MerchantApiClientFactoryInterface;
use Harmonizely\Service\Simplypay\Contract\MerchantApiClientInterface;
use Harmonizely\Service\Simplypay\Contract\SubscriptionHelperServiceInterface;
use Harmonizely\User\UserDeletedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserDeletedSubscriber implements EventSubscriberInterface
{
/**
* Subscription helper
*
* @var SubscriptionHelperServiceInterface
*/
private SubscriptionHelperServiceInterface $subscriptionHelperService;
/**
* Client factory
*
* @var MerchantApiClientFactoryInterface
*/
private MerchantApiClientFactoryInterface $clientFactory;
/**
* Constructor
*
* @param SubscriptionHelperServiceInterface $subscriptionHelperService
* @param MerchantApiClientFactoryInterface $clientFactory
*/
public function __construct(
SubscriptionHelperServiceInterface $subscriptionHelperService,
MerchantApiClientFactoryInterface $clientFactory
)
{
$this->subscriptionHelperService = $subscriptionHelperService;
$this->clientFactory = $clientFactory;
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * ['eventName' => 'methodName']
* * ['eventName' => ['methodName', $priority]]
* * ['eventName' => [['methodName1', $priority], ['methodName2']]]
*
* The code must not depend on runtime state as it will only be called at compile time.
* All logic depending on runtime state must be put into the individual methods handling the events.
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents(): array
{
return [
UserDeletedEvent::NAME => 'onUserDeleted',
];
}
public function onUserDeleted(UserDeletedEvent $event): void
{
$userId = $this->subscriptionHelperService->encodeUserId(strval($event->getUserId()));
$client = $this->buildClient();
$client->cancelCustomerRecurringProfiles(
$userId, 'User deleted account. ' . $event->getReason()
);
}
/**
* Build client
*
* @return MerchantApiClientInterface
*/
private function buildClient(): MerchantApiClientInterface
{
// @todo it is better to move this to separate service
return $this->clientFactory->build(
$this->subscriptionHelperService->getToken(),
$this->subscriptionHelperService->getSecret(),
$this->subscriptionHelperService->getMerchant()
);
}
}