Passed
Pull Request — master (#106)
by Bob
03:51
created

auth::onMessage()   F

Complexity

Conditions 30
Paths 729

Size

Total Lines 122
Code Lines 81

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 30
eloc 81
nc 729
nop 2
dl 0
loc 122
rs 2.1481
c 0
b 0
f 0

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
use discord\discord;
26
27
/**
28
 * Class auth
29
 */
30
class auth
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...
31
{
32
    public $config;
33
    public $discord;
34
    public $logger;
35
    private $excludeChannel;
36
    private $nameEnforce;
37
    private $db;
38
    private $dbUser;
39
    private $dbPass;
40
    private $dbName;
41
    private $ssoUrl;
42
    private $corpTickers;
43
    private $authGroups;
44
    private $guild;
45
46
    /**
47
     * @param $config
48
     * @param $discord
49
     * @param $logger
50
     */
51
    public function init($config, $discord, $logger)
52
    {
53
        $this->config = $config;
54
        $this->discord = $discord;
55
        $this->logger = $logger;
56
        $this->db = $config['database']['host'];
57
        $this->dbUser = $config['database']['user'];
58
        $this->dbPass = $config['database']['pass'];
59
        $this->dbName = $config['database']['database'];
60
        $this->corpTickers = $config['plugins']['auth']['corpTickers'];
61
        $this->nameEnforce = $config['plugins']['auth']['nameEnforce'];
62
        $this->ssoUrl = $config['plugins']['auth']['url'];
63
        $this->excludeChannel = $this->config['bot']['restrictedChannels'];
64
        $this->authGroups = $config['plugins']['auth']['authGroups'];
65
        $this->guild = $config['bot']['guild'];
66
    }
67
68
    /**
69
     * @param $msgData
70
     * @param $message
71
     * @return null
72
     */
73
    public function onMessage($msgData, $message)
74
    {
75
        $channelID = (int) $msgData['message']['channelID'];
76
77
        if (in_array($channelID, $this->excludeChannel, true)) {
78
            return null;
79
        }
80
81
        $this->message = $message;
82
        $userID = $msgData['message']['fromID'];
83
        $userName = $msgData['message']['from'];
84
        $message = $msgData['message']['message'];
85
        $channelInfo = $this->message->channel;
86
        $guildID = $channelInfo[@guild_id];
87
        $data = command($message, $this->information()['trigger'], $this->config['bot']['trigger']);
88
        if (isset($data['trigger'])) {
89
            if (isset($this->config['bot']['primary'])) {
90
                if ($guildID != $this->config['bot']['primary']) {
91
                    $this->message->reply('**Failure:** The auth code your attempting to use is for another discord server');
92
                    return null;
93
                }
94
95
            }
96
            // If config is outdated
97
            if (null === $this->authGroups) {
98
                $this->message->reply('**Failure:** Please update the bots config to the latest version.');
99
                return null;
100
            }
101
102
            $code = $data['messageString'];
103
            $result = selectPending($this->db, $this->dbUser, $this->dbPass, $this->dbName, $code);
104
105
            if (strlen($code) < 12) {
106
                $this->message->reply('Invalid Code, check ' . $this->config['bot']['trigger'] . 'help auth for more info.');
107
                return null;
108
            }
109
110
            while ($rows = $result->fetch_assoc()) {
111
                $charID = (int) $rows['characterID'];
112
                $corpID = (int) $rows['corporationID'];
113
                $allianceID = (int) $rows['allianceID'];
114
115
                //If corp is new store in DB
116
                $corpInfo = getCorpInfo($corpID);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $corpInfo is correct as getCorpInfo($corpID) (which targets getCorpInfo()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
117
                if (null === $corpInfo) {
118
                    $corpDetails = corpDetails($corpID);
119
                    $corpTicker = $corpDetails['ticker'];
120
                    $corpName = corpName($corpID);
121
                    addCorpInfo($corpID, $corpTicker, $corpName);
122
                } else {
123
                    $corpTicker = $corpInfo['corpTicker'];
124
                }
125
126
                //Add corp ticker to name
127
                if ($this->corpTickers === 'true') {
128
                    $setTicker = 1;
129
                }
130
131
                //Set eve name if nameCheck is true
132
                if ($this->nameEnforce === 'true') {
133
                    $nameEnforce = 1;
134
                }
135
136
                $allianceRoleSet = 0;
137
                $corpRoleSet = 0;
138
139
                $roles = @$this->message->channel->guild->roles;
140
                $member = @$this->message->channel->guild->members->get('id', $userID);
141
                $eveName = characterName($charID);
142
                foreach ($this->authGroups as $authGroup) {
143
                    //Check if corpID matches
144
                    if ($corpID === $authGroup['corpID']) {
145
                        foreach ($roles as $role) {
146
                            if ((string)$role->name === (string)$authGroup['corpMemberRole']) {
147
                                $member->addRole($role);
148
                                $corpRoleSet = 1;
149
                            }
150
                        }
151
                    }
152
                    //Check if allianceID matches
153
                    if ($allianceID === $authGroup['allianceID'] && $authGroup['allianceID'] != 0) {
154
                        foreach ($roles as $role) {
155
                            if ((string)$role->name === (string)$authGroup['allyMemberRole']) {
156
                                $member->addRole($role);
157
                                $allianceRoleSet = 1;
158
                            }
159
                        }
160
                    }
161
                    if ($allianceRoleSet === 1 || $corpRoleSet === 1) {
162
                        $guild = $this->discord->guilds->get('id', $guildID);
163
                        insertUser($this->db, $this->dbUser, $this->dbPass, $this->dbName, $userID, $charID, $eveName, 'corp');
164
                        disableReg($this->db, $this->dbUser, $this->dbPass, $this->dbName, $code);
165
                        $msg = ":white_check_mark: **Success:** {$userName} has been successfully authed.";
166
                        $this->logger->addInfo("auth: {$eveName} authed");
167
                        $this->message->reply($msg);
168
                        //Add ticker if set and change name if nameEnforce is on
169
                        if (isset($setTicker) || isset($nameEnforce)) {
170
                            if (isset($setTicker) && isset($nameEnforce)) {
171
                                $nick = "[{$corpTicker}] {$eveName}";
172
                            } elseif (null === $setTicker && isset($nameEnforce)) {
173
                                $nick = "{$eveName}";
174
                            } elseif (isset($setTicker) && !isset($nameEnforce)) {
175
                                $nick = "[{$corpTicker}] {$userName}";
176
                            }
177
                        }
178
                        if (null !== $nick) {
179
                            queueRename($userID, $nick, $this->guild);
0 ignored issues
show
Bug introduced by
The variable $nick 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...
180
                        }
181
                        $guild->members->save($member);
182
                        return null;
183
                    }
184
                }
185
                $this->message->reply('**Failure:** There are no roles available for your corp/alliance.');
186
                $this->logger->addInfo('Auth: User was denied due to not being in the correct corp or alliance ' . $eveName);
187
                return null;
188
            }
189
            $this->message->reply('**Failure:** There was an issue with your code.');
190
            $this->logger->addInfo('Auth: User was denied due to the code being invalid ' . $userName);
191
            return null;
192
        }
193
        return null;
194
    }
195
196
    /**
197
     * @return array
198
     */
199 View Code Duplication
    public function information()
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...
200
    {
201
        return array(
202
            'name' => 'auth',
203
            'trigger' => array($this->config['bot']['trigger'] . 'auth'),
204
            'information' => 'SSO based auth system. ' . $this->ssoUrl . ' Visit the link and login with your main EVE account, select the correct character, and put the !auth <string> you receive in chat.'
205
        );
206
    }
207
}
208