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.

UserRepository::create()   B
last analyzed

Complexity

Conditions 6
Paths 14

Size

Total Lines 51
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 51
rs 8.6588
c 0
b 0
f 0
cc 6
eloc 32
nc 14
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Pterodactyl - Panel
4
 * Copyright (c) 2015 - 2017 Dane Everitt <[email protected]>
5
 * Some Modifications (c) 2015 Dylan Seidt <[email protected]>.
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in all
15
 * copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
 * SOFTWARE.
24
 */
25
26
namespace Pterodactyl\Repositories;
27
28
use DB;
29
use Auth;
30
use Hash;
31
use Settings;
32
use Validator;
33
use Pterodactyl\Models;
34
use Pterodactyl\Services\UuidService;
35
use Pterodactyl\Exceptions\DisplayException;
36
use Pterodactyl\Exceptions\DisplayValidationException;
37
38
class UserRepository
39
{
40
    /**
41
     * Creates a user on the panel. Returns the created user's ID.
42
     *
43
     * @param  array  $data
44
     * @return \Pterodactyl\Models\User
45
     *
46
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
47
     */
48
    public function create(array $data)
49
    {
50
        $validator = Validator::make($data, [
51
            'email' => 'required|email|unique:users,email',
52
            'username' => 'required|string|between:1,255|unique:users,username|' . Models\User::USERNAME_RULES,
53
            'name_first' => 'required|string|between:1,255',
54
            'name_last' => 'required|string|between:1,255',
55
            'password' => 'sometimes|nullable|' . Models\User::PASSWORD_RULES,
56
            'root_admin' => 'required|boolean',
57
            'custom_id' => 'sometimes|nullable|unique:users,id',
58
        ]);
59
60
        // Run validator, throw catchable and displayable exception if it fails.
61
        // Exception includes a JSON result of failed validation rules.
62
        if ($validator->fails()) {
63
            throw new DisplayValidationException(json_encode($validator->errors()));
64
        }
65
66
        DB::beginTransaction();
67
68
        try {
69
            $user = new Models\User;
70
            $uuid = new UuidService;
71
72
            // Support for API Services
73
            if (isset($data['custom_id']) && ! is_null($data['custom_id'])) {
74
                $user->id = $token;
0 ignored issues
show
Bug introduced by
The variable $token does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
75
            }
76
77
            // UUIDs are not mass-fillable.
78
            $user->uuid = $uuid->generate('users', 'uuid');
79
80
            $user->fill([
81
                'email' => $data['email'],
82
                'username' => $data['username'],
83
                'name_first' => $data['name_first'],
84
                'name_last' => $data['name_last'],
85
                'password' => (empty($data['password'])) ? 'unset' : Hash::make($data['password']),
86
                'root_admin' => $data['root_admin'],
87
                'language' => Settings::get('default_language', 'en'),
88
            ]);
89
            $user->save();
90
91
            DB::commit();
92
93
            return $user;
94
        } catch (\Exception $ex) {
95
            DB::rollBack();
96
            throw $ex;
97
        }
98
    }
99
100
    /**
101
     * Updates a user on the panel.
102
     *
103
     * @param  int    $id
104
     * @param  array  $data
105
     * @return \Pterodactyl\Models\User
106
     *
107
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
108
     */
109
    public function update($id, array $data)
110
    {
111
        $user = Models\User::findOrFail($id);
112
113
        $validator = Validator::make($data, [
114
            'email' => 'sometimes|required|email|unique:users,email,' . $id,
115
            'username' => 'sometimes|required|string|between:1,255|unique:users,username,' . $user->id . '|' . Models\User::USERNAME_RULES,
116
            'name_first' => 'sometimes|required|string|between:1,255',
117
            'name_last' => 'sometimes|required|string|between:1,255',
118
            'password' => 'sometimes|nullable|' . Models\User::PASSWORD_RULES,
119
            'root_admin' => 'sometimes|required|boolean',
120
            'language' => 'sometimes|required|string|min:1|max:5',
121
            'use_totp' => 'sometimes|required|boolean',
122
            'totp_secret' => 'sometimes|required|size:16',
123
        ]);
124
125
        // Run validator, throw catchable and displayable exception if it fails.
126
        // Exception includes a JSON result of failed validation rules.
127
        if ($validator->fails()) {
128
            throw new DisplayValidationException(json_encode($validator->errors()));
129
        }
130
131
        // The password and root_admin fields are not mass assignable.
132
        if (! empty($data['password'])) {
133
            $data['password'] = Hash::make($data['password']);
134
        } else {
135
            unset($data['password']);
136
        }
137
138
        $user->fill($data)->save();
139
140
        return $user;
141
    }
142
143
    /**
144
     * Deletes a user on the panel.
145
     *
146
     * @param  int $id
147
     * @return void
148
     * @todo   Move user self-deletion checking to the controller, rather than the repository.
149
     *
150
     * @throws \Pterodactyl\Exceptions\DisplayException
151
     */
152
    public function delete($id)
153
    {
154
        if (Models\Server::where('owner_id', $id)->count() > 0) {
155
            throw new DisplayException('Cannot delete a user with active servers attached to thier account.');
156
        }
157
158
        if (! is_null(Auth::user()) && (int) Auth::user()->id === (int) $id) {
159
            throw new DisplayException('Cannot delete your own account.');
160
        }
161
162
        DB::beginTransaction();
163
164
        try {
165
            foreach (Models\Subuser::with('permissions')->where('user_id', $id)->get() as &$subuser) {
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...
Bug introduced by
The expression \Pterodactyl\Models\Subu...('user_id', $id)->get() cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
166
                foreach ($subuser->permissions as &$permission) {
167
                    $permission->delete();
168
                }
169
170
                $subuser->delete();
171
            }
172
173
            Models\User::destroy($id);
174
            DB::commit();
175
        } catch (\Exception $ex) {
176
            DB::rollBack();
177
            throw $ex;
178
        }
179
    }
180
}
181