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 ( 4e916c...5e2777 )
by Dane
02:47
created

ServerController::lists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
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\API;
26
27
use Log;
28
use Illuminate\Http\Request;
29
use Pterodactyl\Models\Server;
30
use Dingo\Api\Exception\ResourceException;
31
use Pterodactyl\Exceptions\DisplayException;
32
use Pterodactyl\Repositories\ServerRepository;
33
use Pterodactyl\Exceptions\DisplayValidationException;
34
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
35
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
36
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
37
38
class ServerController extends BaseController
39
{
40
    /**
41
     * Lists all servers currently on the system.
42
     *
43
     * @param  Request  $request
44
     * @return array
45
     */
46
    public function index(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...
47
    {
48
        return Server::all()->toArray();
49
    }
50
51
    /**
52
     * Create Server.
53
     *
54
     * @param  Request  $request
55
     * @return array
56
     */
57
    public function create(Request $request)
58
    {
59
        $repo = new ServerRepository;
60
61
        try {
62
            $server = $repo->create($request->all());
63
64
            return ['id' => $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...
65
        } catch (DisplayValidationException $ex) {
66
            throw new ResourceException('A validation error occured.', json_decode($ex->getMessage(), true));
67
        } catch (DisplayException $ex) {
68
            throw new ResourceException($ex->getMessage());
69
        } catch (\Exception $ex) {
70
            Log::error($ex);
71
            throw new BadRequestHttpException('There was an error while attempting to add this server to the system.');
72
        }
73
    }
74
75
    /**
76
     * List Specific Server.
77
     *
78
     * @param  Request  $request
79
     * @param  int      $id
80
     * @return array
81
     */
82
    public function view(Request $request, $id)
83
    {
84
        $server = Server::with('node', 'allocations', 'pack')->where('id', $id)->firstOrFail();
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...
85
86 View Code Duplication
        if (! is_null($request->input('fields'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
87
            $fields = explode(',', $request->input('fields'));
88
            if (! empty($fields) && is_array($fields)) {
89
                return collect($server)->only($fields);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return collect($server)->only($fields); (Illuminate\Support\Collection) is incompatible with the return type documented by Pterodactyl\Http\Control...\ServerController::view of type array.

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...
90
            }
91
        }
92
93
        if ($request->input('daemon') === 'true') {
94
            try {
95
                $response = $server->node->guzzleClient([
96
                    'X-Access-Token' => $server->node->daemonSecret,
97
                ])->request('GET', '/servers');
98
99
                $server->daemon = json_decode($response->getBody())->{$server->uuid};
100
            } catch (\GuzzleHttp\Exception\TransferException $ex) {
101
                // Couldn't hit the daemon, return what we have though.
102
                $server->daemon = [
103
                    'error' => 'There was an error encountered while attempting to connect to the remote daemon.',
104
                ];
105
            }
106
        }
107
108
        $server->allocations->transform(function ($item) {
109
            return collect($item)->except(['created_at', 'updated_at']);
110
        });
111
112
        return $server->toArray();
113
    }
114
115
    /**
116
     * Update Server configuration.
117
     *
118
     * @param  Request  $request
119
     * @param  int      $id
120
     * @return array
121
     */
122
    public function config(Request $request, $id)
123
    {
124
        $repo = new ServerRepository;
125
126
        try {
127
            $server = $repo->updateDetails($id, $request->intersect([
0 ignored issues
show
Unused Code introduced by
$server 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...
128
                'owner_id', 'name', 'reset_token',
129
            ]));
130
131
            return ['id' => $id];
132
        } catch (DisplayValidationException $ex) {
133
            throw new ResourceException('A validation error occured.', json_decode($ex->getMessage(), true));
134
        } catch (DisplayException $ex) {
135
            throw new ResourceException($ex->getMessage());
136
        } catch (\Exception $ex) {
137
            throw new ServiceUnavailableHttpException('Unable to update server on system due to an error.');
138
        }
139
    }
140
141
    /**
142
     * Update Server Build Configuration.
143
     *
144
     * @param  Request  $request
145
     * @param  int      $id
146
     * @return array
147
     */
148 View Code Duplication
    public function build(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...
149
    {
150
        $repo = new ServerRepository;
151
152
        try {
153
            $server = $repo->changeBuild($id, $request->intersect([
0 ignored issues
show
Unused Code introduced by
$server 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...
154
                'allocation_id', 'add_allocations', 'remove_allocations',
155
                'memory', 'swap', 'io', 'cpu',
156
            ]));
157
158
            return ['id' => $id];
159
        } catch (DisplayValidationException $ex) {
160
            throw new ResourceException('A validation error occured.', json_decode($ex->getMessage(), true));
161
        } catch (DisplayException $ex) {
162
            throw new ResourceException($ex->getMessage());
163
        } catch (\Exception $ex) {
164
            throw new ServiceUnavailableHttpException('Unable to update server on system due to an error.');
165
        }
166
    }
167
168
    /**
169
     * Suspend Server.
170
     *
171
     * @param  Request  $request
172
     * @param  int      $id
173
     * @return void
174
     */
175 View Code Duplication
    public function suspend(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...
176
    {
177
        try {
178
            $repo = new ServerRepository;
179
            $repo->suspend($id);
180
181
            return $this->response->noContent();
182
        } catch (DisplayException $ex) {
183
            throw new ResourceException($ex->getMessage());
184
        } catch (\Exception $ex) {
185
            throw new ServiceUnavailableHttpException('An error occured while attempting to suspend this server instance.');
186
        }
187
    }
188
189
    /**
190
     * Unsuspend Server.
191
     *
192
     * @param  Request  $request
193
     * @param  int      $id
194
     * @return void
195
     */
196 View Code Duplication
    public function unsuspend(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...
197
    {
198
        try {
199
            $repo = new ServerRepository;
200
            $repo->unsuspend($id);
201
202
            return $this->response->noContent();
203
        } catch (DisplayException $ex) {
204
            throw new ResourceException($ex->getMessage());
205
        } catch (\Exception $ex) {
206
            throw new ServiceUnavailableHttpException('An error occured while attempting to unsuspend this server instance.');
207
        }
208
    }
209
210
    /**
211
     * Delete Server.
212
     *
213
     * @param  Request  $request
214
     * @param  int      $id
215
     * @param  string|null $force
216
     * @return void
217
     */
218 View Code Duplication
    public function delete(Request $request, $id, $force = null)
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...
219
    {
220
        $repo = new ServerRepository;
221
222
        try {
223
            $repo->deleteServer($id, $force);
0 ignored issues
show
Bug introduced by
The method deleteServer() does not exist on Pterodactyl\Repositories\ServerRepository. Did you maybe mean delete()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
224
225
            return $this->response->noContent();
226
        } catch (DisplayException $ex) {
227
            throw new ResourceException($ex->getMessage());
228
        } catch (\Exception $e) {
229
            throw new ServiceUnavailableHttpException('An error occured while attempting to delete this server.');
230
        }
231
    }
232
}
233