Completed
Push — master ( 0c7343...2c4859 )
by Adolfo
02:44 queued 01:38
created

HasSubscriptions::unsubscribe()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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->hasManyIntervals()) {
38
            throw new SubscriptionErrorException(
39
                'This plan has many intervals, please use subscribeToInterval() function'
40
            );
41
        }
42
43
        $currentSubscription = $this->getActiveSubscription();
44
        $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...
45
        $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...
46
47
        if ($currentSubscription == null) {
48
            $start_at = now();
49
        } else {
50
            $start_at = $currentSubscription->getExpirationDate();
51
        }
52
53
        if ($plan->isFree()) {
54
            $end_at = null;
55
        } else {
56
            $end_at = $this->calculateExpireDate($start_at, optional($plan->intervals())->first());
57
        }
58
59
        $subscription = Subscription::make($plan, $start_at, $end_at);
60
        $subscription = $this->subscriptions()->save($subscription);
61
62
        return $subscription;
63
    }
64
65
    public function getActiveSubscription(): ?SubscriptionContact
66
    {
67
        return $this->subscriptions()
68
            ->current()
69
            ->first();
70
    }
71
72
    public function subscriptions(): MorphMany
73
    {
74
        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...
75
    }
76
77
    private function calculateExpireDate(Carbon $start_at, PlanIntervalContract $interval)
78
    {
79
        $end_at = Carbon::createFromTimestamp($start_at->timestamp);
80
81
        switch ($interval->getType()) {
82
            case PlanInterval::DAY:
83
                return $end_at->addDays($interval->getUnit());
84
                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...
85
            case PlanInterval::MONTH:
86
                return $end_at->addMonths($interval->getUnit());
87
                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...
88
            case PlanInterval::YEAR:
89
                return $end_at->addYears($interval->getUnit());
90
                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...
91
            default:
92
                throw new SubscriptionErrorException(
93
                    'The interval \''.$interval->getType().'\' selected is not available.'
94
                );
95
                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...
96
        }
97
    }
98
99
    public function subscribeToInterval(PlanIntervalContract $interval): SubscriptionContact
100
    {
101
        $currentSubscription = $this->getActiveSubscription();
102
        $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...
103
        $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...
104
105
        if ($currentSubscription == null) {
106
            $start_at = now();
107
        } else {
108
            $start_at = $currentSubscription->getExpirationDate();
109
        }
110
111
        $end_at = $this->calculateExpireDate($start_at, $interval);
112
113
        $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...
114
        $subscription = $this->subscriptions()->save($subscription);
115
116
        return $subscription;
117
    }
118
119
    public function changePlanTo(PlanContract $plan, PlanIntervalContract $interval = null)
120
    {
121
        if (! $this->hasActiveSubscription()) {
122
            throw new SubscriptionErrorException('You need a subscription for upgrade to other.');
123
        }
124
125
        if ($plan->hasManyIntervals() && $interval == null) {
126
            throw new SubscriptionErrorException('The plan has many intervals, please indicate a interval.');
127
        }
128
129
        $currentSubscription = $this->getActiveSubscription();
130
        $currentPlan = $currentSubscription->plan;
131
        $currentIntervalPrice = $currentPlan->isFree() ? 0.00 : $currentPlan->getInterval()->getPrice();
132
133
        $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...
134
135
        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...
136
            throw new SubscriptionErrorException('You can\'t change to same plan. You need change to other plan.');
137
        }
138
139
        if ($interval !== null) {
140
            $toInterval = $interval;
141
        }
142
143
        if ($currentIntervalPrice < $toInterval->getPrice()) {
144
            return $this->upgradeTo($toInterval);
145
        }
146
147
        return $this->downgradeTo($toInterval);
148
    }
149
150
    public function hasActiveSubscription(): bool
151
    {
152
        return $this->subscriptions()
153
            ->current()
154
            ->exists();
155
    }
156
157
    protected function upgradeTo(PlanIntervalContract $interval): SubscriptionContact
158
    {
159
        if (! $this->hasActiveSubscription()) {
160
            throw new SubscriptionErrorException('You need a subscription for upgrade to other.');
161
        }
162
163
        $this->forceUnsubscribe();
164
165
        return $this->subscribeToInterval($interval);
166
    }
167
168
    public function forceUnsubscribe()
169
    {
170
        $currentSubscription = $this->getActiveSubscription();
171
        $currentSubscription->end_at = now()->subSecond();
172
        $currentSubscription->cancelled_at = now();
173
        $currentSubscription->save();
174
    }
175
176
    protected function downgradeTo(PlanIntervalContract $interval): SubscriptionContact
177
    {
178
        if (! $this->hasActiveSubscription()) {
179
            throw new SubscriptionErrorException('You need a subscription for upgrade to other.');
180
        }
181
182
        return $this->subscribeToInterval($interval);
183
    }
184
185
    public function renewSubscription(PlanIntervalContract $interval = null)
186
    {
187
        $currentSubscription = $this->getActiveSubscription();
188
189
        if ($interval === null) {
190
            $plan = $currentSubscription->plan;
191
192
            if ($plan->hasManyIntervals()) {
193
                throw new SubscriptionErrorException(
194
                    'The plan you want will subscribe has many intervals, please consider renew to a interval of plan'
195
                );
196
            }
197
198
            $interval = $plan->intervals()->first();
199
        }
200
201
        $newExpireDate = $this->calculateExpireDate($currentSubscription->end_at, $interval);
202
203
        $currentSubscription->end_at = $newExpireDate;
204
        $currentSubscription->save();
205
206
        return $currentSubscription;
207
    }
208
209
    public function unsubscribe()
210
    {
211
        $currentSubscription = $this->getActiveSubscription();
212
        $currentSubscription->cancelled_at = now();
213
        $currentSubscription->save();
214
    }
215
216
    public function getConsumables()
217
    {
218
    }
219
}
220