File size: 1,895 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | <?php
declare(strict_types=1);
namespace Billing\Application\CommandHandlers;
use Billing\Application\Commands\CancelSubscriptionCommand;
use Billing\Domain\Entities\SubscriptionEntity;
use Billing\Domain\Exceptions\SubscriptionNotFoundException;
use Billing\Domain\Repositories\SubscriptionRepositoryInterface;
use Billing\Infrastructure\Payments\Exceptions\GatewayNotFoundException;
use Billing\Infrastructure\Payments\Exceptions\PaymentException;
use Billing\Infrastructure\Payments\PaymentGatewayFactoryInterface;
use Shared\Domain\ValueObjects\Id;
class CancelSubscriptionCommandHandler
{
public function __construct(
private SubscriptionRepositoryInterface $repo,
private PaymentGatewayFactoryInterface $factory,
) {
}
/**
* @throws SubscriptionNotFoundException
*/
public function handle(CancelSubscriptionCommand $cmd): SubscriptionEntity
{
$sub = $cmd->subscription instanceof Id
? $this->repo->ofId($cmd->subscription)
: $cmd->subscription;
$ws = $sub->getWorkspace();
// Stop payments
if ($sub->getPaymentGateway()->value) {
try {
$gateway = $this->factory->create(
$sub->getPaymentGateway()->value
);
$gateway->cancelSubscription($sub->getExternalId()->value);
} catch (PaymentException | GatewayNotFoundException $th) {
// Couldn't stop the payments, case must be handled manually
}
}
$sub->cancel();
$activeSub = $ws->getSubscription();
if (
!$activeSub
|| (string) $activeSub->getId()->getValue() !== (string) $sub->getId()->getValue()
) {
// This is not the active subscription, so we can end it here
$sub->end();
}
return $sub;
}
}
|