Completed
Push — master ( a8e708...5c0517 )
by Arthur
06:07
created

AccountController   C

Complexity

Total Complexity 44

Size/Duplication

Total Lines 388
Duplicated Lines 4.38 %

Coupling/Cohesion

Components 2
Dependencies 17

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 44
c 4
b 0
f 1
lcom 2
cbo 17
dl 17
loc 388
rs 6.3722

15 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 46 2
A index() 0 8 1
A create() 0 5 1
B store() 0 27 6
B show() 0 24 4
A induction() 0 6 1
A updateInduction() 0 12 1
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
     * @var InductionValidator
56
     */
57
    private $inductionValidator;
58
59
60
    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...
61
        \BB\Validators\UserValidator $userForm,
62
        \BB\Validators\UpdateSubscription $updateSubscriptionAdminForm,
63
        \BB\Helpers\GoCardlessHelper $goCardless,
64
        \BB\Helpers\UserImage $userImage,
65
        \BB\Validators\UserDetails $userDetailsForm,
66
        \BB\Repo\ProfileDataRepository $profileRepo,
67
        \BB\Repo\InductionRepository $inductionRepository,
68
        \BB\Repo\EquipmentRepository $equipmentRepository,
69
        \BB\Repo\UserRepository $userRepository,
70
        \BB\Validators\ProfileValidator $profileValidator,
71
        \BB\Repo\AddressRepository $addressRepository,
72
        \BB\Repo\SubscriptionChargeRepository $subscriptionChargeRepository,
73
        InductionValidator $inductionValidator)
74
    {
75
        $this->userForm = $userForm;
76
        $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...
77
        $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...
78
        $this->userImage = $userImage;
79
        $this->userDetailsForm = $userDetailsForm;
80
        $this->profileRepo = $profileRepo;
81
        $this->inductionRepository = $inductionRepository;
82
        $this->equipmentRepository = $equipmentRepository;
83
        $this->userRepository = $userRepository;
84
        $this->profileValidator = $profileValidator;
85
        $this->addressRepository = $addressRepository;
86
        $this->subscriptionChargeRepository = $subscriptionChargeRepository;
87
        $this->inductionValidator = $inductionValidator;
88
89
        //This tones down some validation rules for admins
90
        $this->userForm->setAdminOverride( ! \Auth::guest() && \Auth::user()->hasRole('admin'));
91
92
        $this->middleware('role:member', array('except' => ['create', 'store']));
93
        $this->middleware('role:admin', array('only' => ['index']));
94
        //$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...
95
96
        $paymentMethods = [
97
            'gocardless'    => 'GoCardless',
98
            'paypal'        => 'PayPal',
99
            'bank-transfer' => 'Manual Bank Transfer',
100
            'other'         => 'Other'
101
        ];
102
        \View::share('paymentMethods', $paymentMethods);
103
        \View::share('paymentDays', array_combine(range(1, 31), range(1, 31)));
104
105
    }
106
107
    /**
108
     * Display a listing of the resource.
109
     *
110
     * @return Response
111
     */
112
    public function index()
113
    {
114
        $sortBy = \Request::get('sortBy');
115
        $direction = \Request::get('direction', 'asc');
116
        $showLeft = \Request::get('showLeft', 0);
117
        $users = $this->userRepository->getPaginated(compact('sortBy', 'direction', 'showLeft'));
118
        return \View::make('account.index')->withUsers($users);
119
    }
120
121
122
    /**
123
     * Show the form for creating a new resource.
124
     *
125
     * @return Response
126
     */
127
    public function create()
128
    {
129
        \View::share('body_class', 'register_login');
130
        return \View::make('account.create');
131
    }
132
133
134
    /**
135
     * Store a newly created resource in storage.
136
     *
137
     * @return Illuminate\Http\RedirectResponse
138
     */
139
    public function store()
140
    {
141
        $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');
142
143
        $this->userForm->validate($input);
144
        $this->profileValidator->validate($input);
145
146
147
        $user = $this->userRepository->registerMember($input, ! \Auth::guest() && \Auth::user()->hasRole('admin'));
148
149
        if (\Input::file('new_profile_photo')) {
150
            try {
151
                $this->userImage->uploadPhoto($user->hash, \Input::file('new_profile_photo')->getRealPath(), true);
152
153
                $this->profileRepo->update($user->id, ['new_profile_photo'=>1, 'profile_photo_private'=>$input['profile_photo_private']]);
154
            } catch (\Exception $e) {
155
                \Log::error($e);
156
            }
157
        }
158
159
        //If this isn't an admin user creating the record log them in
160
        if (\Auth::guest() || ! \Auth::user()->isAdmin()) {
161
            \Auth::login($user);
162
        }
163
164
        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...
165
    }
166
167
168
    /**
169
     * Display the specified resource.
170
     *
171
     * @param  int  $id
172
     * @return Response
173
     */
174
    public function show($id)
175
    {
176
        $user = User::findWithPermission($id);
177
178
        $inductions = $this->equipmentRepository->getRequiresInduction();
179
180
        $userInductions = $user->inductions()->get();
181
        foreach ($inductions as $i=>$induction) {
182
            $inductions[$i]->userInduction = false;
183
            foreach ($userInductions as $userInduction) {
184
                if ($userInduction->key == $induction->device_key) {
185
                    $inductions[$i]->userInduction = $userInduction;
186
                }
187
            }
188
        }
189
190
        //get pending address if any
191
        $newAddress = $this->addressRepository->getNewUserAddress($id);
192
193
        //Get the member subscription payments
194
        $subscriptionCharges = $this->subscriptionChargeRepository->getMemberChargesPaginated($id);
195
196
        return \View::make('account.show')->with('user', $user)->with('inductions', $inductions)->with('newAddress', $newAddress)->with('subscriptionCharges', $subscriptionCharges);
197
    }
198
199
    public function induction($id)
200
    {
201
        $user = User::findWithPermission($id);
202
203
        return view('account.induction')->with('user', $user);
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
204
    }
205
206
    public function updateInduction($id)
207
    {
208
        $user = User::findWithPermission($id);
209
210
        $input = \Input::only('rules_agreed', 'induction_completed');
211
212
        $this->inductionValidator->validate($input);
213
214
        $this->userRepository->recordInductionCompleted($id);
215
216
        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...
217
    }
218
219
220
    /**
221
     * Show the form for editing the specified resource.
222
     *
223
     * @param  int  $id
224
     * @return Response
225
     */
226
    public function edit($id)
227
    {
228
        $user = User::findWithPermission($id);
229
230
        //We need to access the address here so its available in the view
231
        $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...
232
233
        return \View::make('account.edit')->with('user', $user);
234
    }
235
236
237
    /**
238
     * Update the specified resource in storage.
239
     *
240
     * @param  int  $id
241
     * @return \Illuminate\Http\RedirectResponse
242
     */
243
    public function update($id)
244
    {
245
        $user = User::findWithPermission($id);
246
        $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');
247
248
        $this->userForm->validate($input, $user->id);
249
250
        $this->userRepository->updateMember($id, $input, \Auth::user()->hasRole('admin'));
251
252
        \Notification::success('Details Updated');
253
        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...
254
    }
255
256
257
258
    public function adminUpdate($id)
259
    {
260
        $user = User::findWithPermission($id);
261
262
        $madeTrusted = false;
263
264
265
        if (\Input::has('trusted')) {
266
            if ( ! $user->trusted && \Input::get('trusted')) {
267
                //User has been made a trusted member
268
                $madeTrusted = true;
269
            }
270
            $user->trusted = \Input::get('trusted');
271
        }
272
273
        if (\Input::has('key_holder')) {
274
            $user->key_holder = \Input::get('key_holder');
275
        }
276
277
        if (\Input::has('induction_completed')) {
278
            $user->induction_completed = \Input::get('induction_completed');
279
        }
280
281
        if (\Input::has('profile_photo_on_wall')) {
282
            $profileData = $user->profile()->first();
283
            $profileData->profile_photo_on_wall = \Input::get('profile_photo_on_wall');
284
            $profileData->save();
285
        }
286
287
        if (\Input::has('photo_approved')) {
288
            $profile = $user->profile()->first();
289
290
            if (\Input::get('photo_approved')) {
291
                $this->userImage->approveNewImage($user->hash);
292
                $profile->update(['new_profile_photo' => false, 'profile_photo' => true]);
293
            } else {
294
                $profile->update(['new_profile_photo' => false]);
295
                event(new MemberPhotoWasDeclined($user));
296
            }
297
        }
298
299
        if (\Input::has('inducted_by')) {
300
            $user->inducted_by = \Auth::id();
0 ignored issues
show
Documentation introduced by
The property inducted_by does not exist on object<BB\Entities\User>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
301
        }
302
303
        $user->save();
304
305
        if (\Input::has('approve_new_address')) {
306
            if (\Input::get('approve_new_address') == 'Approve') {
307
                $this->addressRepository->approvePendingMemberAddress($id);
308
            } elseif (\Input::get('approve_new_address') == 'Decline') {
309
                $this->addressRepository->declinePendingMemberAddress($id);
310
            }
311
        }
312
313
        if ($madeTrusted) {
314
            $message = 'You have been made a trusted member at Build Brighton';
315
            $notificationHash = 'trusted_status';
316
            Notification::logNew($user->id, $message, 'trusted_status', $notificationHash);
317
            event(new MemberGivenTrustedStatus($user));
318
        }
319
320
321
        if (\Request::wantsJson()) {
322
            return \Response::json('Updated', 200);
323
        } else {
324
            \Notification::success('Details Updated');
325
            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...
326
        }
327
    }
328
329
330
    public function alterSubscription($id)
331
    {
332
        $user = User::findWithPermission($id);
333
        $input = \Input::all();
334
335
        $this->updateSubscriptionAdminForm->validate($input, $user->id);
336
337
        if (($user->payment_method == 'gocardless') && ($input['payment_method'] != 'gocardless')) {
338
            //Changing away from GoCardless
339
            $subscription = $this->goCardless->cancelSubscription($user->subscription_id);
340
            if ($subscription->status == 'cancelled') {
341
                $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...
342
            }
343
        }
344
345
        $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...
346
347
        \Notification::success('Details Updated');
348
        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...
349
    }
350
351
    public function confirmEmail($id, $hash)
352
    {
353
        $user = User::find($id);
354
        if ($user && $user->hash == $hash) {
355
            $user->emailConfirmed();
356
            \Notification::success('Email address confirmed, thank you');
357
            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...
358
        }
359
        \Notification::error('Error confirming email address');
360
        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...
361
    }
362
363
364
365 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...
366
    {
367
        $user = User::findWithPermission($id);
368
369
        //No one will ever leaves the system but we can at least update their status to left.
370
        $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...
371
372
        \Notification::success('Updated status to leaving');
373
        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...
374
    }
375
376
377 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...
378
    {
379
        $user = User::findWithPermission($id);
380
        $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...
381
        \Notification::success('Details Updated');
382
        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...
383
    }
384
385
    public function updateSubscriptionAmount($id)
386
    {
387
        $amount = \Input::get('monthly_subscription');
388
389
        if ($amount < 5) {
390
            throw new ValidationException('The minimum subscription is 5 GBP');
391
        }
392
393
        $user = User::findWithPermission($id);
394
        $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...
395
        \Notification::success('Details Updated');
396
        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...
397
    }
398
}
399