Passed
Push — develop ( faa3f8...82f9ab )
by Francisco
03:19
created

EnrollmentExchangeController::store()   B

Complexity

Conditions 4
Paths 7

Size

Total Lines 40
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 20
nc 7
nop 2
dl 0
loc 40
rs 8.5806
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use App\Judite\Models\Exchange;
7
use App\Judite\Models\Enrollment;
8
use Illuminate\Support\Facades\DB;
9
use App\Events\ExchangeWasConfirmed;
10
use App\Http\Requests\Exchange\CreateRequest;
11
use App\Exceptions\EnrollmentCannotBeExchangedException;
12
use App\Exceptions\ExchangeEnrollmentsOnDifferentCoursesException;
13
14
class EnrollmentExchangeController extends Controller
15
{
16
    /**
17
     * Create a new controller instance.
18
     */
19
    public function __construct()
20
    {
21
        $this->middleware('can.exchange');
22
    }
23
24
    /**
25
     * Show the form for creating a new resource.
26
     *
27
     * @param int $id
28
     *
29
     * @return \Illuminate\Http\Response
30
     */
31
    public function create($id)
32
    {
33
        try {
34
            $data = DB::transaction(function () use ($id) {
35
                $enrollment = student()->enrollments()->findOrFail($id);
36
37
                if (! $enrollment->availableForExchange()) {
38
                    throw new \LogicException('The enrollment is not available for exchange.');
39
                }
40
41
                $matchingEnrollments = Enrollment::similarEnrollments($enrollment)
42
                    ->orderByStudent()
43
                    ->get();
44
45
                return compact('enrollment', 'matchingEnrollments');
46
            });
47
48
            $data['matchingEnrollments'] = $data['matchingEnrollments']->map(function ($item) {
49
                return [
50
                    'id' => $item->id,
51
                    '_toString' => $item->present()->inlineToString(),
52
                ];
53
            });
54
55
            return view('exchanges.create', $data);
0 ignored issues
show
Bug Best Practice introduced by
The expression return view('exchanges.create', $data) returns the type Illuminate\View\View which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
56
        } catch (\LogicException $e) {
57
            flash($e->getMessage())->error();
58
59
            return redirect()->route('home');
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->route('home') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
60
        }
61
    }
62
63
    /**
64
     * Store a newly created resource in storage.
65
     *
66
     * @param int                                       $id
67
     * @param \App\Http\Requests\Exchange\CreateRequest $request
68
     *
69
     * @return \Illuminate\Http\Response
70
     */
71
    public function store($id, CreateRequest $request)
72
    {
73
        try {
74
            $exchange = DB::transaction(function () use ($id, $request) {
75
                $this->validate($request, [
76
                    'to_enrollment_id' => 'exists:enrollments,id',
77
                ]);
78
79
                $fromEnrollment = student()->enrollments()->findOrFail($id);
80
                $toEnrollment = Enrollment::find($request->input('to_enrollment_id'));
81
82
                // Firstly check if the inverse exchange for the same enrollments
83
                // already exists. If the inverse record is found then we will
84
                // exchange and update both enrollments of this exchange.
85
                if ($exchange = Exchange::findMatchingExchange($fromEnrollment, $toEnrollment)) {
86
                    return $exchange->perform();
87
                }
88
89
                // Otherwise, we create a new exchange between both enrollments
90
                // so the user that owns the target enrollment can confirm the
91
                // exchange and allow the other user to enroll on the shift.
92
                $exchange = Exchange::make();
93
                $exchange->setExchangeEnrollments($fromEnrollment, $toEnrollment);
94
                $exchange->save();
95
96
                return $exchange;
97
            });
98
99
            $message = 'The exchange was successfully proposed.';
100
            if ($exchange->isPerformed()) {
101
                $message = 'The exchanged was successfully confirmed, since it matched an existing one.';
102
                event(new ExchangeWasConfirmed($exchange));
103
            }
104
105
            flash($message)->success();
106
        } catch (EnrollmentCannotBeExchangedException | ExchangeEnrollmentsOnDifferentCoursesException $e) {
107
            flash($e->getMessage())->error();
108
        }
109
110
        return redirect()->route('home');
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->route('home') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
111
    }
112
113
    /**
114
     * Remove the specified resource from storage.
115
     *
116
     * @param int $id
117
     *
118
     * @return \Illuminate\Http\Response
119
     */
120
    public function destroy($id)
121
    {
122
        DB::transaction(function () use ($id) {
123
            student()->requestedExchanges()->findOrFail($id)->delete();
124
        });
125
126
        flash('The shift exchange request was successfully deleted.')->success();
127
128
        return redirect()->back();
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back() returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
129
    }
130
}
131