Completed
Pull Request — master (#82)
by Brandon
02:12
created

DeviceController::remove()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 6
ccs 0
cts 3
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 2
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
14
class DeviceController extends Controller
15
{
16
    /**
17
     * Create a new controller instance.
18
     *
19
     */
20
    public function __construct()
21
    {
22
        $this->middleware('auth');
23
        // TODO: Setup logging
24
        // $this->middleware('log')->only('index');
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
25
    }
26
27
    /**
28
     * Display index page and process dataTable ajax request.
29
     *
30
     * @param \App\DataTables\DevicesDataTable $dataTable
31
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
32
     */
33
    public function index(DevicesDataTable $dataTable)
34
    {
35
        return $dataTable->render('device.index');
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.create');
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
        return view('device.show', [ 'device' => $device ]);
58
    }
59
60
    /**
61
     * View the edit device page or the edit device modal
62
     *
63
     * @param  string  $id
64
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
65
     */
66
    public function edit($id)
67
    {
68
        //Get the device with the given id
69
        $device = Device::publicDashData()->findOrFail($id);
70
        
71
        //Get the devices location
72
        $location = $device->location()->select('id', 'name', 'site_id')->first();
73
        
74
        //Check if the selected device has a location
75
        if (!empty($location))
76
        {
77
            //Get all the sites except for the current site ordered by name
78
            $sites = Site::select('id', 'name')->orderBy('name', 'ASC')->get()->except($location->site->id);
79
            //Get all the locations except for the current location for the given site ordered by name
80
            $locations = $location->site->locations()->select('id', 'name', 'site_id')->orderBy('name', 'ASC')->get()->except($location->id);
81
            
82
            //Add the current site to the front of the collection of sites
83
            $sites->prepend($location->site);
84
            //Add the current location to the front of the collection of locations
85
            $locations->prepend($location);
86
        }
87
        else
88
        {
89
            //Set locations to null since there is no site or location attached to the selected device
90
            $locations = null;
91
            //Get all of the sites
92
            $sites = Site::all();
93
        }
94
        
95
        if (\Request::ajax())
96
            return response()->json([ 'device' => $device, 'locations' => $locations, 'sites' => $sites ]);
97
        else
98
            return view('device.edit', [ 'device' => $device, 'locations' => $locations, 'sites' => $sites ]);
99
    }
100
    
101
    /**
102
     * Get the locations with the given site id
103
     * Return null if the site does not have any locations
104
     *
105
     * @param  int $site_id
106
     * @return Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
107
     */
108
    public function locations($site_id)
109
    {
110
        $locations = Location::bySite($site_id)->select('id', 'name', 'site_id')->get();
111
        
112
        if ($locations->isEmpty())
113
            $locations = null;
114
    
115
        return response()->json($locations);
116
    }
117
    
118
    /**
119
     * Get the devices details
120
     * Return 404 error if the device is not found
121
     *
122
     * @param  int $id
123
     * @return Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
124
     */
125
    public function details($id)
126
    {
127
        $device = Device::publicDashData()->findOrFail($id);
128
        
129
        return response()->json($device);
130
    }
131
132
    /**
133
     * Update the given device.
134
     *
135
     * @param  EditDevice  $request
136
     * @param  string  $id
137
     * @return \Illuminate\Http\RedirectResponse
138
     */
139
    public function update(EditDevice $request, $id)
140
    {
141
        $device = Device::findOrFail($id);
142
        $location = null;
0 ignored issues
show
Unused Code introduced by
$location 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...
143
        $site = null;
0 ignored issues
show
Unused Code introduced by
$site 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...
144
145
        // TODO figure out way for unique location names for each specific site
146
        
147
        //Get the site id of the old or newly created site
148
        if (!empty($request->input('new_site_name')))
149
        {
150
            //Create a new site
151
            $siteName = $request->input('new_site_name');
152
            $site_id = Site::createSite($siteName)->id;
153
        }
154
        else
155
        {
156
            $site_id = $request->input('site');
157
        }
158
    
159
        //Verify the site with the given site id actually exists
160
        Site::findOrFail($site_id);
161
        
162
        //Get the location id of the old or newly created location
163
        if (!empty($request->input('new_location_name')))
164
        {
165
            //Create a new location
166
            $locationName = $request->input('new_location_name');
167
            $location_id = Location::createLocation($locationName, $site_id)->id;
168
        }
169
        else
170
        {
171
            $location_id = $request->input('location');
172
        }
173
        
174
        //Verify the location with the given location id actually exists
175
        Location::findOrFail($location_id);
176
        
177
        //Update the devices name and location_id
178
        $device->location_id = $location_id;
179
        $device->name = $request->input('name');
180
        $device->open_time = $request->input('open_time');
181
        $device->close_time = $request->input('close_time');
182
        $device->update_rate = $request->input('update_rate');
183
        $device->image_rate = $request->input('image_rate');
184
        $device->sensor_rate = $request->input('sensor_rate');
185
        $device->save();
186
187
        //Remove any unused sites or locations
188
        $this->RemoveUnusedSiteLoc();
189
    
190
        if (\Request::ajax())
191
            return response()->json("Success");
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json('Success'); (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...
192
        else
193
            return redirect('device');
194
    }
195
196
    /**
197
     * Deletes a device.
198
     *
199
     * @param  string  $id
200
     * @return \Illuminate\Http\RedirectResponse
201
     */
202
    public function destroy($id)
203
    {
204
        $device = Device::findOrFail($id);
205
206
        if ($device->trashed())
207
        {
208
            //If the device was already deleted then permanently delete it
209
            Device::destroy($id);
210
        }
211
        else
212
        {
213
            //Remove the location from the device
214
            $device->location_id = null;
215
            
216
            //Remove any unused sites or locations
217
            $this->RemoveUnusedSiteLoc();
218
            
219
            //Soft delete the user the first time
220
            $device->delete();
221
        }
222
223
        return redirect('device');
224
    }
225
    
226
    /**
227
     * Delete all unused sites and locations
228
     */
229
    private function RemoveUnusedSiteLoc()
230
    {
231
        //Delete all sites that don't have any devices
232
        //Locations connected to these sites will automatically be deleted by the database
233
        Site::doesntHave('devices')->delete();
234
    
235
        //Delete all locations that don't have any devices
236
        Location::doesntHave('devices')->delete();
237
    }
238
}
239