Completed
Pull Request — master (#219)
by Arthur
05:01 queued 02:13
created

SubscriptionController::updatePaymentMethod()   D

Complexity

Conditions 9
Paths 12

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 4.909
c 0
b 0
f 0
cc 9
eloc 22
nc 12
nop 1
1
<?php namespace BB\Http\Controllers;
2
3
use Carbon\Carbon;
4
use BB\Entities\User;
5
use BB\Repo\SubscriptionChargeRepository;
6
7
class SubscriptionController extends Controller
8
{
9
10
11
    /**
12
     * @var SubscriptionChargeRepository
13
     */
14
    private $subscriptionChargeRepository;
15
    /**
16
     * @var \BB\Repo\UserRepository
17
     */
18
    private $userRepository;
19
20
    function __construct(\BB\Helpers\GoCardlessHelper $goCardless, SubscriptionChargeRepository $subscriptionChargeRepository, \BB\Repo\UserRepository $userRepository)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
21
    {
22
        $this->goCardless = $goCardless;
0 ignored issues
show
Bug introduced by
The property goCardless does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
23
        $this->subscriptionChargeRepository = $subscriptionChargeRepository;
24
        $this->userRepository = $userRepository;
25
26
        $this->middleware('role:member', array('only' => ['create', 'destroy']));
27
    }
28
29
    /**
30
     * Setup a new pre auth
31
     *
32
     * @return \Illuminate\Http\RedirectResponse
33
     */
34
    public function create($userId)
35
    {
36
        $user = User::findWithPermission($userId);
37
        $payment_details = array(
38
            'redirect_uri'      => route('account.subscription.store', $user->id),
0 ignored issues
show
Documentation introduced by
$user->id is of type integer, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
39
            'user'              => [
40
                'first_name'        =>  $user->given_name,
41
                'last_name'         =>  $user->family_name,
42
                'billing_address1'  =>  $user->address->line_1,
0 ignored issues
show
Documentation introduced by
The property address does not exist on object<BB\Entities\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
43
                'billing_address2'  =>  $user->address->line_2,
0 ignored issues
show
Documentation introduced by
The property address does not exist on object<BB\Entities\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
44
                'billing_town'      =>  $user->address->line_3,
0 ignored issues
show
Documentation introduced by
The property address does not exist on object<BB\Entities\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
45
                'billing_postcode'  =>  $user->address->postcode,
0 ignored issues
show
Documentation introduced by
The property address does not exist on object<BB\Entities\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
46
                'country_code'      => 'GB'
47
            ]
48
        );
49
50
        return \Redirect::to($this->goCardless->newPreAuthUrl($payment_details));
51
    }
52
53
    /**
54
     * Store a newly created resource in storage.
55
     *
56
     * @return \Illuminate\Http\RedirectResponse
57
     */
58
    public function store($userId)
59
    {
60
        $confirm_params = array(
61
            'resource_id'    => \Request::get('resource_id'),
62
            'resource_type'  => \Request::get('resource_type'),
63
            'resource_uri'   => \Request::get('resource_uri'),
64
            'signature'      => \Request::get('signature'),
65
        );
66
67
        // State is optional
68
        if (\Request::get('state')) {
69
            $confirm_params['state'] = \Request::get('state');
70
        }
71
72
        $user = User::findWithPermission($userId);
73
74
        try {
75
            $confirmed_resource = $this->goCardless->confirmResource($confirm_params);
76
        } catch (\Exception $e) {
77
            \Notification::error($e->getMessage());
78
            return \Redirect::route('account.show', $user->id);
79
        }
80
81
        if (strtolower($confirmed_resource->status) != 'active') {
82
            \Notification::error('Something went wrong, you can try again or get in contact');
83
            return \Redirect::route('account.show', $user->id);
84
        }
85
86
        $this->userRepository->recordGoCardlessVariableDetails($user->id, $confirmed_resource->id);
87
88
        //all we need for a valid member is an active dd so make sure the user account is active
89
        $this->userRepository->ensureMembershipActive($user->id);
90
91
        return \Redirect::route('account.show', [$user->id]);
92
    }
93
94
95
    /**
96
     * Remove the specified resource from storage.
97
     *
98
     * @param  int  $id
99
     * @return Illuminate\Http\RedirectResponse
100
     */
101
    public function destroy($userId, $id = null)
102
    {
103
104
        /**
105
         * TODO: Check for and cancel pending sub charges
106
         */
107
        $user = User::findWithPermission($userId);
108
        if ($user->payment_method == 'gocardless') {
109
            try {
110
                $subscription = $this->goCardless->cancelSubscription($user->subscription_id);
111
                if ($subscription->status == 'cancelled') {
112
                    $user->cancelSubscription();
0 ignored issues
show
Deprecated Code introduced by
The method BB\Entities\User::cancelSubscription() has been deprecated.

This method has been deprecated.

Loading history...
113
                    \Notification::success('Your subscription has been cancelled');
114
                    return \Redirect::back();
115
                }
116
            } catch (\GoCardless_ApiException $e) {
117
                if ($e->getCode() == 404) {
118
                    $user->cancelSubscription();
0 ignored issues
show
Deprecated Code introduced by
The method BB\Entities\User::cancelSubscription() has been deprecated.

This method has been deprecated.

Loading history...
119
                    \Notification::success('Your subscription has been cancelled');
120
                    return \Redirect::back();
121
                }
122
            }
123
        } elseif ($user->payment_method == 'gocardless-variable') {
124
            $status = $this->goCardless->cancelPreAuth($user->subscription_id);
125
            if ($status) {
126
                $user->subscription_id = null;
127
                $user->payment_method = '';
128
                $user->save();
129
130
                $user->setLeaving();
0 ignored issues
show
Deprecated Code introduced by
The method BB\Entities\User::setLeaving() has been deprecated.

This method has been deprecated.

Loading history...
131
132
                $this->subscriptionChargeRepository->cancelOutstandingCharges($userId);
133
134
                \Notification::success('Your direct debit has been cancelled');
135
                return \Redirect::back();
136
            }
137
        }
138
        \Notification::error('Sorry, we were unable to cancel your subscription, please get in contact');
139
        return \Redirect::back();
140
    }
141
142
143
    public function listCharges()
144
    {
145
        $charges = $this->subscriptionChargeRepository->getChargesPaginated();
146
        return \View::make('payments.sub-charges')->with('charges', $charges);
147
    }
148
149
    public function updatePaymentMethod($id)
150
    {
151
        $user = User::findWithPermission($id);
152
        $paymentMethod = \Input::get('payment_method');
153
154
        if ($paymentMethod === 'balance' && empty($user->payment_method) && ($user->status == 'setting-up')) {
155
            // Activate a users membership with a payment method of balance
156
            $user->payment_method  = 'balance';
157
            $user->secondary_payment_method = null;
158
            $user->payment_day = Carbon::now()->day;
159
            $user->save();
160
161
            $this->userRepository->ensureMembershipActive($user->id);
162
        }
163
164
        if ($paymentMethod === 'balance' && $user->payment_method == 'gocardless-variable') {
165
            $user->payment_method  = 'balance';
166
            $user->secondary_payment_method = 'gocardless-variable';
167
            $user->save();
168
        }
169
170
        if ($paymentMethod === 'gocardless-variable' && $user->payment_method == 'balance') {
171
            if (empty($user->subscription_id)) {
172
                $user->payment_method = null;
173
            } else {
174
                $user->payment_method = 'gocardless-variable';
175
            }
176
            $user->secondary_payment_method = null;
177
            $user->save();
178
        }
179
180
        \Notification::success('Details Updated');
181
        return \Redirect::route('account.show', [$user->id]);
182
    }
183
}
184