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
Pull Request — develop (#286)
by Dane
04:53 queued 02:03
created

NodeController   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 176
Duplicated Lines 10.23 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 11
dl 18
loc 176
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A lists() 0 4 1
A create() 0 21 4
B view() 6 22 5
A config() 0 9 2
A allocations() 0 4 1
A allocationsView() 0 4 1
A delete() 12 13 3

How to fix   Duplicated Code   

Duplicated Code

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

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * 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 Pterodactyl\Models;
29
use Illuminate\Http\Request;
30
use Dingo\Api\Exception\ResourceException;
31
use Pterodactyl\Exceptions\DisplayException;
32
use Pterodactyl\Repositories\NodeRepository;
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
/**
39
 * @Resource("Servers")
40
 */
41
class NodeController extends BaseController
42
{
43
    public function __construct()
44
    {
45
        //
46
    }
47
48
    /**
49
     * List All Nodes.
50
     *
51
     * Lists all nodes currently on the system.
52
     *
53
     * @Get("/nodes/{?page}")
54
     * @Versions({"v1"})
55
     * @Parameters({
56
     *      @Parameter("page", type="integer", description="The page of results to view.", default=1)
57
     * })
58
     * @Response(200)
59
     */
60
    public function lists(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...
61
    {
62
        return Models\Node::all()->toArray();
63
    }
64
65
    /**
66
     * Create a New Node.
67
     *
68
     * @Post("/nodes")
69
     * @Versions({"v1"})
70
     * @Transaction({
71
     *      @Request({
72
     *      	'name' => 'My API Node',
73
     *      	'location' => 1,
74
     *      	'public' => 1,
75
     *      	'fqdn' => 'daemon.wuzzle.woo',
76
     *      	'scheme' => 'https',
77
     *      	'memory' => 10240,
78
     *      	'memory_overallocate' => 100,
79
     *      	'disk' => 204800,
80
     *      	'disk_overallocate' => -1,
81
     *      	'daemonBase' => '/srv/daemon-data',
82
     *      	'daemonSFTP' => 2022,
83
     *      	'daemonListen' => 8080
84
     *      }, headers={"Authorization": "Bearer <jwt-token>"}),
85
     *       @Response(200),
86
     *       @Response(422, body={
87
     *          "message": "A validation error occured.",
88
     *          "errors": {},
89
     *          "status_code": 422
90
     *       }),
91
     *       @Response(503, body={
92
     *       	"message": "There was an error while attempting to add this node to the system.",
93
     *       	"status_code": 503
94
     *       })
95
     * })
96
     */
97
    public function create(Request $request)
98
    {
99
        try {
100
            $repo = new NodeRepository;
101
            $node = $repo->create($request->only([
0 ignored issues
show
Unused Code introduced by
$node 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...
102
                'name', 'location_id', 'public', 'fqdn',
103
                'scheme', 'memory', 'memory_overallocate',
104
                'disk', 'disk_overallocate', 'daemonBase',
105
                'daemonSFTP', 'daemonListen',
106
            ]));
107
108
            return ['id' => $repo->id];
0 ignored issues
show
Bug introduced by
The property id does not seem to exist in Pterodactyl\Repositories\NodeRepository.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
109
        } catch (DisplayValidationException $ex) {
110
            throw new ResourceException('A validation error occured.', json_decode($ex->getMessage(), true));
111
        } catch (DisplayException $ex) {
112
            throw new ResourceException($ex->getMessage());
113
        } catch (\Exception $ex) {
114
            Log::error($ex);
115
            throw new BadRequestHttpException('There was an error while attempting to add this node to the system.');
116
        }
117
    }
118
119
    /**
120
     * List Specific Node.
121
     *
122
     * Lists specific fields about a server or all fields pertaining to that node.
123
     *
124
     * @Get("/nodes/{id}/{?fields}")
125
     * @Versions({"v1"})
126
     * @Parameters({
127
     *      @Parameter("id", type="integer", required=true, description="The ID of the node to get information on."),
128
     *      @Parameter("fields", type="string", required=false, description="A comma delimidated list of fields to include.")
129
     * })
130
     * @Response(200)
131
     */
132
    public function view(Request $request, $id, $fields = null)
0 ignored issues
show
Unused Code introduced by
The parameter $fields 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...
133
    {
134
        $node = Models\Node::with('allocations')->where('id', $id)->first();
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...
135
        if (! $node) {
136
            throw new NotFoundHttpException('No node by that ID was found.');
137
        }
138
139
        $node->allocations->transform(function ($item) {
140
            return collect($item)->only([
141
                'id', 'ip', 'ip_alias', 'port', 'server_id',
142
            ]);
143
        });
144
145 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...
146
            $fields = explode(',', $request->input('fields'));
147
            if (! empty($fields) && is_array($fields)) {
148
                return collect($node)->only($fields);
149
            }
150
        }
151
152
        return $node;
153
    }
154
155
    public function config(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...
156
    {
157
        $node = Models\Node::where('id', $id)->first();
158
        if (! $node) {
159
            throw new NotFoundHttpException('No node by that ID was found.');
160
        }
161
162
        return $node->getConfigurationAsJson();
163
    }
164
165
     /**
166
      * List all Node Allocations.
167
      *
168
      * Returns a listing of all allocations for every node.
169
      *
170
      * @Get("/nodes/allocations")
171
      * @Versions({"v1"})
172
      * @Response(200)
173
      */
174
     public function allocations(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...
175
     {
176
         return Models\Allocation::all()->toArray();
177
     }
178
179
     /**
180
      * List Node Allocation based on assigned to ID.
181
      *
182
      * Returns a listing of the allocation for the specified server id.
183
      *
184
      * @Get("/nodes/allocations/{id}")
185
      * @Versions({"v1"})
186
      * @Response(200)
187
      */
188
     public function allocationsView(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...
189
     {
190
         return Models\Allocation::where('assigned_to', $id)->get()->toArray();
191
     }
192
193
    /**
194
     * Delete Node.
195
     *
196
     * @Delete("/nodes/{id}")
197
     * @Versions({"v1"})
198
     * @Parameters({
199
     *      @Parameter("id", type="integer", required=true, description="The ID of the node."),
200
     * })
201
     * @Response(204)
202
     */
203 View Code Duplication
    public function delete(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...
204
    {
205
        try {
206
            $node = new NodeRepository;
207
            $node->delete($id);
208
209
            return $this->response->noContent();
210
        } catch (DisplayException $ex) {
211
            throw new ResourceException($ex->getMessage());
212
        } catch (\Exception $e) {
213
            throw new ServiceUnavailableHttpException('An error occured while attempting to delete this node.');
214
        }
215
    }
216
}
217