Completed
Pull Request — master (#87)
by Brandon
02:20
created

DeviceController::restore()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 9
loc 9
ccs 0
cts 5
cp 0
rs 9.6666
cc 1
eloc 5
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
        $trashed = Device::onlyTrashed()->get();
36
        return $dataTable->render('device.index', compact('trashed'));
37
    }
38
39
    /**
40
     * Show create device page.
41
     *
42
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
43
     */
44
    public function create()
45
    {
46
        return view('device.create');
47
    }
48
49
    /**
50
     * Show the given device.
51
     *
52
     * @param  string  $id
53
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
54
     */
55
    public function show($id)
56
    {
57
        $device = Device::findOrFail($id);
58
        return view('device.show', [ 'device' => $device ]);
59
    }
60
61
    /**
62
     * View the edit device page or the edit device modal
63
     *
64
     * @param  string  $id
65
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
66
     */
67
    public function edit($id)
68
    {
69
        //Get the device with the given id
70
        $device = Device::publicDashData()->findOrFail($id);
71
        
72
        //Get the devices location
73
        $location = $device->location()->select('id', 'name', 'site_id')->first();
74
        
75
        //Check if the selected device has a location
76
        if (!empty($location))
77
        {
78
            //Get all the sites except for the current site ordered by name
79
            $sites = Site::select('id', 'name')->orderBy('name', 'ASC')->get()->except($location->site->id);
80
            //Get all the locations except for the current location for the given site ordered by name
81
            $locations = $location->site->locations()->select('id', 'name', 'site_id')->orderBy('name', 'ASC')->get()->except($location->id);
82
            
83
            //Add the current site to the front of the collection of sites
84
            $sites->prepend($location->site);
85
            //Add the current location to the front of the collection of locations
86
            $locations->prepend($location);
87
        }
88
        else
89
        {
90
            //Set locations to null since there is no site or location attached to the selected device
91
            $locations = null;
92
            //Get all of the sites
93
            $sites = Site::all();
94
        }
95
        
96
        if (\Request::ajax())
97
            return response()->json([ 'device' => $device, 'locations' => $locations, 'sites' => $sites ]);
98
        else
99
            return view('device.edit', [ 'device' => $device, 'locations' => $locations, 'sites' => $sites ]);
100
    }
101
    
102
    /**
103
     * Get the locations with the given site id
104
     * Return null if the site does not have any locations
105
     *
106
     * @param  int $site_id
107
     * @return Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
108
     */
109
    public function locations($site_id)
110
    {
111
        $locations = Location::bySite($site_id)->select('id', 'name', 'site_id')->get();
112
        
113
        if ($locations->isEmpty())
114
            $locations = null;
115
    
116
        return response()->json($locations);
117
    }
118
    
119
    /**
120
     * Get the devices details
121
     * Return 404 error if the device is not found
122
     *
123
     * @param  int $id
124
     * @return Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
125
     */
126
    public function details($id)
127
    {
128
        $device = Device::publicDashData()->findOrFail($id);
129
        
130
        return response()->json($device);
131
    }
132
133
    /**
134
     * Update the given device.
135
     *
136
     * @param  EditDevice  $request
137
     * @param  string  $id
138
     * @return \Illuminate\Http\RedirectResponse
139
     */
140
    public function update(EditDevice $request, $id)
141
    {
142
        $device = Device::findOrFail($id);
143
        $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...
144
        $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...
145
146
        // TODO figure out way for unique location names for each specific site
147
        
148
        //Get the site id of the old or newly created site
149
        if (!empty($request->input('new_site_name')))
150
        {
151
            //Create a new site
152
            $siteName = $request->input('new_site_name');
153
            $site_id = Site::createSite($siteName)->id;
154
        }
155
        else
156
        {
157
            $site_id = $request->input('site');
158
        }
159
    
160
        //Verify the site with the given site id actually exists
161
        Site::findOrFail($site_id);
162
        
163
        //Get the location id of the old or newly created location
164
        if (!empty($request->input('new_location_name')))
165
        {
166
            //Create a new location
167
            $locationName = $request->input('new_location_name');
168
            $location_id = Location::createLocation($locationName, $site_id)->id;
169
        }
170
        else
171
        {
172
            $location_id = $request->input('location');
173
        }
174
        
175
        //Verify the location with the given location id actually exists
176
        Location::findOrFail($location_id);
177
        
178
        //Update the devices name and location_id
179
        $device->location_id = $location_id;
180
        $device->name = $request->input('name');
181
        $device->open_time = $request->input('open_time');
182
        $device->close_time = $request->input('close_time');
183
        $device->update_rate = $request->input('update_rate');
184
        $device->image_rate = $request->input('image_rate');
185
        $device->sensor_rate = $request->input('sensor_rate');
186
        $device->save();
187
188
        //Remove any unused sites or locations
189
        $this->RemoveUnusedSiteLoc();
0 ignored issues
show
Documentation Bug introduced by
The method RemoveUnusedSiteLoc does not exist on object<App\Http\Controllers\DeviceController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
190
    
191
        if (\Request::ajax())
192
            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...
193
        else
194
            return redirect('device');
195
    }
196
197
    /**
198
     * Deletes a device.
199
     *
200
     * @param  string  $id
201
     * @return \Illuminate\Http\RedirectResponse
202
     */
203 View Code Duplication
    public function destroy($id)
204
    {
205
        $device = Device::withTrashed()->findOrFail($id);
206
207
        if ($device->trashed()) {
208
            //If the device was already deleted then permanently delete it
209
            $device->forceDelete($device->id);
210
        } else {
211
            //Soft delete the device the first time
212
            $device->delete();
213
        }
214
215
        return redirect()->route('device.index')
216
            ->with('success','Device deleted successfully');
217
    }
218
    
219
    /**
220
     * Restores a device.
221
     *
222
     * @param  string  $id
223
     * @return \Illuminate\Http\RedirectResponse
224
     */
225 View Code Duplication
    public function restore($id)
226
    {
227
        $device = Device::onlyTrashed()->findOrFail($id);
228
229
        $device->restore();
230
        
231
        return redirect()->route('device.show', $device->id)
232
            ->with('success','Device restored successfully');
233
    }
234
}
235