Completed
Push — gocardless-upgrade ( 88f819...8f5bab )
by Arthur
11:53 queued 07:44
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
            "description"          => "Build Brighton",
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal description does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
Coding Style Comprehensibility introduced by
The string literal Build Brighton does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
39
            'success_redirect_url' => 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...
40
            "session_token"        => 'user-token-'.$user->id,
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal session_token does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
41
            'prefilled_customer'   => [
42
                'given_name'    => $user->given_name,
43
                'family_name'   => $user->family_name,
44
                'email'         => $user->email,
45
                'address_line1' => $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...
46
                'address_line2' => $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...
47
                'city'          => $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...
48
                'postal_code'   => $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...
49
                'country_code'  => 'GB'
50
            ]
51
        );
52
53
        return \Redirect::to($this->goCardless->newPreAuthUrl($user, $payment_details));
54
    }
55
56
    /**
57
     * Store a newly created resource in storage.
58
     *
59
     * @return \Illuminate\Http\RedirectResponse
60
     */
61
    public function store($userId)
62
    {
63
        $confirm_params = array(
64
            'resource_id'    => \Request::get('resource_id'),
65
            'resource_type'  => \Request::get('resource_type'),
66
            'resource_uri'   => \Request::get('resource_uri'),
67
            'signature'      => \Request::get('signature'),
68
        );
69
70
        // State is optional
71
        if (\Request::get('state')) {
72
            $confirm_params['state'] = \Request::get('state');
73
        }
74
75
        $user = User::findWithPermission($userId);
76
77
        try {
78
            $confirmed_resource = $this->goCardless->confirmResource($user, $confirm_params);
79
        } catch (\Exception $e) {
80
            \Notification::error($e->getMessage());
81
            return \Redirect::route('account.show', $user->id);
82
        }
83
84
85
        if (!isset($confirmed_resource->links->mandate) || empty($confirmed_resource->links->mandate)) {
86
            \Notification::error('Something went wrong, you can try again or get in contact');
87
            return \Redirect::route('account.show', $user->id);
88
        }
89
90
        $this->userRepository->recordGoCardlessVariableDetails($user->id, $confirmed_resource->links->mandate);
91
92
        //all we need for a valid member is an active dd so make sure the user account is active
93
        $this->userRepository->ensureMembershipActive($user->id);
94
95
        return \Redirect::route('account.show', [$user->id]);
96
    }
97
98
99
    /**
100
     * Remove the specified resource from storage.
101
     *
102
     * @param  int  $id
103
     * @return Illuminate\Http\RedirectResponse
104
     */
105
    public function destroy($userId, $id = null)
106
    {
107
108
        /**
109
         * TODO: Check for and cancel pending sub charges
110
         */
111
        $user = User::findWithPermission($userId);
112
        if ($user->payment_method == 'gocardless') {
113
            try {
114
                $subscription = $this->goCardless->cancelSubscription($user->subscription_id);
115
                if ($subscription->status == 'cancelled') {
116
                    $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...
117
                    \Notification::success('Your subscription has been cancelled');
118
                    return \Redirect::back();
119
                }
120
            } catch (\Exception $e) {
121
                $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...
122
                \Notification::success('Your subscription has been cancelled');
123
                return \Redirect::back();
124
            }
125
        } elseif ($user->payment_method == 'gocardless-variable') {
126
            $status = $this->goCardless->cancelPreAuth($user->subscription_id);
127
            if ($status) {
128
                $user->subscription_id = null;
129
                $user->payment_method = '';
130
                $user->save();
131
132
                $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...
133
134
                $this->subscriptionChargeRepository->cancelOutstandingCharges($userId);
135
136
                \Notification::success('Your direct debit has been cancelled');
137
                return \Redirect::back();
138
            }
139
        }
140
        \Notification::error('Sorry, we were unable to cancel your subscription, please get in contact');
141
        return \Redirect::back();
142
    }
143
144
145
    public function listCharges()
146
    {
147
        $charges = $this->subscriptionChargeRepository->getChargesPaginated();
148
        return \View::make('payments.sub-charges')->with('charges', $charges);
149
    }
150
151
    public function updatePaymentMethod($id)
152
    {
153
        $user = User::findWithPermission($id);
154
        $paymentMethod = \Input::get('payment_method');
155
156
        if ($paymentMethod === 'balance' && empty($user->payment_method) && ($user->status == 'setting-up')) {
157
            // Activate a users membership with a payment method of balance
158
            $user->payment_method  = 'balance';
159
            $user->secondary_payment_method = null;
160
            $user->payment_day = Carbon::now()->day;
161
            $user->save();
162
163
            $this->userRepository->ensureMembershipActive($user->id);
164
        }
165
166
        if ($paymentMethod === 'balance' && $user->payment_method == 'gocardless-variable') {
167
            $user->payment_method  = 'balance';
168
            $user->secondary_payment_method = 'gocardless-variable';
169
            $user->save();
170
        }
171
172
        if ($paymentMethod === 'gocardless-variable' && $user->payment_method == 'balance') {
173
            if (empty($user->subscription_id)) {
174
                $user->payment_method = null;
175
            } else {
176
                $user->payment_method = 'gocardless-variable';
177
            }
178
            $user->secondary_payment_method = null;
179
            $user->save();
180
        }
181
182
        \Notification::success('Details Updated');
183
        return \Redirect::route('account.show', [$user->id]);
184
    }
185
}
186