Completed
Push — master ( 1795d4...4c7cfd )
by Arthur
03:27
created

AccountController::alterSubscription()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 11
nc 3
nop 1
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
        \BB\Services\Credit $bbCredit)
70
    {
71
        $this->userForm = $userForm;
72
        $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...
73
        $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...
74
        $this->userImage = $userImage;
75
        $this->userDetailsForm = $userDetailsForm;
76
        $this->profileRepo = $profileRepo;
77
        $this->inductionRepository = $inductionRepository;
78
        $this->equipmentRepository = $equipmentRepository;
79
        $this->userRepository = $userRepository;
80
        $this->profileValidator = $profileValidator;
81
        $this->addressRepository = $addressRepository;
82
        $this->subscriptionChargeRepository = $subscriptionChargeRepository;
83
        $this->bbCredit = $bbCredit;
0 ignored issues
show
Bug introduced by
The property bbCredit 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...
84
85
        //This tones down some validation rules for admins
86
        $this->userForm->setAdminOverride( ! \Auth::guest() && \Auth::user()->hasRole('admin'));
87
88
        $this->middleware('role:member', array('except' => ['create', 'store']));
89
        $this->middleware('role:admin', array('only' => ['index']));
90
        //$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...
91
92
        $paymentMethods = [
93
            'gocardless'    => 'GoCardless',
94
            'paypal'        => 'PayPal',
95
            'bank-transfer' => 'Manual Bank Transfer',
96
            'other'         => 'Other'
97
        ];
98
        \View::share('paymentMethods', $paymentMethods);
99
        \View::share('paymentDays', array_combine(range(1, 31), range(1, 31)));
100
101
    }
102
103
    /**
104
     * Display a listing of the resource.
105
     *
106
     * @return Response
107
     */
108
    public function index()
109
    {
110
        $sortBy = \Request::get('sortBy');
111
        $direction = \Request::get('direction', 'asc');
112
        $showLeft = \Request::get('showLeft', 0);
113
        $users = $this->userRepository->getPaginated(compact('sortBy', 'direction', 'showLeft'));
114
        return \View::make('account.index')->withUsers($users);
115
    }
116
117
118
    /**
119
     * Show the form for creating a new resource.
120
     *
121
     * @return Response
122
     */
123
    public function create()
124
    {
125
        \View::share('body_class', 'register_login');
126
        return \View::make('account.create');
127
    }
128
129
130
    /**
131
     * Store a newly created resource in storage.
132
     *
133
     * @return Illuminate\Http\RedirectResponse
134
     */
135
    public function store()
136
    {
137
        $input = \Input::only(
138
            'given_name',
139
            'family_name',
140
            'email',
141
            'secondary_email',
142
            'password',
143
            'phone',
144
            'address.line_1',
145
            'address.line_2',
146
            'address.line_3',
147
            'address.line_4',
148
            'address.postcode',
149
            'monthly_subscription',
150
            'emergency_contact',
151
            'new_profile_photo',
152
            'profile_photo_private',
153
            'rules_agreed',
154
            'visited_space'
155
        );
156
157
        $this->userForm->validate($input);
158
        $this->profileValidator->validate($input);
159
160
161
        $user = $this->userRepository->registerMember($input, ! \Auth::guest() && \Auth::user()->hasRole('admin'));
162
163
        if (\Input::file('new_profile_photo')) {
164
            try {
165
                $this->userImage->uploadPhoto($user->hash, \Input::file('new_profile_photo')->getRealPath(), true);
166
167
                $this->profileRepo->update($user->id, ['new_profile_photo'=>1, 'profile_photo_private'=>$input['profile_photo_private']]);
168
            } catch (\Exception $e) {
169
                \Log::error($e);
170
            }
171
        }
172
173
        //If this isn't an admin user creating the record log them in
174
        if (\Auth::guest() || ! \Auth::user()->isAdmin()) {
175
            \Auth::login($user);
176
        }
177
178
        return \Redirect::route('account.show', [$user->id]);
179
    }
180
181
182
    /**
183
     * Display the specified resource.
184
     *
185
     * @param  int  $id
186
     * @return Response
187
     */
188
    public function show($id)
189
    {
190
        $user = User::findWithPermission($id);
191
192
        $inductions = $this->equipmentRepository->getRequiresInduction();
193
194
        $userInductions = $user->inductions()->get();
195
        foreach ($inductions as $i=>$induction) {
196
            $inductions[$i]->userInduction = false;
197
            foreach ($userInductions as $userInduction) {
198
                if ($userInduction->key == $induction->induction_category) {
199
                    $inductions[$i]->userInduction = $userInduction;
200
                }
201
            }
202
        }
203
204
        //get pending address if any
205
        $newAddress = $this->addressRepository->getNewUserAddress($id);
206
207
        //Get the member subscription payments
208
        $subscriptionCharges = $this->subscriptionChargeRepository->getMemberChargesPaginated($id);
209
210
        //Get the members balance
211
        $this->bbCredit->setUserId($user->id);
212
        $memberBalance = $this->bbCredit->getBalanceFormatted();
213
214
        return \View::make('account.show')
215
            ->with('user', $user)
216
            ->with('inductions', $inductions)
217
            ->with('newAddress', $newAddress)
218
            ->with('subscriptionCharges', $subscriptionCharges)
219
            ->with('memberBalance', $memberBalance);
220
    }
221
222
223
    /**
224
     * Show the form for editing the specified resource.
225
     *
226
     * @param  int  $id
227
     * @return Response
228
     */
229
    public function edit($id)
230
    {
231
        $user = User::findWithPermission($id);
232
233
        //We need to access the address here so its available in the view
234
        $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...
235
236
        return \View::make('account.edit')->with('user', $user);
237
    }
238
239
240
    /**
241
     * Update the specified resource in storage.
242
     *
243
     * @param  int  $id
244
     * @return \Illuminate\Http\RedirectResponse
245
     */
246
    public function update($id)
247
    {
248
        $user = User::findWithPermission($id);
249
        $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');
250
251
        $this->userForm->validate($input, $user->id);
252
253
        $this->userRepository->updateMember($id, $input, \Auth::user()->hasRole('admin'));
254
255
        \Notification::success('Details Updated');
256
        return \Redirect::route('account.show', [$user->id]);
257
    }
258
259
260
261
    public function adminUpdate($id)
262
    {
263
        $user = User::findWithPermission($id);
264
265
        $madeTrusted = false;
266
267
268
        if (\Input::has('trusted')) {
269
            if ( ! $user->trusted && \Input::get('trusted')) {
270
                //User has been made a trusted member
271
                $madeTrusted = true;
272
            }
273
            $user->trusted = \Input::get('trusted');
274
        }
275
276
        if (\Input::has('key_holder')) {
277
            $user->key_holder = \Input::get('key_holder');
278
        }
279
280
        if (\Input::has('induction_completed')) {
281
            $user->induction_completed = \Input::get('induction_completed');
282
        }
283
284
        if (\Input::has('profile_photo_on_wall')) {
285
            $profileData = $user->profile()->first();
286
            $profileData->profile_photo_on_wall = \Input::get('profile_photo_on_wall');
287
            $profileData->save();
288
        }
289
290
        if (\Input::has('photo_approved')) {
291
            $profile = $user->profile()->first();
292
293
            if (\Input::get('photo_approved')) {
294
                $this->userImage->approveNewImage($user->hash);
295
                $profile->update(['new_profile_photo' => false, 'profile_photo' => true]);
296
            } else {
297
                $profile->update(['new_profile_photo' => false]);
298
                event(new MemberPhotoWasDeclined($user));
299
            }
300
        }
301
302
        $user->save();
303
304
        if (\Input::has('approve_new_address')) {
305
            if (\Input::get('approve_new_address') == 'Approve') {
306
                $this->addressRepository->approvePendingMemberAddress($id);
307
            } elseif (\Input::get('approve_new_address') == 'Decline') {
308
                $this->addressRepository->declinePendingMemberAddress($id);
309
            }
310
        }
311
312
        if ($madeTrusted) {
313
            $message = 'You have been made a trusted member at Build Brighton';
314
            $notificationHash = 'trusted_status';
315
            Notification::logNew($user->id, $message, 'trusted_status', $notificationHash);
316
            event(new MemberGivenTrustedStatus($user));
317
        }
318
319
320
        if (\Request::wantsJson()) {
321
            return \Response::json('Updated', 200);
322
        } else {
323
            \Notification::success('Details Updated');
324
            return \Redirect::route('account.show', [$user->id]);
325
        }
326
    }
327
328
329
    public function alterSubscription($id)
330
    {
331
        // I don't think this is used any more
332
333
        $user = User::findWithPermission($id);
334
        $input = \Input::all();
335
336
        $this->updateSubscriptionAdminForm->validate($input, $user->id);
337
338
        if (($user->payment_method == 'gocardless') && ($input['payment_method'] != 'gocardless')) {
339
            //Changing away from GoCardless
340
            $subscription = $this->goCardless->cancelSubscription($user->subscription_id);
341
            if ($subscription->status == 'cancelled') {
342
                $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...
343
            }
344
        }
345
346
        $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...
347
348
        \Notification::success('Details Updated');
349
        return \Redirect::route('account.show', [$user->id]);
350
    }
351
352
    public function confirmEmail($id, $hash)
353
    {
354
        $user = User::find($id);
355
        if ($user && $user->hash == $hash) {
356
            $user->emailConfirmed();
357
            \Notification::success('Email address confirmed, thank you');
358
            return \Redirect::route('account.show', $user->id);
359
        }
360
        \Notification::error('Error confirming email address');
361
        return \Redirect::route('home');
362
    }
363
364
365
366
    public function destroy($id)
367
    {
368
        $user = User::findWithPermission($id);
369
370
        // If they never became a member just delete the record
371
        if ($user->status == 'setting-up') {
372
            $user->delete();
373
374
            \Notification::success('Member deleted');
375
            return \Redirect::route('account.index');
376
        }
377
378
        //No one will ever leaves the system but we can at least update their status to left.
379
        $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...
380
381
        \Notification::success('Updated status to leaving');
382
        return \Redirect::route('account.show', [$user->id]);
383
    }
384
385
386
    public function rejoin($id)
387
    {
388
        $user = User::findWithPermission($id);
389
        $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...
390
        \Notification::success('Details Updated');
391
        return \Redirect::route('account.show', [$user->id]);
392
    }
393
394
    public function updateSubscriptionAmount($id)
395
    {
396
        $amount = \Input::get('monthly_subscription');
397
398
        if ($amount < 5) {
399
            throw new ValidationException('The minimum subscription is 5 GBP');
400
        } elseif (!\Auth::user()->isAdmin() && ($amount < 15)) {
401
            throw new ValidationException('The minimum subscription is 15 GBP, please contact the trustees for a lower amount. [email protected]');
402
        }
403
404
        $user = User::findWithPermission($id);
405
        $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...
406
        \Notification::success('Details Updated');
407
        return \Redirect::route('account.show', [$user->id]);
408
    }
409
}
410