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 (#371)
by Dane
02:54
created

UserController   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 145
Duplicated Lines 72.41 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 8
dl 105
loc 145
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A index() 16 16 3
A view() 13 13 2
B store() 28 28 4
B update() 28 28 4
A delete() 20 20 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\Admin;
26
27
use Fractal;
28
use Illuminate\Http\Request;
29
use Pterodactyl\Models\User;
30
use Pterodactyl\Http\Controllers\Controller;
31
use Pterodactyl\Exceptions\DisplayException;
32
use Pterodactyl\Repositories\UserRepository;
33
use Pterodactyl\Transformers\Admin\UserTransformer;
34
use Pterodactyl\Exceptions\DisplayValidationException;
35
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
36
37
class UserController extends Controller
38
{
39
    /**
40
     * Controller to handle returning all users on the system.
41
     *
42
     * @param  \Illuminate\Http\Request  $request
43
     * @return array
44
     */
45 View Code Duplication
    public function index(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...
46
    {
47
        $this->authorize('user-list', $request->apiKey());
48
49
        $users = User::paginate(config('pterodactyl.paginate.api.users'));
50
        $fractal = Fractal::create()->collection($users)
51
            ->transformWith(new UserTransformer($request))
52
            ->withResourceName('user')
53
            ->paginateWith(new IlluminatePaginatorAdapter($users));
54
55
        if (config('pterodactyl.api.include_on_list') && $request->input('include')) {
56
            $fractal->parseIncludes(explode(',', $request->input('include')));
57
        }
58
59
        return $fractal->toArray();
60
    }
61
62
    /**
63
     * Display information about a single user on the system.
64
     *
65
     * @param  \Illuminate\Http\Request  $request
66
     * @param  int                       $id
67
     * @return array
68
     */
69 View Code Duplication
    public function view(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...
70
    {
71
        $this->authorize('user-view', $request->apiKey());
72
73
        $fractal = Fractal::create()->item(User::findOrFail($id));
74
        if ($request->input('include')) {
75
            $fractal->parseIncludes(explode(',', $request->input('include')));
76
        }
77
78
        return $fractal->transformWith(new UserTransformer($request))
79
            ->withResourceName('user')
80
            ->toArray();
81
    }
82
83
    /**
84
     * Create a new user on the system.
85
     *
86
     * @param  \Illuminate\Http\Request  $request
87
     * @return \Illuminate\Http\JsonResponse|array
88
     */
89 View Code Duplication
    public function store(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
        $this->authorize('user-create', $request->apiKey());
92
93
        $repo = new UserRepository;
94
        try {
95
            $user = $repo->create($request->only([
96
                'custom_id', 'email', 'password', 'name_first',
97
                'name_last', 'username', 'root_admin',
98
            ]));
99
100
            $fractal = Fractal::create()->item($user)->transformWith(new UserTransformer($request));
101
            if ($request->input('include')) {
102
                $fractal->parseIncludes(explode(',', $request->input('include')));
103
            }
104
105
            return $fractal->withResourceName('user')->toArray();
106
        } catch (DisplayValidationException $ex) {
107
            return response()->json([
108
                'error' => json_decode($ex->getMessage()),
109
            ], 400);
110
        } catch (\Exception $ex) {
111
            Log::error($ex);
112
            return response()->json([
113
                'error' => 'An unhandled exception occured while attemping to create this user. Please try again.',
114
            ], 500);
115
        }
116
    }
117
118
    /**
119
     * Update a user.
120
     *
121
     * @param  \Illuminate\Http\Request  $request
122
     * @param  int                       $user
123
     * @return \Illuminate\Http\RedirectResponse
124
     */
125 View Code Duplication
    public function update(Request $request, $user)
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...
126
    {
127
        $this->authorize('user-edit', $request->apiKey());
128
129
        $repo = new UserRepository;
130
        try {
131
            $user = $repo->update($user, $request->intersect([
132
                'email', 'password', 'name_first',
133
                'name_last', 'username', 'root_admin',
134
            ]));
135
136
            $fractal = Fractal::create()->item($user)->transformWith(new UserTransformer($request));
137
            if ($request->input('include')) {
138
                $fractal->parseIncludes(explode(',', $request->input('include')));
139
            }
140
141
            return $fractal->withResourceName('user')->toArray();
142
        } catch (DisplayValidationException $ex) {
143
            return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...->getMessage())), 400); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Pterodactyl\Http\Control...\UserController::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...
144
                'error' => json_decode($ex->getMessage()),
145
            ], 400);
146
        } catch (\Exception $ex) {
147
            Log::error($ex);
148
            return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...ase try again.'), 500); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Pterodactyl\Http\Control...\UserController::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...
149
                'error' => 'An unhandled exception occured while attemping to update this user. Please try again.',
150
            ], 500);
151
        }
152
    }
153
154
    /**
155
     * Delete a user from the system.
156
     *
157
     * @param  \Illuminate\Http\Request  $request
158
     * @param  int                       $id
159
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
160
     */
161 View Code Duplication
    public function delete(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...
162
    {
163
        $this->authorize('user-delete', $request->apiKey());
164
165
        $repo = new UserRepository;
166
        try {
167
            $repo->delete($id);
168
169
            return response('', 204);
170
        } catch (DisplayException $ex) {
171
            return response()->json([
172
                'error' => $ex->getMessage(),
173
            ], 400);
174
        } catch (\Exception $ex) {
175
            Log::error($ex);
176
            return response()->json([
177
                'error' => 'An unhandled exception occured while attemping to delete this user. Please try again.',
178
            ], 500);
179
        }
180
    }
181
}
182