Switchable::switchOff()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
namespace SoareCostin\LaravelToggleSwitchFields\Traits;
4
5
trait Switchable
6
{
7
    protected function switchableFields()
8
    {
9
        return [
10
            config('toggle_switch_fields.default_field'),
11
        ];
12
    }
13
14
    /**
15
     * Switch the current resource on.
16
     *
17
     * @param  \Illuminate\Database\Eloquent\Model  $entity
18
     * @param  string $fieldName
19
     * @return
20
     */
21
    public function switchOn($entity, $fieldName)
22
    {
23
        if (! in_array($fieldName, $this->switchableFields())) {
24
            abort(404);
25
        }
26
27
        $success = $entity->update([$fieldName => 1]);
28
29
        return response()->json([
30
            'ok' => $success,
31
        ]);
32
    }
33
34
    /**
35
     * Switch the current resource off.
36
     *
37
     * @param  \Illuminate\Database\Eloquent\Model  $entity
38
     * @param  string $fieldName
39
     * @return
40
     */
41
    public function switchOff($entity, $fieldName)
42
    {
43
        if (! in_array($fieldName, $this->switchableFields())) {
44
            abort(404);
45
        }
46
47
        $success = $entity->update([$fieldName => 0]);
48
49
        return response()->json([
50
            'ok' => $success,
51
        ]);
52
    }
53
}
54