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 ( 008ccc...22da8d )
by Dane
02:48
created

UserRepository::create()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 62
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 62
rs 7.3333
c 0
b 0
f 0
cc 7
eloc 38
nc 24
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 Carbon;
32
use Settings;
33
use Validator;
34
use Pterodactyl\Models;
35
use Pterodactyl\Services\UuidService;
36
use Pterodactyl\Exceptions\DisplayException;
37
use Pterodactyl\Notifications\AccountCreated;
38
use Pterodactyl\Exceptions\DisplayValidationException;
39
40
class UserRepository
41
{
42
    public function __construct()
43
    {
44
        //
45
    }
46
47
    /**
48
     * Creates a user on the panel. Returns the created user's ID.
49
     *
50
     * @param  string       $email
0 ignored issues
show
Bug introduced by
There is no parameter named $email. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
51
     * @param  string|null  $password An unhashed version of the user's password.
0 ignored issues
show
Bug introduced by
There is no parameter named $password. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
52
     * @param  bool         $admin    Boolean value if user should be an admin or not.
0 ignored issues
show
Bug introduced by
There is no parameter named $admin. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
53
     * @param  int          $token    A custom user ID.
0 ignored issues
show
Bug introduced by
There is no parameter named $token. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
54
     * @return bool|int
55
     */
56
    public function create(array $data)
57
    {
58
        $validator = Validator::make($data, [
59
            'email' => 'required|email|unique:users,email',
60
            'username' => 'required|string|between:1,255|unique:users,username|' . Models\User::USERNAME_RULES,
61
            'name_first' => 'required|string|between:1,255',
62
            'name_last' => 'required|string|between:1,255',
63
            'password' => 'sometimes|nullable|' . Models\User::PASSWORD_RULES,
64
            'root_admin' => 'required|boolean',
65
            'custom_id' => 'sometimes|nullable|unique:users,id',
66
        ]);
67
68
        // Run validator, throw catchable and displayable exception if it fails.
69
        // Exception includes a JSON result of failed validation rules.
70
        if ($validator->fails()) {
71
            throw new DisplayValidationException($validator->errors());
72
        }
73
74
        DB::beginTransaction();
75
76
        try {
77
            $user = new Models\User;
78
            $uuid = new UuidService;
79
80
            // Support for API Services
81
            if (isset($data['custom_id']) && ! is_null($data['custom_id'])) {
82
                $user->id = $token;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Pterodactyl\Models\User>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
Bug introduced by
The variable $token seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
83
            }
84
85
            // UUIDs are not mass-fillable.
86
            $user->uuid = $uuid->generate('users', 'uuid');
0 ignored issues
show
Documentation introduced by
The property uuid does not exist on object<Pterodactyl\Models\User>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
87
88
            $user->fill([
89
                'email' => $data['email'],
90
                'username' => $data['username'],
91
                'name_first' => $data['name_first'],
92
                'name_last' => $data['name_last'],
93
                'password' => Hash::make((empty($data['password'])) ? str_random(30) : $data['password']),
94
                'root_admin' => $data['root_admin'],
95
                'language' => Settings::get('default_language', 'en'),
96
            ]);
97
            $user->save();
98
99
            // Setup a Password Reset to use when they set a password.
100
            // Only used if no password is provided.
101
            if (empty($data['password'])) {
102
                $token = str_random(32);
103
                DB::table('password_resets')->insert([
104
                    'email' => $user->email,
0 ignored issues
show
Documentation introduced by
The property email does not exist on object<Pterodactyl\Models\User>. 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...
105
                    'token' => $token,
106
                    'created_at' => Carbon::now()->toDateTimeString(),
107
                ]);
108
            }
109
110
            DB::commit();
111
112
            return $user;
113
        } catch (\Exception $ex) {
114
            DB::rollBack();
115
            throw $ex;
116
        }
117
    }
118
119
    /**
120
     * Updates a user on the panel.
121
     *
122
     * @param  int $id
123
     * @param  array $data An array of columns and their associated values to update for the user.
124
     * @return bool
125
     */
126
    public function update($id, array $data)
127
    {
128
        $user = Models\User::findOrFail($id);
129
130
        $validator = Validator::make($data, [
131
            'email' => 'sometimes|required|email|unique:users,email,' . $id,
132
            'username' => 'sometimes|required|string|between:1,255|unique:users,username,' . $user->id . '|' . Models\User::USERNAME_RULES,
133
            'name_first' => 'sometimes|required|string|between:1,255',
134
            'name_last' => 'sometimes|required|string|between:1,255',
135
            'password' => 'sometimes|nullable|' . Models\User::PASSWORD_RULES,
136
            'root_admin' => 'sometimes|required|boolean',
137
            'language' => 'sometimes|required|string|min:1|max:5',
138
            'use_totp' => 'sometimes|required|boolean',
139
            'totp_secret' => 'sometimes|required|size:16',
140
        ]);
141
142
        // Run validator, throw catchable and displayable exception if it fails.
143
        // Exception includes a JSON result of failed validation rules.
144
        if ($validator->fails()) {
145
            throw new DisplayValidationException($validator->errors());
146
        }
147
148
        // The password and root_admin fields are not mass assignable.
149
        if (! empty($data['password'])) {
150
            $data['password'] = Hash::make($data['password']);
151
        } else {
152
            unset($data['password']);
153
        }
154
155
        $user->fill($data);
156
157
        return $user->save();
158
    }
159
160
    /**
161
     * Deletes a user on the panel, returns the number of records deleted.
162
     *
163
     * @param  int $id
164
     * @return int
165
     */
166
    public function delete($id)
167
    {
168
        if (Models\Server::where('owner_id', $id)->count() > 0) {
169
            throw new DisplayException('Cannot delete a user with active servers attached to thier account.');
170
        }
171
172
        // @TODO: this should probably be checked outside of this method because we won't always have Auth::user()
173
        if (! is_null(Auth::user()) && Auth::user()->id === $id) {
174
            throw new DisplayException('Cannot delete your own account.');
175
        }
176
177
        DB::beginTransaction();
178
179
        try {
180
            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...
181
                foreach($subuser->permissions as &$permission) {
182
                    $permission->delete();
183
                }
184
185
                $subuser->delete();
186
            }
187
188
            Models\User::destroy($id);
189
            DB::commit();
190
191
            return true;
192
        } catch (\Exception $ex) {
193
            DB::rollBack();
194
            throw $ex;
195
        }
196
    }
197
}
198