Completed
Pull Request — master (#107)
by
unknown
47:04 queued 15:58
created

DeviceController   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 208
Duplicated Lines 14.9 %

Coupling/Cohesion

Components 0
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 26
c 1
b 0
f 1
lcom 0
cbo 7
dl 31
loc 208
ccs 0
cts 85
cp 0
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A index() 0 5 1
A create() 0 4 1
A edit() 0 20 1
A show() 0 17 2
F update() 0 71 17
A destroy() 22 22 2
A restore() 9 9 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Http\Requests\EditDevice;
6
use Validator;
7
use Illuminate\Http\Request;
8
use App\DataTables\DevicesDataTable;
9
use Illuminate\Support\Facades\Route;
10
use App\Device;
11
use App\Site;
12
use App\Location;
13
use Charts;
14
15
class DeviceController extends Controller
16
{
17
    /**
18
     * Create a new controller instance.
19
     *
20
     */
21
    public function __construct()
22
    {
23
        $this->middleware('auth');
24
    }
25
26
    /**
27
     * Display index page and process dataTable ajax request.
28
     *
29
     * @param \App\DataTables\DevicesDataTable $dataTable
30
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
31
     */
32
    public function index(DevicesDataTable $dataTable)
33
    {
34
        $trashed = Device::onlyTrashed()->get();
35
        return $dataTable->render('device.index', compact('trashed'));
36
    }
37
38
    /**
39
     * Show create device page.
40
     *
41
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
42
     */
43
    public function create()
44
    {
45
        return view('device.index');
46
    }
47
48
    /**
49
     * Show the given device.
50
     *
51
     * @param  string  $id
52
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
53
     */
54
    public function show($id)
55
    {
56
        $device = Device::findOrFail($id);
57
        
58
        $charts = [];
59
        foreach ($device->sensors as $sensor) {
60
            $data = $sensor->last_month_daily_avg_data;
61
            $charts[$sensor->id] = Charts::create('line', 'highcharts')
62
                ->title($sensor->name)
63
                ->elementLabel($sensor->type)
64
                ->labels($data->pluck('date'))
65
                ->values($data->pluck('value'))
66
                ->responsive(true);
67
        }
68
        
69
        return view('device.show', [ 'device' => $device, 'charts' => $charts ]);
70
    }
71
72
    /**
73
     * View the edit device page
74
     *
75
     * @param  string  $id
76
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
77
     */
78
    public function edit($id)
79
    {
80
        //Get the device with the given id
81
        $device = Device::findOrFail($id);
82
        //Get the devices location
83
        $location = $device->location()->select('id', 'name', 'site_id')->first();
84
    
85
        //Get the site id and location id if they exist and if not assign 0
86
        $site_id = $location->site_id ?? 0;
87
        $location_id = $location->id ?? 0;
88
    
89
        //Get all sites with the current site first
90
        $sites = Site::select('id', 'name')->orderByRaw("id = ? DESC", $site_id)
91
            ->orderBy('name', 'ASC')->get();
92
        //Get all locations for the selected site with the selected location first
93
        $locations = Location::select('id', 'name')->where('site_id', '=', $sites[0]->id ?? 0)
94
            ->orderByRaw("id = ? DESC", $location_id)->orderBy('name', 'ASC')->get();
95
        
96
        return view('device.edit', [ 'device' => $device, 'locations' => $locations, 'sites' => $sites ]);
97
    }
98
99
    /**
100
     * Update the given device.
101
     *
102
     * @param  EditDevice  $request
103
     * @param  string  $id
104
     * @return \Illuminate\Http\RedirectResponse
105
     */
106
    public function update(EditDevice $request, $id)
107
    {
108
        $device = Device::findOrFail($id);
109
        $site_id = null;
0 ignored issues
show
Unused Code introduced by
$site_id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
110
        $location_id = null;
111
        
112
        //Get the site id and location id for the device if they are not null
113
        if ($request->input('new_site_name') != null || $request->input('site_id') != null)
114
        {
115
            //Get the site id of the old or newly created site
116
            if (!empty($request->input('new_site_name')))
117
            {
118
                //Create a new site
119
                $site = Site::create(['name' => $request->input('new_site_name')]);
120
                $site_id = $site->id;
121
            } else
122
                $site_id = $request->input('site_id');
123
    
124
            //Get the location id of the old or newly created location
125
            if (!empty($request->input('new_location_name')))
126
            {
127
                //Create a new location
128
                $location = Location::create(['name' => $request->input('new_location_name'), 'site_id' => $site_id]);
129
                $location_id = $location->id;
130
            } else
131
                $location_id = $request->input('location_id');
132
        }
133
        
134
        //Update the device
135
        if ($location_id != null)
136
            $device->location_id = $location_id;
137
        if ($request->input('name') != null)
138
            $device->name = $request->input('name');
139
        if ($request->input('open_time') != null)
140
            $device->open_time = $request->input('open_time');
141
        if ($request->input('close_time') != null)
142
            $device->close_time = $request->input('close_time');
143
        if ($request->input('update_rate') != null)
144
            $device->update_rate = $request->input('update_rate');
145
        if ($request->input('image_rate') != null)
146
            $device->image_rate = $request->input('image_rate');
147
        if ($request->input('sensor_rate') != null)
148
            $device->sensor_rate = $request->input('sensor_rate');
149
        //Check if the cover_command needs to be updated
150
        if ($request->input('command') != null)
151
        {
152
            //If device is currently opening, closing or in an error state don't update command
153
            if (!$device->isReadyForCommand())
154
                return response()->json("Device is currently in use.", 403);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...rrently in use.', 403); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by App\Http\Controllers\DeviceController::update of type Illuminate\Http\RedirectResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
155
    
156
            $command = $request->input('command');
157
            
158
            //If command is to unlock the device then check if the device should be open or closed based on the schedule
159
            if ($request->command === 'unlock')
0 ignored issues
show
Documentation introduced by
The property command does not exist on object<App\Http\Requests\EditDevice>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
160
            {
161
                if ($device->isDuringScheduleOpen())
162
                    $command =  'open';
163
                else
164
                    $command =  'close';
165
            }
166
            $device->cover_command = $command;
167
        }
168
        
169
        $device->save();
170
    
171
        if (\Request::ajax())
172
            return response()->json(['success' => 'Device updated successfully']);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...pdated successfully')); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by App\Http\Controllers\DeviceController::update of type Illuminate\Http\RedirectResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
173
        else
174
            return redirect()->route('device.show', $id)
1 ignored issue
show
Documentation introduced by
$id is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
175
                ->with('success', 'Device updated successfully');
176
    }
177
178
    /**
179
     * Deletes a device.
180
     *
181
     * @param  string  $id
182
     * @return \Illuminate\Http\RedirectResponse
183
     */
184 View Code Duplication
    public function destroy($id)
185
    {
186
        $device = Device::withTrashed()->findOrFail($id);
187
188
        if ($device->trashed())
189
        {
190
            //If the device was already deleted then permanently delete it
191
            $device->forceDelete($device->id);
192
        }
193
        else
194
        {
195
            //Remove the location from the device
196
            $device->location_id = null;
197
            $device->save();
198
            
199
            //Soft delete the device the first time
200
            $device->delete();
201
        }
202
203
        return redirect()->route('device.index')
204
            ->with('success','Device deleted successfully');
205
    }
206
    
207
    /**
208
     * Restores a device.
209
     *
210
     * @param  string  $id
211
     * @return \Illuminate\Http\RedirectResponse
212
     */
213 View Code Duplication
    public function restore($id)
214
    {
215
        $device = Device::onlyTrashed()->findOrFail($id);
216
217
        $device->restore();
218
        
219
        return redirect()->route('device.show', $device->id)
220
            ->with('success','Device restored successfully');
221
    }
222
}
223