Completed
Push — develop ( b200db...5ab519 )
by Adolfo
04:19
created

HasSubscriptions::downgradeTo()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Sagitarius29\LaravelSubscriptions\Traits;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Relations\MorphMany;
8
use Sagitarius29\LaravelSubscriptions\Entities\PlanInterval;
9
use Sagitarius29\LaravelSubscriptions\Entities\Subscription;
10
use Sagitarius29\LaravelSubscriptions\Contracts\PlanContract;
11
use Sagitarius29\LaravelSubscriptions\Contracts\SubscriptionContact;
12
use Sagitarius29\LaravelSubscriptions\Contracts\PlanIntervalContract;
13
use Sagitarius29\LaravelSubscriptions\Exceptions\SubscriptionErrorException;
14
15
trait HasSubscriptions
16
{
17
    /**
18
     * @param  PlanContract|PlanIntervalContract  $planOrInterval
19
     * @return Model|SubscriptionContact
20
     */
21
    public function subscribeTo($planOrInterval): SubscriptionContact
22
    {
23
        if ($planOrInterval instanceof PlanContract) {
24
            return $this->subscribeToPlan($planOrInterval);
25
        }
26
27
        return $this->subscribeToInterval($planOrInterval);
28
    }
29
30
    /**
31
     * @param  PlanContract  $plan
32
     * @return Model|SubscriptionContact
33
     * @throws SubscriptionErrorException
34
     */
35
    public function subscribeToPlan(PlanContract $plan): SubscriptionContact
36
    {
37
        if($plan->isDisabled()) {
38
            throw new SubscriptionErrorException(
39
                'This plan has been disabled, please subscribe to other plan.'
40
            );
41
        }
42
43
        if ($this->subscriptions()->unfinished()->count() >= 2) {
44
            throw new SubscriptionErrorException('You are changed to other plan previously');
45
        }
46
47
        if ($plan->hasManyIntervals()) {
48
            throw new SubscriptionErrorException(
49
                'This plan has many intervals, please use subscribeToInterval() function'
50
            );
51
        }
52
53
        $currentSubscription = $this->getActiveSubscription();
54
        $start_at = null;
0 ignored issues
show
Unused Code introduced by
$start_at is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
55
        $end_at = null;
0 ignored issues
show
Unused Code introduced by
$end_at is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
56
57
        if ($currentSubscription == null) {
58
            $start_at = now();
59
        } else {
60
            $start_at = $currentSubscription->getExpirationDate();
61
        }
62
63
        if ($plan->isFree()) {
64
            $end_at = null;
65
        } else {
66
            $end_at = $this->calculateExpireDate($start_at, optional($plan->intervals())->first());
67
        }
68
69
        $subscription = Subscription::make($plan, $start_at, $end_at);
70
        $subscription = $this->subscriptions()->save($subscription);
71
72
        return $subscription;
73
    }
74
75
    public function getActiveSubscription(): ?SubscriptionContact
76
    {
77
        return $this->subscriptions()
78
            ->current()
79
            ->first();
80
    }
81
82
    public function subscriptions(): MorphMany
83
    {
84
        return $this->morphMany(config('subscriptions.entities.plan_subscription'), 'subscriber');
0 ignored issues
show
Bug introduced by
It seems like morphMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
85
    }
86
87
    private function calculateExpireDate(Carbon $start_at, PlanIntervalContract $interval)
88
    {
89
        $end_at = Carbon::createFromTimestamp($start_at->timestamp);
90
91
        switch ($interval->getType()) {
92
            case PlanInterval::DAY:
93
                return $end_at->addDays($interval->getUnit());
94
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
95
            case PlanInterval::MONTH:
96
                return $end_at->addMonths($interval->getUnit());
97
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
98
            case PlanInterval::YEAR:
99
                return $end_at->addYears($interval->getUnit());
100
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
101
            default:
102
                throw new SubscriptionErrorException(
103
                    'The interval \''.$interval->getType().'\' selected is not available.'
104
                );
105
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
106
        }
107
    }
108
109
    public function subscribeToInterval(PlanIntervalContract $interval): SubscriptionContact
110
    {
111
        if($interval->plan->isDisabled()) {
0 ignored issues
show
Bug introduced by
Accessing plan on the interface Sagitarius29\LaravelSubs...ts\PlanIntervalContract suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
112
            throw new SubscriptionErrorException(
113
                'This plan has been disabled, please subscribe to other plan.'
114
            );
115
        }
116
117
        if ($this->subscriptions()->unfinished()->count() >= 2) {
118
            throw new SubscriptionErrorException('You are changed to other plan previously');
119
        }
120
121
        $currentSubscription = $this->getActiveSubscription();
122
        $start_at = null;
0 ignored issues
show
Unused Code introduced by
$start_at is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
123
        $end_at = null;
0 ignored issues
show
Unused Code introduced by
$end_at is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
124
125
        if ($currentSubscription == null) {
126
            $start_at = now();
127
        } else {
128
            $start_at = $currentSubscription->getExpirationDate();
129
        }
130
131
        $end_at = $this->calculateExpireDate($start_at, $interval);
132
133
        $subscription = Subscription::make($interval->plan, $start_at, $end_at);
0 ignored issues
show
Bug introduced by
Accessing plan on the interface Sagitarius29\LaravelSubs...ts\PlanIntervalContract suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
134
        $subscription = $this->subscriptions()->save($subscription);
135
136
        return $subscription;
137
    }
138
139
    public function changePlanTo(PlanContract $plan, PlanIntervalContract $interval = null)
140
    {
141
        if (! $this->hasActiveSubscription()) {
142
            throw new SubscriptionErrorException('You need a subscription for upgrade to other.');
143
        }
144
145
        if ($plan->hasManyIntervals() && $interval == null) {
146
            throw new SubscriptionErrorException('The plan has many intervals, please indicate a interval.');
147
        }
148
149
        if ($this->subscriptions()->unfinished()->count() >= 2) {
150
            throw new SubscriptionErrorException('You are changed to other plan previously');
151
        }
152
153
        $currentSubscription = $this->getActiveSubscription();
154
        $currentPlan = $currentSubscription->plan;
155
        $currentIntervalPrice = $currentPlan->isFree() ? 0.00 : $currentPlan->getInterval()->getPrice();
156
157
        $toInterval = $plan->getInterval();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Sagitarius29\LaravelSubs...\Contracts\PlanContract as the method getInterval() does only exist in the following implementations of said interface: Sagitarius29\LaravelSubscriptions\Entities\Plan.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
158
159
        if ($currentPlan->id == $plan->id) {
0 ignored issues
show
Bug introduced by
Accessing id on the interface Sagitarius29\LaravelSubs...\Contracts\PlanContract suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
160
            throw new SubscriptionErrorException('You can\'t change to same plan. You need change to other plan.');
161
        }
162
163
        if ($interval !== null) {
164
            $toInterval = $interval;
165
        }
166
167
        if ($currentIntervalPrice < $toInterval->getPrice()) {
168
            return $this->upgradeTo($toInterval);
169
        }
170
171
        return $this->downgradeTo($toInterval);
172
    }
173
174
    public function hasActiveSubscription(): bool
175
    {
176
        return $this->subscriptions()
177
            ->current()
178
            ->exists();
179
    }
180
181
    protected function upgradeTo(PlanIntervalContract $interval): SubscriptionContact
182
    {
183
        if (! $this->hasActiveSubscription()) {
184
            throw new SubscriptionErrorException('You need a subscription for upgrade to other.');
185
        }
186
187
        $this->forceUnsubscribe();
188
189
        return $this->subscribeToInterval($interval);
190
    }
191
192
    public function forceUnsubscribe()
193
    {
194
        $currentSubscription = $this->getActiveSubscription();
195
        $currentSubscription->end_at = now()->subSecond();
196
        $currentSubscription->cancelled_at = now();
197
        $currentSubscription->save();
198
    }
199
200
    protected function downgradeTo(PlanIntervalContract $interval): SubscriptionContact
201
    {
202
        if (! $this->hasActiveSubscription()) {
203
            throw new SubscriptionErrorException('You need a subscription for upgrade to other.');
204
        }
205
206
        return $this->subscribeToInterval($interval);
207
    }
208
209
    public function renewSubscription(PlanIntervalContract $interval = null)
210
    {
211
        if ($this->subscriptions()->unfinished()->count() >= 2) {
212
            throw new SubscriptionErrorException('You are changed to other plan previously');
213
        }
214
215
        $currentSubscription = $this->getActiveSubscription();
216
217
        if ($interval === null) {
218
            $plan = $currentSubscription->plan;
219
220
            if ($plan->hasManyIntervals()) {
221
                throw new SubscriptionErrorException(
222
                    'The plan you want will subscribe has many intervals, please consider renew to a interval of plan'
223
                );
224
            }
225
226
            $interval = $plan->intervals()->first();
227
        }
228
229
        $newExpireDate = $this->calculateExpireDate($currentSubscription->end_at, $interval);
230
231
        $currentSubscription->end_at = $newExpireDate;
232
        $currentSubscription->save();
233
234
        return $currentSubscription;
235
    }
236
237
    public function unsubscribe()
238
    {
239
        $currentSubscription = $this->getActiveSubscription();
240
        $currentSubscription->cancelled_at = now();
241
        $currentSubscription->save();
242
    }
243
244
    public function getConsumables()
245
    {
246
    }
247
}
248