|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace SpeedPuzzling\Web\MessageHandler; |
| 6 | + |
| 7 | +use DateTimeImmutable; |
| 8 | +use Psr\Clock\ClockInterface; |
| 9 | +use Ramsey\Uuid\Uuid; |
| 10 | +use SpeedPuzzling\Web\Entity\Membership; |
| 11 | +use SpeedPuzzling\Web\Exceptions\MembershipNotFound; |
| 12 | +use SpeedPuzzling\Web\Exceptions\PlayerNotFound; |
| 13 | +use SpeedPuzzling\Web\Message\CreateMembershipSubscription; |
| 14 | +use SpeedPuzzling\Web\Message\UpdateMembershipSubscription; |
| 15 | +use SpeedPuzzling\Web\Repository\MembershipRepository; |
| 16 | +use SpeedPuzzling\Web\Repository\PlayerRepository; |
| 17 | +use Stripe\StripeClient; |
| 18 | +use Symfony\Component\Messenger\Attribute\AsMessageHandler; |
| 19 | +use Symfony\Component\Messenger\MessageBusInterface; |
| 20 | + |
| 21 | +#[AsMessageHandler] |
| 22 | +readonly final class CreateMembershipSubscriptionHandler |
| 23 | +{ |
| 24 | + public function __construct( |
| 25 | + private StripeClient $stripeClient, |
| 26 | + private PlayerRepository $playerRepository, |
| 27 | + private MembershipRepository $membershipRepository, |
| 28 | + private ClockInterface $clock, |
| 29 | + private MessageBusInterface $messageBus, |
| 30 | + ) { |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @throws PlayerNotFound |
| 35 | + */ |
| 36 | + public function __invoke(CreateMembershipSubscription $message): void |
| 37 | + { |
| 38 | + $subscriptionId = $message->stripeSubscriptionId; |
| 39 | + $subscription = $this->stripeClient->subscriptions->retrieve($subscriptionId); |
| 40 | + $billingPeriodEnd = DateTimeImmutable::createFromFormat('U', (string) $subscription->current_period_end); |
| 41 | + assert($billingPeriodEnd instanceof DateTimeImmutable); |
| 42 | + |
| 43 | + $customerId = $subscription->customer; |
| 44 | + assert(is_string($customerId)); |
| 45 | + |
| 46 | + $customer = $this->stripeClient->customers->retrieve($customerId); |
| 47 | + $playerId = $customer->metadata->player_id ?? null; |
| 48 | + |
| 49 | + if (!is_string($playerId)) { |
| 50 | + // Can not continue without playerId |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + try { |
| 55 | + $this->membershipRepository->getByPlayerId($playerId); |
| 56 | + $this->messageBus->dispatch( |
| 57 | + new UpdateMembershipSubscription($subscriptionId), |
| 58 | + ); |
| 59 | + } catch (MembershipNotFound) { |
| 60 | + $player = $this->playerRepository->get($playerId); |
| 61 | + $membership = new Membership( |
| 62 | + Uuid::uuid7(), |
| 63 | + $player, |
| 64 | + $this->clock->now(), |
| 65 | + $subscriptionId, |
| 66 | + $billingPeriodEnd, |
| 67 | + ); |
| 68 | + |
| 69 | + $this->membershipRepository->save($membership); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments