ThingsController   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 361
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 192
dl 0
loc 361
rs 10
c 2
b 0
f 0
wmc 15

9 Methods

Rating   Name   Duplication   Size   Complexity  
A json() 0 29 3
A index() 0 35 1
A restore() 0 12 1
A miscErrorResponse() 0 5 1
A show() 0 42 1
A upsert() 0 45 3
A updateSettings() 0 21 1
A updateImage() 0 52 1
A delete() 0 20 3
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Item;
6
use App\Thing;
7
use Illuminate\Http\Request;
8
use Illuminate\Http\Response;
9
use Imagine\Imagick\Imagine;
10
11
class ThingsController extends Controller
12
{
13
14
    protected $thing;
15
16
    /**
17
     * Validation error messages.
18
     *
19
     * @static array
20
     */
21
    protected $messages = [
22
        'name.required' => 'Internt navn må fylles ut.',
23
        'name.unique' => 'Typen finnes allerede.',
24
25
        'loan_time.required' => 'Lånetid må fylles ut.',
26
27
        'properties.name_indefinite.nob.required' => 'Ubestemt form på bokmål må fylles ut.',
28
        'properties.name_definite.nob.required' => 'Bestemt form på bokmål må fylles ut.',
29
30
        'properties.name_indefinite.nno.required' => 'Ubestemt form på nynorsk må fylles ut.',
31
        'properties.name_definite.nno.required' => 'Bestemt form på nynorsk må fylles ut.',
32
33
        'properties.name_indefinite.eng.required' => 'Ubestemt form på engelsk må fylles ut.',
34
        'properties.name_definite.eng.required' => 'Bestemt form på engelsk må fylles ut.',
35
    ];
36
37
    /**
38
     * Display a listing of the resource.
39
     *
40
     * @param Request $request
41
     * @return Response
42
     */
43
    public function index(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

43
    public function index(/** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
44
    {
45
        $libraryId = \Auth::user()->id;
46
47
        $things = Thing::with('items', 'settings', 'items.loans')
48
            ->orderBy('properties->name->nob')
49
            ->get();
50
51
        $things = $things->map(function ($thing) use ($libraryId) {
52
            $all = $thing->items->whereNotIn('barcode', [null]);
53
            $avail = $all->filter(function (Item $item) {
54
                return is_null($item->activeLoan);
0 ignored issues
show
Bug introduced by
The property activeLoan does not seem to exist on App\Item. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
55
            });
56
            $mine = $all->where('library_id', $libraryId);
57
            $avail_mine = $avail->where('library_id', $libraryId);
58
59
            return [
60
                'type' => 'thing',
61
                'id' => $thing->id,
62
                'name' => $thing->name(),
63
                'library_settings' => $thing->library_settings,
64
                'properties' => $thing->properties,
65
                'image' => $thing->image,
66
                'loan_time' => $thing->loan_time,
67
68
                'items_total' => $all->count(),
69
                'items_mine' => $mine->count(),
70
71
                'avail_total' => $avail->count(),
72
                'avail_mine' => $avail_mine->count(),
73
            ];
74
        });
75
76
        return response()->view('things.index', [
77
            'things' => $things,
78
        ]);
79
    }
80
81
    /**
82
     * Display a listing of the resource.
83
     *
84
     * @param Request $request
85
     * @return Response
86
     */
87
    public function json(Request $request)
88
    {
89
        $libraryId = \Auth::user()->id;
0 ignored issues
show
Unused Code introduced by
The assignment to $libraryId is dead and can be removed.
Loading history...
90
91
        $things = Thing::with('settings');
92
93
        if ($request->input('withLoans')) {
94
            $things->with('items.loans');
95
        }
96
97
        $things = $things->orderBy('properties->name->nob')->get();
98
99
        if ($request->input('withoutBarcode')) {
100
            $things = $things->filter(function ($thing) {
101
                return $thing->library_settings->loans_without_barcode;
102
            })->values();
103
        }
104
105
        $things = $things->map(function ($thing) {
106
            return [
107
                'id' => $thing->id,
108
                'type' => 'thing',
109
                'name' => $thing->name(),
110
                'properties' => $thing->properties,
111
                'library_settings' => $thing->library_settings,
112
            ];
113
        });
114
115
        return response()->json($things);
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json($things) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
116
    }
117
118
    /**
119
     * Display the specified resource.
120
     *
121
     * @param Thing $thing
122
     * @return Response
123
     */
124
    public function show(Thing $thing)
125
    {
126
        $items = Item::with('thing', 'library')
127
            ->whereNotNull('barcode')
128
            ->where('thing_id', '=', $thing->id)
129
            ->orderBy('library_id')
130
            ->orderBy('barcode')
131
            ->get();
132
133
        $stats = [
134
            'loans' => [
135
                'total' => \DB::select(
136
                    "select count(*) as val from loans
137
                      where loans.item_id IN (select id from items where thing_id=:thing_id)",
138
                    ['thing_id' => $thing->id]
139
                )[0]->val,
140
                'this_year' => \DB::select(
141
                    "select count(*) as val from loans
142
                      where loans.item_id in (select id from items where thing_id=:thing_id)
143
                      and date_part('year', loans.created_at) = :year",
144
                    ['thing_id' => $thing->id, 'year' => date('Y')]
145
                )[0]->val,
146
                'last_year' => \DB::select(
147
                    "select count(*) as val from loans
148
                      where loans.item_id in (select id from items where thing_id=:thing_id)
149
                      and date_part('year', loans.created_at) = :year",
150
                    ['thing_id' => $thing->id, 'year' => date('Y') - 1]
151
                )[0]->val,
152
            ],
153
            'items' => [
154
                'lost' => \DB::select(
155
                    "select count(*) as val from items
156
                      where items.is_lost = :is_lost and thing_id=:thing_id",
157
                    ['thing_id' => $thing->id, 'is_lost' => true]
158
                )[0]->val,
159
            ]
160
        ];
161
162
        return response()->view('things.show', array(
163
            'thing' => $thing,
164
            'items' => $items,
165
            'stats' => $stats,
166
        ));
167
    }
168
169
    /**
170
     * Update or create the specified resource in storage.
171
     *
172
     * @param Thing $thing
173
     * @param Request $request
174
     * @return Response
175
     */
176
    public function upsert(Thing $thing, Request $request)
177
    {
178
        \Validator::make($request->all(), [
179
            //'name' => 'required|unique:things,name' . ($thing->id ? ',' . $thing->id : ''),
180
181
            'properties.name.nob' => 'required',
182
            'properties.name.nno' => 'required',
183
            'properties.name.eng' => 'required',
184
185
            'properties.name_indefinite.nob' => 'required',
186
            'properties.name_indefinite.nno' => 'required',
187
            'properties.name_indefinite.eng' => 'required',
188
            'properties.name_definite.nob' => 'required',
189
            'properties.name_definite.nno' => 'required',
190
            'properties.name_definite.eng' => 'required',
191
            'properties.loan_time' => 'required|numeric|min:1',
192
        ], $this->messages)->validate();
193
194
        $isNew = !$thing->exists;
195
196
        if ($isNew) {
197
            // The frontend will redirect to update the url, so flash a status message to the new page.
198
            \Session::flash('status', 'Tingen ble lagret.');
199
        }
200
201
        $thing->properties = $request->input('properties');
202
        $thing->save();
203
204
        if ($isNew) {
205
            \Log::info(sprintf(
206
                'Opprettet tingen <a href="%s">%s</a>.',
207
                action('ThingsController@show', $thing->id),
208
                $thing->name()
209
            ));
210
        } else {
211
            \Log::info(sprintf(
212
                'Oppdaterte tingen <a href="%s">%s</a>.',
213
                action('ThingsController@show', $thing->id),
214
                $thing->name()
215
            ));
216
        }
217
218
        return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json(....', 'thing' => $thing)) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
219
            'status' => 'Tingen «' . $thing->name() . '» ble lagret.',
220
            'thing' => $thing,
221
        ]);
222
    }
223
224
    /**
225
     * Update thing settings for my library.
226
     *
227
     * @param Thing $thing
228
     * @return Response
229
     */
230
    public function updateSettings(Thing $thing, Request $request)
231
    {
232
        \Validator::make($request->all(), [
233
            'loans_without_barcode' => ['required', 'boolean'],
234
            'reminders' => ['required', 'boolean'],
235
        ])->validate();
236
237
        $settings = $thing->library_settings;
238
        $settings->loans_without_barcode = (boolean) $request->input('loans_without_barcode');
0 ignored issues
show
Bug introduced by
The property loans_without_barcode does not seem to exist on App\ThingSettings. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
239
        $settings->reminders = (boolean) $request->input('reminders');
0 ignored issues
show
Bug introduced by
The property reminders does not seem to exist on App\ThingSettings. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
240
        $settings->save();
241
242
        \Log::info(sprintf(
243
            'Oppdaterte innstillinger for tingen <a href="%s">%s</a>.',
244
            action('ThingsController@show', $thing->id),
245
            $thing->name()
246
        ));
247
248
        return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json(...ettings' => $settings)) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
249
            'status' => 'ok',
250
            'library_settings' => $settings,
251
        ]);
252
    }
253
254
    /**
255
     * Update image
256
     *
257
     * @param Thing $thing
258
     * @param Request $request
259
     * @param Imagine $imagine
260
     * @return Response
261
     * @throws \Illuminate\Validation\ValidationException
262
     */
263
    public function updateImage(Thing $thing, Request $request, Imagine $imagine)
264
    {
265
        $this->validate($request, [
266
            'thingimage' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
267
        ]);
268
269
        $file = $request->file('thingimage');
270
        $filename = $file->storePublicly('public');
271
        $filename = substr($filename, strpos($filename, '/') + 1);
0 ignored issues
show
Bug introduced by
It seems like $filename can also be of type false; however, parameter $string of substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

271
        $filename = substr(/** @scrutinizer ignore-type */ $filename, strpos($filename, '/') + 1);
Loading history...
Bug introduced by
It seems like $filename can also be of type false; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

271
        $filename = substr($filename, strpos(/** @scrutinizer ignore-type */ $filename, '/') + 1);
Loading history...
272
        $filename_t = $filename . '.thumb.jpg';
273
274
        $fullpath  = storage_path("app/public/$filename");
275
        $fullpath_t = storage_path("app/public/$filename_t");
276
277
        $imagine->open($fullpath)
278
            ->thumbnail(
279
                new \Imagine\Image\Box(
280
                    config('bibrex.thumbnail_dimensions.width'),
281
                    config('bibrex.thumbnail_dimensions.height')
282
                ),
283
                \Imagine\Image\ImageInterface::THUMBNAIL_INSET
284
            )
285
            ->save($fullpath_t);
286
287
        list($width, $height) = getimagesize($fullpath);
288
        list($width_t, $height_t) = getimagesize($fullpath_t);
289
290
        $thing->image = [
291
            'full' => [
292
                'name' => $filename,
293
                'size' => filesize($fullpath),
294
                'width' => $width,
295
                'height' => $height,
296
            ],
297
            'thumb' => [
298
                'name' => $filename_t,
299
                'size' => filesize($fullpath_t),
300
                'width' => $width_t,
301
                'height' => $height_t,
302
            ],
303
        ];
304
        $thing->save();
305
306
        \Log::info(sprintf(
307
            'Oppdaterte bilde for tingen <a href="%s">%s</a>.',
308
            action('ThingsController@show', $thing->id),
309
            $thing->name()
310
        ));
311
312
        return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json(....', 'thing' => $thing)) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
313
            'status' => 'Bildet ble lagret.',
314
            'thing' => $thing,
315
        ]);
316
    }
317
318
    public function miscErrorResponse($msg)
319
    {
320
        return response()->json([
321
            'errors' => ['misc' => [$msg]],
322
        ], 422);
323
    }
324
325
    /**
326
     * Remove the specified resource from storage.
327
     *
328
     * @param Thing $thing
329
     * @return Response
330
     */
331
    public function delete(Thing $thing)
332
    {
333
        if ($thing->items()->whereNotNull('barcode')->count() != 0) {
334
            return $this->miscErrorResponse('Kan ikke slette ting med eksemplarer.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->miscErrorR...ting med eksemplarer.') returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
335
        }
336
337
        if (count($thing->activeLoans()) != 0) {
338
            return $this->miscErrorResponse('Kan ikke slette ting med aktive lån.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->miscErrorR...ting med aktive lån.') returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
339
        }
340
341
        \Log::info(sprintf(
342
            'Slettet tingen <a href="%s">%s</a>.',
343
            action('ThingsController@show', $thing->id),
344
            $thing->name()
345
        ));
346
        $thing->delete();
347
348
        return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json(....', 'thing' => $thing)) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
349
            'status' => 'Tingen «' . $thing->name() . '» ble sletta.',
350
            'thing' => $thing,
351
        ]);
352
    }
353
354
    /**
355
     * Restore the specified resource.
356
     *
357
     * @param Thing $thing
358
     * @return Response
359
     */
360
    public function restore(Thing $thing)
361
    {
362
        $thing->restore();
363
        \Log::info(sprintf(
364
            'Gjenopprettet tingen <a href="%s">%s</a>.',
365
            action('ThingsController@show', $thing->id),
366
            $thing->name()
367
        ));
368
369
        return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json(....', 'thing' => $thing)) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
370
            'status' => 'Tingen «' . $thing->name() . '» ble gjenopprettet.',
371
            'thing' => $thing,
372
        ]);
373
    }
374
}
375