Completed
Push — master ( 907be4...4d46ed )
by Arthur
05:36
created

AccountController   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 362
Duplicated Lines 4.7 %

Coupling/Cohesion

Components 2
Dependencies 16

Importance

Changes 5
Bugs 0 Features 2
Metric Value
wmc 42
c 5
b 0
f 2
lcom 2
cbo 16
dl 17
loc 362
rs 7.0367

13 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 44 2
A index() 0 8 1
A create() 0 5 1
B store() 0 27 6
B show() 0 24 4
A edit() 0 9 1
A update() 0 12 1
F adminUpdate() 0 70 15
A alterSubscription() 0 20 4
A confirmEmail() 0 11 3
A destroy() 10 10 1
A rejoin() 7 7 1
A updateSubscriptionAmount() 0 13 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AccountController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AccountController, and based on these observations, apply Extract Interface, too.

1
<?php namespace BB\Http\Controllers;
2
3
4
use BB\Entities\Notification;
5
use BB\Entities\User;
6
use BB\Events\MemberGivenTrustedStatus;
7
use BB\Events\MemberPhotoWasDeclined;
8
use BB\Exceptions\ValidationException;
9
use BB\Validators\InductionValidator;
10
11
class AccountController extends Controller
12
{
13
14
    protected $layout = 'layouts.main';
15
16
    protected $userForm;
17
18
    /**
19
     * @var \BB\Helpers\UserImage
20
     */
21
    private $userImage;
22
    /**
23
     * @var \BB\Validators\UserDetails
24
     */
25
    private $userDetailsForm;
26
    /**
27
     * @var \BB\Repo\ProfileDataRepository
28
     */
29
    private $profileRepo;
30
    /**
31
     * @var \BB\Repo\InductionRepository
32
     */
33
    private $inductionRepository;
34
    /**
35
     * @var \BB\Repo\EquipmentRepository
36
     */
37
    private $equipmentRepository;
38
    /**
39
     * @var \BB\Repo\UserRepository
40
     */
41
    private $userRepository;
42
    /**
43
     * @var \BB\Validators\ProfileValidator
44
     */
45
    private $profileValidator;
46
    /**
47
     * @var \BB\Repo\AddressRepository
48
     */
49
    private $addressRepository;
50
    /**
51
     * @var \BB\Repo\SubscriptionChargeRepository
52
     */
53
    private $subscriptionChargeRepository;
54
55
56
    function __construct(
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...
57
        \BB\Validators\UserValidator $userForm,
58
        \BB\Validators\UpdateSubscription $updateSubscriptionAdminForm,
59
        \BB\Helpers\GoCardlessHelper $goCardless,
60
        \BB\Helpers\UserImage $userImage,
61
        \BB\Validators\UserDetails $userDetailsForm,
62
        \BB\Repo\ProfileDataRepository $profileRepo,
63
        \BB\Repo\InductionRepository $inductionRepository,
64
        \BB\Repo\EquipmentRepository $equipmentRepository,
65
        \BB\Repo\UserRepository $userRepository,
66
        \BB\Validators\ProfileValidator $profileValidator,
67
        \BB\Repo\AddressRepository $addressRepository,
68
        \BB\Repo\SubscriptionChargeRepository $subscriptionChargeRepository)
69
    {
70
        $this->userForm = $userForm;
71
        $this->updateSubscriptionAdminForm = $updateSubscriptionAdminForm;
0 ignored issues
show
Bug introduced by
The property updateSubscriptionAdminForm 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...
72
        $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...
73
        $this->userImage = $userImage;
74
        $this->userDetailsForm = $userDetailsForm;
75
        $this->profileRepo = $profileRepo;
76
        $this->inductionRepository = $inductionRepository;
77
        $this->equipmentRepository = $equipmentRepository;
78
        $this->userRepository = $userRepository;
79
        $this->profileValidator = $profileValidator;
80
        $this->addressRepository = $addressRepository;
81
        $this->subscriptionChargeRepository = $subscriptionChargeRepository;
82
83
        //This tones down some validation rules for admins
84
        $this->userForm->setAdminOverride( ! \Auth::guest() && \Auth::user()->hasRole('admin'));
85
86
        $this->middleware('role:member', array('except' => ['create', 'store']));
87
        $this->middleware('role:admin', array('only' => ['index']));
88
        //$this->middleware('guest', array('only' => ['create', 'store']));
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
89
90
        $paymentMethods = [
91
            'gocardless'    => 'GoCardless',
92
            'paypal'        => 'PayPal',
93
            'bank-transfer' => 'Manual Bank Transfer',
94
            'other'         => 'Other'
95
        ];
96
        \View::share('paymentMethods', $paymentMethods);
97
        \View::share('paymentDays', array_combine(range(1, 31), range(1, 31)));
98
99
    }
100
101
    /**
102
     * Display a listing of the resource.
103
     *
104
     * @return Response
105
     */
106
    public function index()
107
    {
108
        $sortBy = \Request::get('sortBy');
109
        $direction = \Request::get('direction', 'asc');
110
        $showLeft = \Request::get('showLeft', 0);
111
        $users = $this->userRepository->getPaginated(compact('sortBy', 'direction', 'showLeft'));
112
        return \View::make('account.index')->withUsers($users);
113
    }
114
115
116
    /**
117
     * Show the form for creating a new resource.
118
     *
119
     * @return Response
120
     */
121
    public function create()
122
    {
123
        \View::share('body_class', 'register_login');
124
        return \View::make('account.create');
125
    }
126
127
128
    /**
129
     * Store a newly created resource in storage.
130
     *
131
     * @return Illuminate\Http\RedirectResponse
132
     */
133
    public function store()
134
    {
135
        $input = \Input::only('given_name', 'family_name', 'email', 'secondary_email', 'password', 'phone', 'address.line_1', 'address.line_2', 'address.line_3', 'address.line_4', 'address.postcode', 'monthly_subscription', 'emergency_contact', 'new_profile_photo', 'profile_photo_private', 'rules_agreed');
136
137
        $this->userForm->validate($input);
138
        $this->profileValidator->validate($input);
139
140
141
        $user = $this->userRepository->registerMember($input, ! \Auth::guest() && \Auth::user()->hasRole('admin'));
142
143
        if (\Input::file('new_profile_photo')) {
144
            try {
145
                $this->userImage->uploadPhoto($user->hash, \Input::file('new_profile_photo')->getRealPath(), true);
146
147
                $this->profileRepo->update($user->id, ['new_profile_photo'=>1, 'profile_photo_private'=>$input['profile_photo_private']]);
148
            } catch (\Exception $e) {
149
                \Log::error($e);
150
            }
151
        }
152
153
        //If this isn't an admin user creating the record log them in
154
        if (\Auth::guest() || ! \Auth::user()->isAdmin()) {
155
            \Auth::login($user);
156
        }
157
158
        return \Redirect::route('account.show', [$user->id]);
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
159
    }
160
161
162
    /**
163
     * Display the specified resource.
164
     *
165
     * @param  int  $id
166
     * @return Response
167
     */
168
    public function show($id)
169
    {
170
        $user = User::findWithPermission($id);
171
172
        $inductions = $this->equipmentRepository->getRequiresInduction();
173
174
        $userInductions = $user->inductions()->get();
175
        foreach ($inductions as $i=>$induction) {
176
            $inductions[$i]->userInduction = false;
177
            foreach ($userInductions as $userInduction) {
178
                if ($userInduction->key == $induction->device_key) {
179
                    $inductions[$i]->userInduction = $userInduction;
180
                }
181
            }
182
        }
183
184
        //get pending address if any
185
        $newAddress = $this->addressRepository->getNewUserAddress($id);
186
187
        //Get the member subscription payments
188
        $subscriptionCharges = $this->subscriptionChargeRepository->getMemberChargesPaginated($id);
189
190
        return \View::make('account.show')->with('user', $user)->with('inductions', $inductions)->with('newAddress', $newAddress)->with('subscriptionCharges', $subscriptionCharges);
191
    }
192
193
194
    /**
195
     * Show the form for editing the specified resource.
196
     *
197
     * @param  int  $id
198
     * @return Response
199
     */
200
    public function edit($id)
201
    {
202
        $user = User::findWithPermission($id);
203
204
        //We need to access the address here so its available in the view
205
        $user->address;
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...
206
207
        return \View::make('account.edit')->with('user', $user);
208
    }
209
210
211
    /**
212
     * Update the specified resource in storage.
213
     *
214
     * @param  int  $id
215
     * @return \Illuminate\Http\RedirectResponse
216
     */
217
    public function update($id)
218
    {
219
        $user = User::findWithPermission($id);
220
        $input = \Input::only('given_name', 'family_name', 'email', 'secondary_email', 'password', 'phone', 'address.line_1', 'address.line_2', 'address.line_3', 'address.line_4', 'address.postcode', 'emergency_contact', 'profile_private');
221
222
        $this->userForm->validate($input, $user->id);
223
224
        $this->userRepository->updateMember($id, $input, \Auth::user()->hasRole('admin'));
225
226
        \Notification::success('Details Updated');
227
        return \Redirect::route('account.show', [$user->id]);
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
228
    }
229
230
231
232
    public function adminUpdate($id)
233
    {
234
        $user = User::findWithPermission($id);
235
236
        $madeTrusted = false;
237
238
239
        if (\Input::has('trusted')) {
240
            if ( ! $user->trusted && \Input::get('trusted')) {
241
                //User has been made a trusted member
242
                $madeTrusted = true;
243
            }
244
            $user->trusted = \Input::get('trusted');
245
        }
246
247
        if (\Input::has('key_holder')) {
248
            $user->key_holder = \Input::get('key_holder');
249
        }
250
251
        if (\Input::has('induction_completed')) {
252
            $user->induction_completed = \Input::get('induction_completed');
253
        }
254
255
        if (\Input::has('profile_photo_on_wall')) {
256
            $profileData = $user->profile()->first();
257
            $profileData->profile_photo_on_wall = \Input::get('profile_photo_on_wall');
258
            $profileData->save();
259
        }
260
261
        if (\Input::has('photo_approved')) {
262
            $profile = $user->profile()->first();
263
264
            if (\Input::get('photo_approved')) {
265
                $this->userImage->approveNewImage($user->hash);
266
                $profile->update(['new_profile_photo' => false, 'profile_photo' => true]);
267
            } else {
268
                $profile->update(['new_profile_photo' => false]);
269
                event(new MemberPhotoWasDeclined($user));
270
            }
271
        }
272
273
        if (\Input::has('inducted_by')) {
274
            $user->inducted_by = \Auth::id();
275
        }
276
277
        $user->save();
278
279
        if (\Input::has('approve_new_address')) {
280
            if (\Input::get('approve_new_address') == 'Approve') {
281
                $this->addressRepository->approvePendingMemberAddress($id);
282
            } elseif (\Input::get('approve_new_address') == 'Decline') {
283
                $this->addressRepository->declinePendingMemberAddress($id);
284
            }
285
        }
286
287
        if ($madeTrusted) {
288
            $message = 'You have been made a trusted member at Build Brighton';
289
            $notificationHash = 'trusted_status';
290
            Notification::logNew($user->id, $message, 'trusted_status', $notificationHash);
291
            event(new MemberGivenTrustedStatus($user));
292
        }
293
294
295
        if (\Request::wantsJson()) {
296
            return \Response::json('Updated', 200);
297
        } else {
298
            \Notification::success('Details Updated');
299
            return \Redirect::route('account.show', [$user->id]);
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
300
        }
301
    }
302
303
304
    public function alterSubscription($id)
305
    {
306
        $user = User::findWithPermission($id);
307
        $input = \Input::all();
308
309
        $this->updateSubscriptionAdminForm->validate($input, $user->id);
310
311
        if (($user->payment_method == 'gocardless') && ($input['payment_method'] != 'gocardless')) {
312
            //Changing away from GoCardless
313
            $subscription = $this->goCardless->cancelSubscription($user->subscription_id);
314
            if ($subscription->status == 'cancelled') {
315
                $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...
316
            }
317
        }
318
319
        $user->updateSubscription($input['payment_method'], $input['payment_day']);
0 ignored issues
show
Deprecated Code introduced by
The method BB\Entities\User::updateSubscription() has been deprecated.

This method has been deprecated.

Loading history...
320
321
        \Notification::success('Details Updated');
322
        return \Redirect::route('account.show', [$user->id]);
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
323
    }
324
325
    public function confirmEmail($id, $hash)
326
    {
327
        $user = User::find($id);
328
        if ($user && $user->hash == $hash) {
329
            $user->emailConfirmed();
330
            \Notification::success('Email address confirmed, thank you');
331
            return \Redirect::route('account.show', $user->id);
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
332
        }
333
        \Notification::error('Error confirming email address');
334
        return \Redirect::route('home');
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
335
    }
336
337
338
339 View Code Duplication
    public function destroy($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
340
    {
341
        $user = User::findWithPermission($id);
342
343
        //No one will ever leaves the system but we can at least update their status to left.
344
        $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...
345
346
        \Notification::success('Updated status to leaving');
347
        return \Redirect::route('account.show', [$user->id]);
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
348
    }
349
350
351 View Code Duplication
    public function rejoin($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
352
    {
353
        $user = User::findWithPermission($id);
354
        $user->rejoin();
0 ignored issues
show
Deprecated Code introduced by
The method BB\Entities\User::rejoin() has been deprecated.

This method has been deprecated.

Loading history...
355
        \Notification::success('Details Updated');
356
        return \Redirect::route('account.show', [$user->id]);
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
357
    }
358
359
    public function updateSubscriptionAmount($id)
360
    {
361
        $amount = \Input::get('monthly_subscription');
362
363
        if ($amount < 5) {
364
            throw new ValidationException('The minimum subscription is 5 GBP');
365
        }
366
367
        $user = User::findWithPermission($id);
368
        $user->updateSubAmount(\Input::get('monthly_subscription'));
0 ignored issues
show
Deprecated Code introduced by
The method BB\Entities\User::updateSubAmount() has been deprecated.

This method has been deprecated.

Loading history...
369
        \Notification::success('Details Updated');
370
        return \Redirect::route('account.show', [$user->id]);
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
371
    }
372
}
373