Test Setup Failed
Push — master ( 31dfdc...3c949c )
by Bob
03:29
created

authCheck::checkAuth()   D

Complexity

Conditions 18
Paths 216

Size

Total Lines 116
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 23
Bugs 9 Features 1
Metric Value
cc 18
eloc 80
c 23
b 9
f 1
nc 216
nop 1
dl 0
loc 116
rs 4.2397

How to fix   Long Method    Complexity   

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
 * The MIT License (MIT)
4
 *
5
 * Copyright (c) 2016 Robert Sardinia
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
use discord\discord;
27
28
/**
29
 * Class fileAuthCheck
30
 * @property int nextCheck
31
 */
32
class authCheck
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
33
{
34
    /**
35
     * @var
36
     */
37
    var $config;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $config.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
38
    /**
39
     * @var
40
     */
41
    var $db;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $db.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
42
    /**
43
     * @var
44
     */
45
    var $discord;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $discord.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
46
    /**
47
     * @var
48
     */
49
    var $channelConfig;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $channelConfig.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
50
    /**
51
     * @var int
52
     */
53
    var $lastCheck = 0;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $lastCheck.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
54
    /**
55
     * @var
56
     */
57
    var $logger;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $logger.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
58
59
    /**
60
     * @param $config
61
     * @param $discord
62
     * @param $logger
63
     */
64
    function init($config, $discord, $logger)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
65
    {
66
        $this->config = $config;
67
        $this->discord = $discord;
68
        $this->logger = $logger;
69
        $this->nextCheck = 0;
70
        $lastCheck = getPermCache("authLastChecked");
71
        if ($lastCheck == NULL) {
72
            // Schedule it for right now if first run
73
            setPermCache("authLastChecked", time() - 5);
74
        }
75
    }
76
77
    /**
78
     * @return array
79
     */
80
    function information()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
81
    {
82
        return array(
83
            "name" => "",
84
            "trigger" => array(),
85
            "information" => ""
86
        );
87
    }
88
    function tick()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
89
    {
90
        $lastChecked = getPermCache("authLastChecked");
91
        $discord = $this->discord;
92
93
        if ($lastChecked <= time()) {
94
            $this->logger->addInfo("Checking authed users for changes....");
95
            $this->checkAuth($discord);
96
        }
97
98
    }
99
100
    /**
101
     * @param $discord
102
     * @return null
103
     */
104
    function checkAuth($discord)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
105
    {
106
        $db = $this->config["database"]["host"];
107
        $dbUser = $this->config["database"]["user"];
108
        $dbPass = $this->config["database"]["pass"];
109
        $dbName = $this->config["database"]["database"];
110
        $id = $this->config["bot"]["guild"];
111
        $allyID = $this->config["plugins"]["auth"]["allianceID"];
112
        $corpID = $this->config["plugins"]["auth"]["corpID"];
113
        $exempt = $this->config["plugins"]["auth"]["exempt"];
114
        if(is_null($exempt)){
115
            $exempt = "0";
116
        }
117
        $toDiscordChannel = $this->config["plugins"]["auth"]["alertChannel"];
118
        $conn = new mysqli($db, $dbUser, $dbPass, $dbName);
119
120
        //get bot ID so we don't remove out own roles
121
        $botID = $this->discord->id;
122
123
        //Remove members who have roles but never authed
124
        $guild = $discord->guilds->get('id', $id);
125
        foreach($guild->members as $member) {
126
            $notifier = null;
0 ignored issues
show
Unused Code introduced by
$notifier 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...
127
            $id = $member->id;
128
            $username = $member->username;
129
            $roles = $member->roles;
130
131
            $sql = "SELECT * FROM authUsers WHERE discordID='$id' AND active='yes'";
132
133
            $result = $conn->query($sql);
134
            if($result->num_rows == 0) {
135
                foreach ($roles as $role) {
136
                    if(!isset($role->name)){
137
                        if($id != $botID && !in_array($role->name, $exempt, true)){
138
                            $member->removeRole($role);
139
                            $guild->members->save($member);
140
                            // Send the info to the channel
141
                            $msg = "{$username} has been removed from the {$role->name} role as they never authed (Someone manually assigned them roles).";
142
                            $channelID = $toDiscordChannel;
143
                            $channel = $guild->channels->get('id', $channelID);
144
                            $channel->sendMessage($msg, false);
145
                            $this->logger->addInfo("{$username} has been removed from the {$role->name} role as they never authed.");
146
                        }
147
                    }
148
                }
149
            }
150
        }
151
152
        $sql = "SELECT characterID, discordID, eveName FROM authUsers WHERE active='yes'";
153
154
        $result = $conn->query($sql);
155
        $num_rows = $result->num_rows;
156
157
        if ($num_rows >= 1) {
158
            while ($rows = $result->fetch_assoc()) {
159
                $charID = $rows['characterID'];
160
                $discordID = $rows['discordID'];
161
                $member = $guild->members->get("id", $discordID);
162
                $eveName = $rows['eveName'];
163
                $roles = $member->roles;
164
165
                if ($this->config["plugins"]["auth"]["nameEnforce"] == "true") {
166
                    $nick = $eveName;
167
                    $member->setNickname($nick);
168
                }
169
170
                $url = "https://api.eveonline.com/eve/CharacterAffiliation.xml.aspx?ids=$charID";
171
                $xml = makeApiRequest($url);
172
                // Stop the process if the api is throwing an error
173
                if (is_null($xml)){
174
                    $this->logger->addInfo("{$eveName} cannot be authed, API issues detected.");
175
                    return null;
176
                }
177
                if ($xml->result->rowset->row[0]) {
178
                    foreach ($xml->result->rowset->row as $character) {
179
180
                        if ($character->attributes()->allianceID != $allyID && $character->attributes()->corporationID != $corpID) {
181
                            foreach ($roles as $role) {
182
                                $member->removeRole($role);
183
                                $guild->members->save($member);
184
                            }
185
186
                            $statsURL = "https://api.eveonline.com/eve/CharacterName.xml.aspx?ids=" . urlencode($character->attributes()->corporationID) . "/";
187
                            $stats = makeApiRequest($statsURL);
188
                            foreach ($stats->result->rowset->row as $corporation) {
189
                                $corporationName = $corporation->attributes()->name;
190
                            }
191
192
                            // Send the info to the channel
193
                            $msg = "{$eveName} roles have been removed, user is now a member of **{$corporationName}**.";
0 ignored issues
show
Bug introduced by
The variable $corporationName does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
194
                            $channelID = $toDiscordChannel;
195
                            $channel = $guild->channels->get('id', $channelID);
196
                            $channel->sendMessage($msg, false);
197
                            $this->logger->addInfo("{$eveName} roles ({$role}) have been removed, user is now a member of **{$corporationName}**.");
0 ignored issues
show
Bug introduced by
The variable $role does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
198
199
                            $sql = "UPDATE authUsers SET active='no' WHERE discordID='$discordID'";
200
                            $conn->query($sql);
201
202
                        }
203
                    }
204
                }
205
            }
206
            $this->logger->addInfo("All users successfully authed.");
207
            $nextCheck = time() + 7200;
208
            setPermCache("authLastChecked", $nextCheck);
209
            $cacheTimer = gmdate("Y-m-d H:i:s", $nextCheck);
210
            $this->logger->addInfo("Next auth and name check at {$cacheTimer} EVE");
211
            return null;
212
        }
213
        $this->logger->addInfo("No users found in database.");
214
        $nextCheck = time() + 7200;
215
        setPermCache("authLastChecked", $nextCheck);
216
        $cacheTimer = gmdate("Y-m-d H:i:s", $nextCheck);
217
        $this->logger->addInfo("Next auth and name check at {$cacheTimer} EVE");
218
        return null;
219
    }
220
221
    /**
222
     * @param $msgData
223
     */
224
    function onMessage($msgData)
0 ignored issues
show
Unused Code introduced by
The parameter $msgData 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...
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
225
    {
226
    }
227
}
228