GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( 2dec65...536865 )
by Dane
02:51
created

ServersController   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 503
Duplicated Lines 20.87 %

Coupling/Cohesion

Components 0
Dependencies 15

Importance

Changes 0
Metric Value
wmc 53
lcom 0
cbo 15
dl 105
loc 503
rs 6.8582
c 0
b 0
f 0

22 Methods

Rating   Name   Duplication   Size   Complexity  
A index() 0 12 2
A new() 0 16 1
A create() 18 18 4
A newServerNodes() 0 23 1
A viewIndex() 0 4 1
A viewDetails() 0 6 1
A viewBuild() 0 10 1
A viewStartup() 0 11 1
A viewDatabase() 0 9 1
A viewManage() 0 4 1
A viewDelete() 0 4 1
A setDetails() 0 20 4
A setContainer() 19 19 4
A toggleInstall() 16 16 3
A rebuildContainer() 0 18 2
B manageSuspension() 0 24 4
B updateBuild() 22 22 4
A delete() 0 21 4
B saveStartup() 0 22 5
A newDatabase() 0 19 4
A resetDatabasePassword() 15 15 2
A deleteDatabase() 15 15 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ServersController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ServersController, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Pterodactyl - Panel
4
 * Copyright (c) 2015 - 2017 Dane Everitt <[email protected]>.
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in all
14
 * copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
 * SOFTWARE.
23
 */
24
25
namespace Pterodactyl\Http\Controllers\Admin;
26
27
use Log;
28
use Alert;
29
use Javascript;
30
use Pterodactyl\Models;
31
use Illuminate\Http\Request;
32
use GuzzleHttp\Exception\TransferException;
33
use Pterodactyl\Exceptions\DisplayException;
34
use Pterodactyl\Http\Controllers\Controller;
35
use Pterodactyl\Repositories\ServerRepository;
36
use Pterodactyl\Repositories\DatabaseRepository;
37
use Pterodactyl\Exceptions\DisplayValidationException;
38
39
class ServersController extends Controller
40
{
41
    /**
42
     * Display the index page with all servers currently on the system.
43
     *
44
     * @param  \Illuminate\Http\Request  $request
45
     * @return \Illuminate\View\View
46
     */
47
    public function index(Request $request)
48
    {
49
        $servers = Models\Server::with('node', 'user', 'allocation');
50
51
        if (! is_null($request->input('query'))) {
52
            $servers->search($request->input('query'));
53
        }
54
55
        return view('admin.servers.index', [
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.inde...ervers->paginate(25))); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 55 which is incompatible with the return type documented by Pterodactyl\Http\Control...erversController::index of type Illuminate\View\View.
Loading history...
56
            'servers' => $servers->paginate(25),
0 ignored issues
show
Bug introduced by
The method paginate does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
57
        ]);
58
    }
59
60
    /**
61
     * Display create new server page.
62
     *
63
     * @param  \Illuminate\Http\Request  $request
64
     * @return \Illuminate\View\View
65
     */
66
    public function new(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
67
    {
68
        $services = Models\Service::with('options.packs', 'options.variables')->get();
0 ignored issues
show
Bug introduced by
The method get does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
69
        Javascript::put([
70
            'services' => $services->map(function ($item) {
71
                return array_merge($item->toArray(), [
72
                    'options' => $item->options->keyBy('id')->toArray(),
73
                ]);
74
            })->keyBy('id'),
75
        ]);
76
77
        return view('admin.servers.new', [
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.new'...rvices' => $services)); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 77 which is incompatible with the return type documented by Pterodactyl\Http\Control...\ServersController::new of type Illuminate\View\View.
Loading history...
78
            'locations' => Models\Location::all(),
79
            'services' => $services,
80
        ]);
81
    }
82
83
    /**
84
     * Create server controller method.
85
     *
86
     * @param  \Illuminate\Http\Request  $request
87
     * @return \Illuminate\Response\RedirectResponse
88
     */
89 View Code Duplication
    public function create(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
    {
91
        try {
92
            $repo = new ServerRepository;
93
            $server = $repo->create($request->except('_token'));
94
95
            return redirect()->route('admin.servers.view', $server->id);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Pterodactyl\Models\Server>. 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...
96
        } catch (DisplayValidationException $ex) {
97
            return redirect()->route('admin.servers.new')->withErrors(json_decode($ex->getMessage()))->withInput();
98
        } catch (DisplayException $ex) {
99
            Alert::danger($ex->getMessage())->flash();
100
        } catch (\Exception $ex) {
101
            Log::error($ex);
102
            Alert::danger('An unhandled exception occured while attemping to add this server. Please try again.')->flash();
103
        }
104
105
        return redirect()->route('admin.servers.new')->withInput();
106
    }
107
108
    /**
109
     * Returns a tree of all avaliable nodes in a given location.
110
     *
111
     * @param  \Illuminate\Http\Request  $request
112
     * @return array
113
     */
114
    public function newServerNodes(Request $request)
115
    {
116
        $nodes = Models\Node::with('allocations')->where('location_id', $request->input('location'))->get();
0 ignored issues
show
Bug introduced by
The method where does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
117
118
        return $nodes->map(function ($item) {
119
            $filtered = $item->allocations->where('server_id', null)->map(function ($map) {
120
                return collect($map)->only(['id', 'ip', 'port']);
121
            });
122
123
            $item->ports = $filtered->map(function ($map) use ($item) {
124
                return [
125
                    'id' => $map['id'],
126
                    'text' => $map['ip'] . ':' . $map['port'],
127
                ];
128
            })->values();
129
130
            return [
131
                'id' => $item->id,
132
                'text' => $item->name,
133
                'allocations' => $item->ports,
134
            ];
135
        })->values();
136
    }
137
138
    /**
139
     * Display the index when viewing a specific server.
140
     *
141
     * @param  \Illuminate\Http\Request  $request
142
     * @param  int                       $id
143
     * @return \Illuminate\View\View
144
     */
145
    public function viewIndex(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
146
    {
147
        return view('admin.servers.view.index', ['server' => Models\Server::findOrFail($id)]);
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.view...ver::findOrFail($id))); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 147 which is incompatible with the return type documented by Pterodactyl\Http\Control...rsController::viewIndex of type Illuminate\View\View.
Loading history...
148
    }
149
150
    /**
151
     * Display the details page when viewing a specific server.
152
     *
153
     * @param  \Illuminate\Http\Request  $request
154
     * @param  int                       $id
155
     * @return \Illuminate\View\View
156
     */
157
    public function viewDetails(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
158
    {
159
        $server = Models\Server::where('installed', 1)->findOrFail($id);
160
161
        return view('admin.servers.view.details', ['server' => $server]);
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.view...('server' => $server)); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 161 which is incompatible with the return type documented by Pterodactyl\Http\Control...Controller::viewDetails of type Illuminate\View\View.
Loading history...
162
    }
163
164
    /**
165
     * Display the build details page when viewing a specific server.
166
     *
167
     * @param  \Illuminate\Http\Request  $request
168
     * @param  int                       $id
169
     * @return \Illuminate\View\View
170
     */
171
    public function viewBuild(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
172
    {
173
        $server = Models\Server::where('installed', 1)->with('node.allocations')->findOrFail($id);
174
175
        return view('admin.servers.view.build', [
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.view...port')->sortBy('ip'))); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 175 which is incompatible with the return type documented by Pterodactyl\Http\Control...rsController::viewBuild of type Illuminate\View\View.
Loading history...
176
            'server' => $server,
177
            'assigned' => $server->node->allocations->where('server_id', $server->id)->sortBy('port')->sortBy('ip'),
178
            'unassigned' => $server->node->allocations->where('server_id', null)->sortBy('port')->sortBy('ip'),
179
        ]);
180
    }
181
182
    /**
183
     * Display startup configuration page for a server.
184
     *
185
     * @param  \Illuminate\Http\Request  $request
186
     * @param  int                       $id
187
     * @return \Illuminate\View\View
188
     */
189
    public function viewStartup(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
190
    {
191
        $server = Models\Server::where('installed', 1)->with('option.variables', 'variables')->findOrFail($id);
192
        $server->option->variables->transform(function ($item, $key) use ($server) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

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

Loading history...
193
            $item->server_value = $server->variables->where('variable_id', $item->id)->pluck('variable_value')->first();
194
195
            return $item;
196
        });
197
198
        return view('admin.servers.view.startup', ['server' => $server]);
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.view...('server' => $server)); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 198 which is incompatible with the return type documented by Pterodactyl\Http\Control...Controller::viewStartup of type Illuminate\View\View.
Loading history...
199
    }
200
201
    /**
202
     * Display the database management page for a specific server.
203
     *
204
     * @param  \Illuminate\Http\Request $request
205
     * @param  int                      $id
206
     * @return \Illuminate\View\View
207
     */
208
    public function viewDatabase(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
209
    {
210
        $server = Models\Server::where('installed', 1)->with('databases.host')->findOrFail($id);
211
212
        return view('admin.servers.view.database', [
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.view... 'server' => $server)); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 212 which is incompatible with the return type documented by Pterodactyl\Http\Control...ontroller::viewDatabase of type Illuminate\View\View.
Loading history...
213
            'hosts' => Models\DatabaseHost::all(),
214
            'server' => $server,
215
        ]);
216
    }
217
218
    /**
219
     * Display the management page when viewing a specific server.
220
     *
221
     * @param  \Illuminate\Http\Request  $request
222
     * @param  int                       $id
223
     * @return \Illuminate\View\View
224
     */
225
    public function viewManage(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
226
    {
227
        return view('admin.servers.view.manage', ['server' => Models\Server::findOrFail($id)]);
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.view...ver::findOrFail($id))); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 227 which is incompatible with the return type documented by Pterodactyl\Http\Control...sController::viewManage of type Illuminate\View\View.
Loading history...
228
    }
229
230
    /**
231
     * Display the deletion page for a server.
232
     *
233
     * @param  \Illuminate\Http\Request  $request
234
     * @param  int                       $id
235
     * @return \Illuminate\View\View
236
     */
237
    public function viewDelete(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
238
    {
239
        return view('admin.servers.view.delete', ['server' => Models\Server::findOrFail($id)]);
0 ignored issues
show
Bug Compatibility introduced by
The expression view('admin.servers.view...ver::findOrFail($id))); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 239 which is incompatible with the return type documented by Pterodactyl\Http\Control...sController::viewDelete of type Illuminate\View\View.
Loading history...
240
    }
241
242
    /**
243
     * Update the details for a server.
244
     *
245
     * @param  \Illuminate\Http\Request  $request
246
     * @param  int                       $id
247
     * @return \Illuminate\Http\RedirectResponse
248
     */
249
    public function setDetails(Request $request, $id)
250
    {
251
        $repo = new ServerRepository;
252
        try {
253
            $repo->updateDetails($id, $request->intersect([
254
                'owner_id', 'name', 'reset_token',
255
            ]));
256
257
            Alert::success('Server details were successfully updated.')->flash();
258
        } catch (DisplayValidationException $ex) {
259
            return redirect()->route('admin.servers.view.details', $id)->withErrors(json_decode($ex->getMessage()))->withInput();
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
260
        } catch (DisplayException $ex) {
261
            Alert::danger($ex->getMessage())->flash();
262
        } catch (\Exception $ex) {
263
            Log::error($ex);
264
            Alert::danger('An unhandled exception occured while attemping to update this server. This error has been logged.')->flash();
265
        }
266
267
        return redirect()->route('admin.servers.view.details', $id)->withInput();
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
268
    }
269
270
    /**
271
     * Set the new docker container for a server.
272
     *
273
     * @param  \Illuminate\Http\Request  $request
274
     * @param  int                       $id
275
     * @return \Illuminate\Http\RedirectResponse
276
     */
277 View Code Duplication
    public function setContainer(Request $request, $id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
278
    {
279
        $repo = new ServerRepository;
280
281
        try {
282
            $repo->updateContainer($id, $request->intersect('docker_image'));
283
284
            Alert::success('Successfully updated this server\'s docker image.')->flash();
285
        } catch (DisplayValidationException $ex) {
286
            return redirect()->route('admin.servers.view.details', $id)->withErrors(json_decode($ex->getMessage()))->withInput();
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
287
        } catch (DisplayException $ex) {
288
            Alert::danger($ex->getMessage())->flash();
289
        } catch (\Exception $ex) {
290
            Log::error($ex);
291
            Alert::danger('An unhandled exception occured while attemping to update this server\'s docker image. This error has been logged.')->flash();
292
        }
293
294
        return redirect()->route('admin.servers.view.details', $id);
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
295
    }
296
297
    /**
298
     * Toggles the install status for a server.
299
     *
300
     * @param  \Illuminate\Http\Request  $request
301
     * @param  int                       $id
302
     * @return \Illuminate\Http\RedirectResponse
303
     */
304 View Code Duplication
    public function toggleInstall(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
305
    {
306
        $repo = new ServerRepository;
307
        try {
308
            $repo->toggleInstall($id);
309
310
            Alert::success('Server install status was successfully toggled.')->flash();
311
        } catch (DisplayException $ex) {
312
            Alert::danger($ex->getMessage())->flash();
313
        } catch (\Exception $ex) {
314
            Log::error($ex);
315
            Alert::danger('An unhandled exception occured while attemping to toggle this servers status. This error has been logged.')->flash();
316
        }
317
318
        return redirect()->route('admin.servers.view.manage', $id);
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
319
    }
320
321
    /**
322
     * Setup a server to have a container rebuild.
323
     *
324
     * @param  \Illuminate\Http\Request  $request
325
     * @param  int                       $id
326
     * @return \Illuminate\Http\RedirectResponse
327
     */
328
    public function rebuildContainer(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
329
    {
330
        $server = Models\Server::with('node')->findOrFail($id);
0 ignored issues
show
Bug introduced by
The method findOrFail does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
331
332
        try {
333
            $server->node->guzzleClient([
334
                'X-Access-Server' => $server->uuid,
335
                'X-Access-Token' => $server->node->daemonSecret,
336
            ])->request('POST', '/server/rebuild');
337
338
            Alert::success('A rebuild has been queued successfully. It will run the next time this server is booted.')->flash();
339
        } catch (TransferException $ex) {
340
            Log::warning($ex);
341
            Alert::danger('A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.')->flash();
342
        }
343
344
        return redirect()->route('admin.servers.view.manage', $id);
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
345
    }
346
347
    /**
348
     * Manage the suspension status for a server.
349
     *
350
     * @param  \Illuminate\Http\Request  $request
351
     * @param  int                       $id
352
     * @return \Illuminate\Http\RedirectResponse
353
     */
354
    public function manageSuspension(Request $request, $id)
355
    {
356
        $repo = new ServerRepository;
357
        $action = $request->input('action');
358
359
        if (! in_array($action, ['suspend', 'unsuspend'])) {
360
            Alert::danger('Invalid action was passed to function.')->flash();
361
362
            return redirect()->route('admin.servers.view.manage', $id);
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
363
        }
364
365
        try {
366
            $repo->$action($id);
367
368
            Alert::success('Server has been ' . $action . 'ed.');
369
        } catch (DisplayException $ex) {
370
            Alert::danger($ex->getMessage())->flash();
371
        } catch (\Exception $ex) {
372
            Log::error($ex);
373
            Alert::danger('An unhandled exception occured while attemping to ' . $action . ' this server. This error has been logged.')->flash();
374
        }
375
376
        return redirect()->route('admin.servers.view.manage', $id);
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
377
    }
378
379
    /**
380
     * Update the build configuration for a server.
381
     *
382
     * @param  \Illuminate\Http\Request  $request
383
     * @param  int                       $id
384
     * @return \Illuminate\Http\RedirectResponse
385
     */
386 View Code Duplication
    public function updateBuild(Request $request, $id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
387
    {
388
        $repo = new ServerRepository;
389
390
        try {
391
            $repo->changeBuild($id, $request->intersect([
392
                'allocation_id', 'add_allocations', 'remove_allocations',
393
                'memory', 'swap', 'io', 'cpu',
394
            ]));
395
396
            Alert::success('Server details were successfully updated.')->flash();
397
        } catch (DisplayValidationException $ex) {
398
            return redirect()->route('admin.servers.view.build', $id)->withErrors(json_decode($ex->getMessage()))->withInput();
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
399
        } catch (DisplayException $ex) {
400
            Alert::danger($ex->getMessage())->flash();
401
        } catch (\Exception $ex) {
402
            Log::error($ex);
403
            Alert::danger('An unhandled exception occured while attemping to add this server. This error has been logged.')->flash();
404
        }
405
406
        return redirect()->route('admin.servers.view.build', $id);
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
407
    }
408
409
    /**
410
     * Start the server deletion process.
411
     *
412
     * @param  \Illuminate\Http\Request  $request
413
     * @param  int                       $id
414
     * @return \Illuminate\Http\RedirectResponse
415
     */
416
    public function delete(Request $request, $id)
417
    {
418
        $repo = new ServerRepository;
419
420
        try {
421
            $repo->delete($id, $request->has('force_delete'));
422
            Alert::success('Server was successfully deleted from the system.')->flash();
423
424
            return redirect()->route('admin.servers');
425
        } catch (DisplayException $ex) {
426
            Alert::danger($ex->getMessage())->flash();
427
        } catch (TransferException $ex) {
428
            Log::warning($ex);
429
            Alert::danger('A TransferException occurred while attempting to delete this server from the daemon, please ensure it is running. This error has been logged.')->flash();
430
        } catch (\Exception $ex) {
431
            Log::error($ex);
432
            Alert::danger('An unhandled exception occured while attemping to delete this server. This error has been logged.')->flash();
433
        }
434
435
        return redirect()->route('admin.servers.view.delete', $id);
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
436
    }
437
438
    /**
439
     * Update the startup command as well as variables.
440
     *
441
     * @param  \Illuminate\Http\Request  $request
442
     * @param  int                       $id
443
     * @return \Illuminate\Http\RedirectResponse
444
     */
445
    public function saveStartup(Request $request, $id)
446
    {
447
        $repo = new ServerRepository;
448
449
        try {
450
            $repo->updateStartup($id, $request->except('_token'), true);
451
452
            Alert::success('Startup variables were successfully modified and assigned for this server.')->flash();
453
        } catch (DisplayValidationException $ex) {
454
            return redirect()->route('admin.servers.view.startup', $id)->withErrors(json_decode($ex->getMessage()));
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
455
        } catch (DisplayException $ex) {
456
            Alert::danger($ex->getMessage())->flash();
457
        } catch (TransferException $ex) {
458
            Log::warning($ex);
459
            Alert::danger('A TransferException occurred while attempting to update the startup for this server, please ensure the daemon is running. This error has been logged.')->flash();
460
        } catch (\Exception $ex) {
461
            Log::error($ex);
462
            Alert::danger('An unhandled exception occured while attemping to update startup variables for this server. This error has been logged.')->flash();
463
        }
464
465
        return redirect()->route('admin.servers.view.startup', $id);
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
466
    }
467
468
    /**
469
     * Creates a new database assigned to a specific server.
470
     *
471
     * @param  \Illuminate\Http\Request  $request
472
     * @param  int                       $id
473
     * @return \Illuminate\Http\RedirectResponse
474
     */
475
    public function newDatabase(Request $request, $id)
476
    {
477
        $repo = new DatabaseRepository;
478
479
        try {
480
            $repo->create($id, $request->only(['host', 'database', 'connection']));
481
482
            Alert::success('A new database was assigned to this server successfully.')->flash();
483
        } catch (DisplayValidationException $ex) {
484
            return redirect()->route('admin.servers.view.database', $id)->withInput()->withErrors(json_decode($ex->getMessage()))->withInput();
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
485
        } catch (DisplayException $ex) {
486
            Alert::danger($ex->getMessage())->flash();
487
        } catch (\Exception $ex) {
488
            Log::error($ex);
489
            Alert::danger('An exception occured while attempting to add a new database for this server. This error has been logged.')->flash();
490
        }
491
492
        return redirect()->route('admin.servers.view.database', $id)->withInput();
0 ignored issues
show
Documentation introduced by
$id is of type integer, 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...
493
    }
494
495
    /**
496
     * Resets the database password for a specific database on this server.
497
     *
498
     * @param  \Illuminate\Http\Request  $request
499
     * @param  int                       $id
500
     * @return \Illuminate\Http\RedirectResponse
501
     */
502 View Code Duplication
    public function resetDatabasePassword(Request $request, $id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
503
    {
504
        $database = Models\Database::where('server_id', $id)->findOrFail($request->input('database'));
505
        $repo = new DatabaseRepository;
506
507
        try {
508
            $repo->password($database->id, str_random(20));
509
510
            return response('', 204);
511
        } catch (\Exception $ex) {
512
            Log::error($ex);
513
514
            return response()->json(['error' => 'A unhandled exception occurred while attempting to reset this password. This error has been logged.'], 503);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...s been logged.'), 503); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Pterodactyl\Http\Control...::resetDatabasePassword 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...
515
        }
516
    }
517
518
    /**
519
     * Deletes a database from a server.
520
     *
521
     * @param  \Illuminate\Http\Request  $request
522
     * @param  int                       $id
523
     * @param  int                       $database
524
     * @return \Illuminate\Http\RedirectResponse
525
     */
526 View Code Duplication
    public function deleteDatabase(Request $request, $id, $database)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
527
    {
528
        $database = Models\Database::where('server_id', $id)->findOrFail($database);
529
        $repo = new DatabaseRepository;
530
531
        try {
532
            $repo->drop($database->id);
533
534
            return response('', 204);
535
        } catch (\Exception $ex) {
536
            Log::error($ex);
537
538
            return response()->json(['error' => 'A unhandled exception occurred while attempting to drop this database. This error has been logged.'], 503);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...s been logged.'), 503); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Pterodactyl\Http\Control...troller::deleteDatabase 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...
539
        }
540
    }
541
}
542