Passed
Push — main ( ab3841...929ade )
by Iain
20:54 queued 15:54
created

SubscriptionManager::startSubscription()   C

Complexity

Conditions 10
Paths 145

Size

Total Lines 71
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 10
Bugs 0 Features 0
Metric Value
cc 10
eloc 51
c 10
b 0
f 0
nc 145
nop 7
dl 0
loc 71
rs 6.9024

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Copyright Humbly Arrogant Software Limited 2020-2023.
7
 *
8
 * Use of this software is governed by the Business Source License included in the LICENSE file and at https://getparthenon.com/docs/next/license.
9
 *
10
 * Change Date: 26.06.2026 ( 3 years after 2.2.0 release )
11
 *
12
 * On the date above, in accordance with the Business Source License, use of this software will be governed by the open source license specified in the LICENSE file.
13
 */
14
15
namespace Parthenon\Billing\Subscription;
16
17
use Obol\Model\CancelSubscription;
18
use Obol\Model\Enum\ProrataType;
19
use Obol\Provider\ProviderInterface;
20
use Parthenon\Billing\Dto\StartSubscriptionDto;
21
use Parthenon\Billing\Entity\CustomerInterface;
22
use Parthenon\Billing\Entity\PaymentCard;
23
use Parthenon\Billing\Entity\Price;
24
use Parthenon\Billing\Entity\Subscription;
25
use Parthenon\Billing\Entity\SubscriptionPlan;
26
use Parthenon\Billing\Enum\BillingChangeTiming;
27
use Parthenon\Billing\Enum\SubscriptionStatus;
28
use Parthenon\Billing\Event\PaymentCreated;
29
use Parthenon\Billing\Event\SubscriptionCancelled;
30
use Parthenon\Billing\Event\SubscriptionCreated;
31
use Parthenon\Billing\Exception\SubscriptionCreationException;
32
use Parthenon\Billing\Factory\EntityFactoryInterface;
33
use Parthenon\Billing\Obol\BillingDetailsFactoryInterface;
34
use Parthenon\Billing\Obol\PaymentFactoryInterface;
35
use Parthenon\Billing\Obol\SubscriptionFactoryInterface;
36
use Parthenon\Billing\Plan\Plan;
37
use Parthenon\Billing\Plan\PlanManagerInterface;
38
use Parthenon\Billing\Plan\PlanPrice;
39
use Parthenon\Billing\Repository\PaymentCardRepositoryInterface;
40
use Parthenon\Billing\Repository\PaymentRepositoryInterface;
41
use Parthenon\Billing\Repository\PriceRepositoryInterface;
42
use Parthenon\Billing\Repository\SubscriptionPlanRepositoryInterface;
43
use Parthenon\Billing\Repository\SubscriptionRepositoryInterface;
44
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
45
46
final class SubscriptionManager implements SubscriptionManagerInterface
47
{
48
    public function __construct(
49
        private PaymentCardRepositoryInterface $paymentDetailsRepository,
50
        private ProviderInterface $provider,
51
        private BillingDetailsFactoryInterface $billingDetailsFactory,
52
        private PaymentFactoryInterface $paymentFactory,
53
        private SubscriptionFactoryInterface $subscriptionFactory,
54
        private PaymentRepositoryInterface $paymentRepository,
55
        private PlanManagerInterface $planManager,
56
        private SubscriptionPlanRepositoryInterface $subscriptionPlanRepository,
57
        private PriceRepositoryInterface $priceRepository,
58
        private SubscriptionRepositoryInterface $subscriptionRepository,
59
        private EntityFactoryInterface $entityFactory,
60
        private EventDispatcherInterface $dispatcher,
61
    ) {
62
    }
63
64
    public function startSubscription(CustomerInterface $customer, SubscriptionPlan|Plan $plan, Price|PlanPrice $planPrice, ?PaymentCard $paymentDetails = null, int $seatNumbers = 1, ?bool $hasTrial = null, ?int $trialLengthDays = 0): Subscription
65
    {
66
        $billingDetails = $this->billingDetailsFactory->createFromCustomerAndPaymentDetails($customer, $paymentDetails);
0 ignored issues
show
Bug introduced by
It seems like $paymentDetails can also be of type null; however, parameter $paymentDetails of Parthenon\Billing\Obol\B...omerAndPaymentDetails() does only seem to accept Parthenon\Billing\Entity\PaymentCard, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

66
        $billingDetails = $this->billingDetailsFactory->createFromCustomerAndPaymentDetails($customer, /** @scrutinizer ignore-type */ $paymentDetails);
Loading history...
67
        $obolSubscription = $this->subscriptionFactory->createSubscription($billingDetails, $planPrice, $seatNumbers, $hasTrial ?? $plan->getHasTrial(), $trialLengthDays ?? $plan->getTrialLengthDays());
68
        $obolSubscription->setStoredPaymentReference($paymentDetails->getStoredPaymentReference());
0 ignored issues
show
Bug introduced by
The method getStoredPaymentReference() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

68
        $obolSubscription->setStoredPaymentReference($paymentDetails->/** @scrutinizer ignore-call */ getStoredPaymentReference());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
69
70
        if ($this->subscriptionRepository->hasActiveSubscription($customer)) {
71
            $subscription = $this->subscriptionRepository->getOneActiveSubscriptionForCustomer($customer);
72
73
            if ($subscription->getCurrency() != $planPrice->getCurrency()) {
74
                throw new SubscriptionCreationException("Can't add a child subscription for a different currency");
75
            }
76
77
            $obolSubscription->setParentReference($subscription->getMainExternalReference());
78
        }
79
80
        $subscriptionCreationResponse = $this->provider->payments()->startSubscription($obolSubscription);
81
        if ($subscriptionCreationResponse->hasCustomerCreation()) {
82
            $customer->setPaymentProviderDetailsUrl($subscriptionCreationResponse->getCustomerCreation()->getDetailsUrl());
83
            $customer->setExternalCustomerReference($subscriptionCreationResponse->getCustomerCreation()->getReference());
84
        }
85
86
        $subscription = $this->entityFactory->getSubscriptionEntity();
87
        $subscription->setPlanName($plan->getName());
88
        if ($planPrice->isRecurring()) {
0 ignored issues
show
Bug introduced by
The method isRecurring() does not exist on Parthenon\Billing\Plan\PlanPrice. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

88
        if ($planPrice->/** @scrutinizer ignore-call */ isRecurring()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
89
            $subscription->setPaymentSchedule($planPrice->getSchedule());
90
        }
91
        $subscription->setActive(true);
92
        $subscription->setMoneyAmount($subscriptionCreationResponse->getPaymentDetails()?->getAmount());
93
        $subscription->setStatus(SubscriptionStatus::ACTIVE);
94
        $subscription->setMainExternalReference($subscriptionCreationResponse->getSubscriptionId());
95
        $subscription->setChildExternalReference($subscriptionCreationResponse->getLineId());
96
        $subscription->setSeats($seatNumbers);
97
        $subscription->setCreatedAt(new \DateTime());
98
        $subscription->setUpdatedAt(new \DateTime());
99
        $subscription->setStartOfCurrentPeriod(new \DateTime());
100
        $subscription->setValidUntil($subscriptionCreationResponse->getBilledUntil());
101
        $subscription->setCustomer($customer);
102
        $subscription->setMainExternalReferenceDetailsUrl($subscriptionCreationResponse->getDetailsUrl());
103
        $subscription->setPaymentDetails($paymentDetails);
104
        $subscription->setTrialLengthDays($obolSubscription->getTrialLengthDays());
105
        $subscription->setHasTrial($obolSubscription->hasTrial());
106
107
        if ($plan instanceof SubscriptionPlan) {
108
            $subscription->setSubscriptionPlan($plan);
109
        } elseif ($plan->hasEntityId()) {
110
            $subscriptionPlan = $this->subscriptionPlanRepository->findById($plan->getEntityId());
111
            $subscription->setSubscriptionPlan($subscriptionPlan);
112
        }
113
114
        if ($planPrice instanceof Price) {
115
            $subscription->setPrice($planPrice);
116
        } elseif ($planPrice->hasEntityId()) {
117
            $price = $this->priceRepository->findById($planPrice->getEntityId());
118
            $subscription->setPrice($price);
119
        }
120
        $this->subscriptionRepository->save($subscription);
121
        $this->subscriptionRepository->updateValidUntilForAllActiveSubscriptions($customer, $subscription->getMainExternalReference(), $subscriptionCreationResponse->getBilledUntil());
122
123
        $this->dispatcher->dispatch(new SubscriptionCreated($subscription), SubscriptionCreated::NAME);
124
125
        $obolPaymentDetails = $subscriptionCreationResponse->getPaymentDetails();
126
        if ($obolPaymentDetails) {
127
            $payment = $this->paymentFactory->fromSubscriptionCreation($obolPaymentDetails, $customer);
128
            $payment->addSubscription($subscription);
129
            $this->paymentRepository->save($payment);
130
131
            $this->dispatcher->dispatch(new PaymentCreated($payment, true), PaymentCreated::NAME);
132
        }
133
134
        return $subscription;
135
    }
136
137
    public function startSubscriptionWithDto(CustomerInterface $customer, StartSubscriptionDto $startSubscriptionDto): Subscription
138
    {
139
        if (!$startSubscriptionDto->getPaymentDetailsId()) {
140
            $paymentDetails = $this->paymentDetailsRepository->getDefaultPaymentCardForCustomer($customer);
141
        } else {
142
            $paymentDetails = $this->paymentDetailsRepository->findById($startSubscriptionDto->getPaymentDetailsId());
143
        }
144
145
        $plan = $this->planManager->getPlanByName($startSubscriptionDto->getPlanName());
146
        $planPrice = $plan->getPriceForPaymentSchedule($startSubscriptionDto->getSchedule(), $startSubscriptionDto->getCurrency());
147
148
        return $this->startSubscription($customer, $plan, $planPrice, $paymentDetails, $startSubscriptionDto->getSeatNumbers());
149
    }
150
151
    public function cancelSubscriptionAtEndOfCurrentPeriod(Subscription $subscription): Subscription
152
    {
153
        $obolSubscription = $this->subscriptionFactory->createSubscriptionFromEntity($subscription, false);
0 ignored issues
show
Unused Code introduced by
The call to Parthenon\Billing\Obol\S...ubscriptionFromEntity() has too many arguments starting with false. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
        /** @scrutinizer ignore-call */ 
154
        $obolSubscription = $this->subscriptionFactory->createSubscriptionFromEntity($subscription, false);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
154
155
        $cancelRequest = new CancelSubscription();
156
        $cancelRequest->setSubscription($obolSubscription);
157
        $cancelRequest->setInstantCancel(false);
158
159
        $cancellation = $this->provider->payments()->stopSubscription($cancelRequest);
0 ignored issues
show
Unused Code introduced by
The assignment to $cancellation is dead and can be removed.
Loading history...
160
161
        $subscription->setStatus(SubscriptionStatus::PENDING_CANCEL);
162
        $subscription->endAtEndOfPeriod();
163
164
        $this->subscriptionRepository->save($subscription);
165
        $this->dispatcher->dispatch(new SubscriptionCancelled($subscription), SubscriptionCancelled::NAME);
166
167
        return $subscription;
168
    }
169
170
    public function cancelSubscriptionInstantly(Subscription $subscription): Subscription
171
    {
172
        $obolSubscription = $this->subscriptionFactory->createSubscriptionFromEntity($subscription);
173
174
        $cancelRequest = new CancelSubscription();
175
        $cancelRequest->setSubscription($obolSubscription);
176
        $cancelRequest->setInstantCancel(true);
177
178
        $cancellation = $this->provider->payments()->stopSubscription($cancelRequest);
0 ignored issues
show
Unused Code introduced by
The assignment to $cancellation is dead and can be removed.
Loading history...
179
180
        $subscription->setStatus(SubscriptionStatus::CANCELLED);
181
        $subscription->setActive(false);
182
        $subscription->endNow();
183
184
        $this->subscriptionRepository->save($subscription);
185
        $this->dispatcher->dispatch(new SubscriptionCancelled($subscription), SubscriptionCancelled::NAME);
186
187
        return $subscription;
188
    }
189
190
    public function cancelSubscriptionOnDate(Subscription $subscription, \DateTimeInterface $dateTime): Subscription
191
    {
192
        $obolSubscription = $this->subscriptionFactory->createSubscriptionFromEntity($subscription);
193
194
        $cancelRequest = new CancelSubscription();
195
        $cancelRequest->setSubscription($obolSubscription);
196
        $cancelRequest->setInstantCancel(false);
197
198
        $cancellation = $this->provider->payments()->stopSubscription($cancelRequest);
0 ignored issues
show
Unused Code introduced by
The assignment to $cancellation is dead and can be removed.
Loading history...
199
200
        $subscription->setStatus(SubscriptionStatus::PENDING_CANCEL);
201
        $subscription->setEndedAt($dateTime);
202
        $subscription->setValidUntil($dateTime);
203
204
        $this->subscriptionRepository->save($subscription);
205
        $this->dispatcher->dispatch(new SubscriptionCancelled($subscription), SubscriptionCancelled::NAME);
206
207
        return $subscription;
208
    }
209
210
    public function changeSubscriptionPrice(Subscription $subscription, Price $price, BillingChangeTiming $billingChangeTiming): void
211
    {
212
        $subscription->setPrice($price);
213
        $subscription->setMoneyAmount($price->getAsMoney());
214
        $obolSubscription = $this->subscriptionFactory->createSubscriptionFromEntity($subscription);
215
        $obolSubscription->setPriceId($price->getExternalReference());
0 ignored issues
show
Bug introduced by
It seems like $price->getExternalReference() can also be of type null; however, parameter $priceId of Obol\Model\Subscription::setPriceId() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

215
        $obolSubscription->setPriceId(/** @scrutinizer ignore-type */ $price->getExternalReference());
Loading history...
216
        $prorataTye = match ($billingChangeTiming) {
217
            BillingChangeTiming::INSTANTLY => ProrataType::NOW,
218
            default => ProrataType::NONE,
219
        };
220
221
        $this->provider->subscriptions()->updatePrice($obolSubscription, $prorataTye);
222
    }
223
224
    public function changeSubscriptionPlan(Subscription $subscription, SubscriptionPlan $plan, Price $price, BillingChangeTiming $billingChangeTiming): void
225
    {
226
        $subscription->setSubscriptionPlan($plan);
227
        $subscription->setPlanName($plan->getName());
228
        $subscription->setPrice($price);
229
        $subscription->setMoneyAmount($price->getAsMoney());
230
231
        $obolSubscription = $this->subscriptionFactory->createSubscriptionFromEntity($subscription);
232
        $obolSubscription->setPriceId($price->getExternalReference());
0 ignored issues
show
Bug introduced by
It seems like $price->getExternalReference() can also be of type null; however, parameter $priceId of Obol\Model\Subscription::setPriceId() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

232
        $obolSubscription->setPriceId(/** @scrutinizer ignore-type */ $price->getExternalReference());
Loading history...
233
        $prorataTye = match ($billingChangeTiming) {
234
            BillingChangeTiming::INSTANTLY => ProrataType::NOW,
235
            default => ProrataType::NONE,
236
        };
237
238
        $this->provider->subscriptions()->updatePrice($obolSubscription, $prorataTye);
239
    }
240
}
241