Passed
Push — master ( 1b8711...f8bf6d )
by Mario
04:02
created

ResourceController::findFirstByKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace RafflesArgentina\ResourceController;
4
5
use DB;
6
7
use Illuminate\Http\Request;
8
9
use RafflesArgentina\ResourceController\Traits\WorksWithRelations;
10
use RafflesArgentina\ResourceController\Traits\WorksWithFileUploads;
11
use RafflesArgentina\ResourceController\Traits\FormatsResponseMessages;
12
use RafflesArgentina\ResourceController\Exceptions\ResourceControllerException;
13
14
class ResourceController extends AbstractResourceController
15
{
16
    use WorksWithRelations, WorksWithFileUploads, FormatsResponseMessages;
0 ignored issues
show
Bug introduced by
The trait RafflesArgentina\Resourc...ts\WorksWithFileUploads requires the property $files which is not provided by RafflesArgentina\Resourc...ller\ResourceController.
Loading history...
17
18
    /**
19
     * Display a listing of the resource.
20
     *
21
     * @param Request $request The request object.
22
     *
23
     * @return mixed
24
     */
25
    public function index(Request $request)
26
    {
27
        $this->getFormRequestInstance();
28
29
        $items = $this->getPaginatorInstance();
30
31
        if ($request->wantsJson()) {
32
            return response()->json($items, 200, [], JSON_PRETTY_PRINT);
33
        }
34
35
        $view = $this->getViewLocation(__FUNCTION__);
36
        $this->checkViewExists($view);
37
38
        return response()->view($view, compact('items'));
39
    }
40
41
    /**
42
     * Show the form for creating a new resource.
43
     *
44
     * @param Request $request The request object.
45
     *
46
     * @return mixed
47
     */
48
    public function create(Request $request)
49
    {
50
        if ($request->wantsJson()) {
51
            return $this->validNotFoundJsonResponse();
52
        }
53
54
        $model = new $this->repository->model;
0 ignored issues
show
Bug introduced by
The property model does not exist on string.
Loading history...
55
56
        $view = $this->getViewLocation(__FUNCTION__);
57
        $this->checkViewExists($view);
58
59
        return response()->view($view, compact('model'));
60
    }
61
62
    /**
63
     * Store a newly created resource in storage.
64
     *
65
     * @param Request $request The request object.
66
     *
67
     * @throws ResourceControllerException
68
     *
69
     * @return mixed
70
     */
71
    public function store(Request $request)
72
    {
73
        $this->getFormRequestInstance();
74
75
        DB::beginTransaction();
76
77
        try {
78
            $instance = $this->repository->create($request->all());
79
            $model = $instance[1];
80
            $number = $model->{$model->getRouteKeyName()};
81
            $this->updateOrCreateRelations($request, $model);
82
            $this->uploadFiles($request, $model);
83
        } catch (\Exception $e) {
84
            DB::rollback();
85
86
            $message = $this->storeFailedMessage($e->getMessage());
87
            throw new ResourceControllerException($message);
88
        }
89
90
        DB::commit();
91
92
        $message = $this->storeSuccessfulMessage($number);
93
94
        if ($request->wantsJson()) {
95
            return $this->validSuccessJsonResponse($message);
96
        }
97
98
        return redirect()->route($this->getRedirectionRoute())
99
                         ->with($this->successFlashMessageKey, $message);
100
    }
101
102
    /**
103
     * Display the specified resource.
104
     *
105
     * @param Request $request The request object.
106
     * @param string  $key     The model key.
107
     *
108
     * @return mixed
109
     */
110
    public function show(Request $request, $key)
111
    {
112
        $model = $this->findFirstByKey($key);
113
114
        if (!$model) {
115
            if ($request->wantsJson()) {
116
                return $this->validNotFoundJsonResponse();
117
            }
118
            abort(404);
119
        }
120
121
        if ($request->wantsJson()) {
122
            return response()->json($model, 200, [], JSON_PRETTY_PRINT);
123
        }
124
125
        $view = $this->getViewLocation(__FUNCTION__);
126
        $this->checkViewExists($view);
127
128
        return response()->view($view, compact('model'));
129
    }
130
131
    /**
132
     * Show the form for editing the specified resource.
133
     *
134
     * @param Request $request The request object.
135
     * @param string  $key     The model key.
136
     *
137
     * @return mixed
138
     */
139
    public function edit(Request $request, $key)
140
    {
141
        if ($request->wantsJson()) {
142
            return $this->validNotFoundJsonResponse();
143
        }
144
145
        $model = $this->findFirstByKey($key);
146
147
        if (!$model) {
148
            abort(404);
149
        }
150
151
        $view = $this->getViewLocation(__FUNCTION__);
152
        $this->checkViewExists($view);
153
154
        return response()->view($view, compact('model'));
155
    }
156
157
    /**
158
     * Update the specified resource in storage.
159
     *
160
     * @param Request $request The request object.
161
     * @param string  $key     The model key.
162
     *
163
     * @throws ResourceControllerException
164
     *
165
     * @return mixed
166
     */
167
    public function update(Request $request, $key)
168
    {
169
        $this->getFormRequestInstance();
170
171
        $model = $this->findFirstByKey($key);
172
173
        if (!$model) {
174
            if ($request->wantsJson()) {
175
                return $this->validNotFoundJsonResponse();
176
            }
177
            abort(404);
178
        }
179
180
        DB::beginTransaction();
181
       
182
        try { 
183
            $instance = $this->repository->update($model, $request->all());
184
            $model = $instance[1];
185
            $this->updateOrCreateRelations($request, $model);
186
            $this->uploadFiles($request, $model);
187
        } catch (\Exception $e) {
188
            DB::rollback();
189
190
            $message = $this->updateFailedMessage($key, $e->getMessage());
191
            throw new ResourceControllerException($message);
192
        }
193
194
        DB::commit();
195
196
        $message = $this->updateSuccessfulMessage($key);
197
198
        if ($request->wantsJson()) {
199
            return $this->validSuccessJsonResponse($message);
200
        }
201
202
        return redirect()->route($this->getRedirectionRoute())
203
                         ->with($this->successFlashMessageKey, $message);
204
    }
205
206
    /**
207
     * Remove the specified resource from storage.
208
     *
209
     * @param Request $request The request object.
210
     * @param string  $key     The model key.
211
     *
212
     * @throws ResourceControllerException
213
     *
214
     * @return mixed
215
     */
216
    public function destroy(Request $request, $key)
217
    {
218
        $this->getFormRequestInstance();
219
220
        $model = $this->findFirstByKey($key);
221
222
        if (!$model) {
223
            if ($request->wantsJson()) {
224
                return $this->validNotFoundJsonResponse();
225
            }
226
            abort(404);
227
        }
228
229
        DB::beginTransaction();
230
231
        try {
232
            $this->repository->delete($model);
233
        } catch (\Exception $e) {
234
            DB::rollback();
235
236
            $message = $this->destroyFailedMessage($key, $e->getMessage());
237
            throw new ResourceControllerException($message);
238
        }
239
240
        DB::commit();
241
242
        $message = $this->destroySuccessfulMessage($key);
243
244
        if ($request->wantsJson()) {
245
            return $this->validSuccessJsonResponse($message);
246
        }
247
248
        return redirect()->route($this->getRedirectionRoute())
249
                         ->with($this->infoFlashMessageKey, $message);
250
    }
251
252
    /**
253
     * Get Paginator instance.
254
     *
255
     * @return \Illuminate\Pagination\LengthAwarePaginator
256
     */
257
    protected function getPaginatorInstance()
258
    {
259
        if ($this->useSoftDeletes) {
260
            return $this->repository->model->withTrashed()->paginate();
0 ignored issues
show
Bug introduced by
The property model does not exist on string.
Loading history...
261
        }
262
263
        return $this->repository->paginate();
264
    }
265
266
    /**
267
     * Find first by key.
268
     *
269
     * @param string $key The model key.
270
     *
271
     * @return Model|null
272
     */
273
    protected function findFirstByKey($key)
274
    {
275
        if ($this->useSoftDeletes) {
276
            return $this->repository
277
                ->withTrashed()
278
                ->where($this->repository->model->getRouteKeyName(), $key)
0 ignored issues
show
Bug introduced by
The property model does not exist on string.
Loading history...
279
                ->first();
280
        }
281
282
        return $this->repository
283
            ->findBy($this->repository->model->getRouteKeyName(), $key);
284
    }
285
}
286