Completed
Push — master ( 465a84...cacecb )
by Mario
03:48
created

ResourceController::getItemsCollection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
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->getItemsCollection();
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
            $data = [
96
                $model
97
            ];
98
99
            return $this->validSuccessJsonResponse($message, $data);
100
        }
101
102
        return redirect()->route($this->getRedirectionRoute())
103
                         ->with($this->successFlashMessageKey, $message);
104
    }
105
106
    /**
107
     * Display the specified resource.
108
     *
109
     * @param Request $request The request object.
110
     * @param string  $key     The model key.
111
     *
112
     * @return mixed
113
     */
114
    public function show(Request $request, $key)
115
    {
116
        $model = $this->findFirstByKey($key);
117
118
        if (!$model) {
119
            if ($request->wantsJson()) {
120
                return $this->validNotFoundJsonResponse();
121
            }
122
            abort(404);
123
        }
124
125
        if ($request->wantsJson()) {
126
            return response()->json($model, 200, [], JSON_PRETTY_PRINT);
127
        }
128
129
        $view = $this->getViewLocation(__FUNCTION__);
130
        $this->checkViewExists($view);
131
132
        return response()->view($view, compact('model'));
133
    }
134
135
    /**
136
     * Show the form for editing the specified resource.
137
     *
138
     * @param Request $request The request object.
139
     * @param string  $key     The model key.
140
     *
141
     * @return mixed
142
     */
143
    public function edit(Request $request, $key)
144
    {
145
        if ($request->wantsJson()) {
146
            return $this->validNotFoundJsonResponse();
147
        }
148
149
        $model = $this->findFirstByKey($key);
150
151
        if (!$model) {
152
            abort(404);
153
        }
154
155
        $view = $this->getViewLocation(__FUNCTION__);
156
        $this->checkViewExists($view);
157
158
        return response()->view($view, compact('model'));
159
    }
160
161
    /**
162
     * Update the specified resource in storage.
163
     *
164
     * @param Request $request The request object.
165
     * @param string  $key     The model key.
166
     *
167
     * @throws ResourceControllerException
168
     *
169
     * @return mixed
170
     */
171
    public function update(Request $request, $key)
172
    {
173
        $this->getFormRequestInstance();
174
175
        $model = $this->findFirstByKey($key);
176
177
        if (!$model) {
178
            if ($request->wantsJson()) {
179
                return $this->validNotFoundJsonResponse();
180
            }
181
            abort(404);
182
        }
183
184
        DB::beginTransaction();
185
       
186
        try { 
187
            $instance = $this->repository->update($model, $request->all());
188
            $model = $instance[1];
189
            $this->updateOrCreateRelations($request, $model);
190
            $this->uploadFiles($request, $model);
191
        } catch (\Exception $e) {
192
            DB::rollback();
193
194
            $message = $this->updateFailedMessage($key, $e->getMessage());
195
            throw new ResourceControllerException($message);
196
        }
197
198
        DB::commit();
199
200
        $message = $this->updateSuccessfulMessage($key);
201
202
        if ($request->wantsJson()) {
203
            $data = [
204
                $model
205
            ];
206
207
            return $this->validSuccessJsonResponse($message, $data);
208
        }
209
210
        return redirect()->route($this->getRedirectionRoute())
211
                         ->with($this->successFlashMessageKey, $message);
212
    }
213
214
    /**
215
     * Remove the specified resource from storage.
216
     *
217
     * @param Request $request The request object.
218
     * @param string  $key     The model key.
219
     *
220
     * @throws ResourceControllerException
221
     *
222
     * @return mixed
223
     */
224
    public function destroy(Request $request, $key)
225
    {
226
        $this->getFormRequestInstance();
227
228
        $model = $this->findFirstByKey($key);
229
230
        if (!$model) {
231
            if ($request->wantsJson()) {
232
                return $this->validNotFoundJsonResponse();
233
            }
234
            abort(404);
235
        }
236
237
        DB::beginTransaction();
238
239
        try {
240
            $this->repository->delete($model);
241
        } catch (\Exception $e) {
242
            DB::rollback();
243
244
            $message = $this->destroyFailedMessage($key, $e->getMessage());
245
            throw new ResourceControllerException($message);
246
        }
247
248
        DB::commit();
249
250
        $message = $this->destroySuccessfulMessage($key);
251
252
        if ($request->wantsJson()) {
253
            $data = [
254
                $model
255
            ];
256
257
            return $this->validSuccessJsonResponse($message, $data);
258
        }
259
260
        return redirect()->route($this->getRedirectionRoute())
261
                         ->with($this->infoFlashMessageKey, $message);
262
    }
263
264
    /**
265
     * Get items collection.
266
     *
267
     * @return \Illuminate\Database\Eloquent\Collection
268
     */
269
    public function getItemsCollection($orderBy = 'updated_at', $order = 'desc')
270
    {
271
        if ($this->useSoftDeletes) {
272
            return $this->repository->model->withTrashed()->orderBy($orderBy, $order)->get();
0 ignored issues
show
Bug introduced by
The property model does not exist on string.
Loading history...
273
        }
274
275
        return $this->repository->orderBy($orderBy, $order)->get();
276
    }
277
278
    /**
279
     * Get Paginator instance.
280
     *
281
     * @return \Illuminate\Pagination\LengthAwarePaginator
282
     */
283
    protected function getPaginatorInstance($orderBy = 'updated_at', $order = 'desc')
284
    {
285
        if ($this->useSoftDeletes) {
286
            return $this->repository->model->withTrashed()->orderBy($orderBy, $order)->paginate();
0 ignored issues
show
Bug introduced by
The property model does not exist on string.
Loading history...
287
        }
288
289
        return $this->repository->orderBy($orderBy, $order)->paginate();
290
    }
291
292
    /**
293
     * Find first by key.
294
     *
295
     * @param string $key The model key.
296
     *
297
     * @return Model|null
298
     */
299
    protected function findFirstByKey($key)
300
    {
301
        if ($this->useSoftDeletes) {
302
            return $this->repository
303
                ->withTrashed()
304
                ->where($this->repository->model->getRouteKeyName(), $key)
0 ignored issues
show
Bug introduced by
The property model does not exist on string.
Loading history...
305
                ->first();
306
        }
307
308
        return $this->repository
309
            ->findBy($this->repository->model->getRouteKeyName(), $key);
310
    }
311
}
312