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

getKillmails   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 192
Duplicated Lines 11.46 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 22
loc 192
rs 9.2
c 0
b 0
f 0
wmc 34
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 10 10 1
B tick() 0 23 5
F getKM() 12 87 20
C getBigKM() 0 50 8

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
 * 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 getKillmails
30
 */
31
class getKillmails
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...
32
{
33
    public $config;
34
    public $db;
35
    public $discord;
36
    public $channelConfig;
37
    public $lastCheck = 0;
38
    public $logger;
39
    public $groupConfig;
40
41
    /**
42
     * @param $config
43
     * @param $discord
44
     * @param $logger
45
     */
46 View Code Duplication
    public function init($config, $discord, $logger)
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...
47
    {
48
        $this->config = $config;
49
        $this->discord = $discord;
50
        $this->logger = $logger;
51
        $this->groupConfig = $config['plugins']['getKillmails']['groupConfig'];
52
        $this->guild = $config['bot']['guild'];
0 ignored issues
show
Bug introduced by
The property guild does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
53
        //Refresh check at bot start
54
        setPermCache('killmailCheck', time() - 5);
55
    }
56
57
    /**
58
     *
59
     */
60
    public function tick()
61
    {
62
        // What was the servers last reported state
63
        $lastStatus = getPermCache('serverState');
64
        if ($lastStatus === 'online') {
65
            $lastChecked = getPermCache('killmailCheck');
66
            if ($lastChecked <= time()) {
67
                //check if user is still using the old config
68
                if (null === $this->groupConfig) {
69
                    $this->logger->addError('Killmails: UPDATE YOUR CONFIG TO RECEIVE KILLMAILS');
70
                    setPermCache('killmailCheck', time() + 600);
71
                    return null;
72
                }
73
                $this->logger->addInfo('Killmails: Checking for new killmails.');
74
                $this->getKM();
75
                setPermCache('killmailCheck', time() + 600);
76
                if (@$this->config['plugins']['getKillmails']['bigKills']['shareBigKills'] === 'true') {
77
                    $this->logger->addInfo('Killmails: Checking for 10b+ kills.');
78
                    $this->getBigKM();
79
                }
80
            }
81
        }
82
    }
83
84
    private function getKM()
85
    {
86
        foreach ($this->groupConfig as $kmGroup) {
87
            $killID = getPermCache("{$kmGroup['name']}newestKillmailID");
88
            //check if start id is greater than current id and if it is set
89
            if ($kmGroup['startMail'] > $killID || null === $killID) {
90
                $killID = $kmGroup['startMail'];
91
            }
92 View Code Duplication
            if ($kmGroup['allianceID'] == '0' & $kmGroup['lossMails'] === 'true') {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: ($kmGroup['allianceID'] ...'lossMails'] === 'true', Probably Intended Meaning: $kmGroup['allianceID'] =...lossMails'] === 'true')

When comparing the result of a bit operation, we suggest to add explicit parenthesis and not to rely on PHP’s built-in operator precedence to ensure the code behaves as intended and to make it more readable.

Let’s take a look at these examples:

// Returns always int(0).
return 0 === $foo & 4;
return (0 === $foo) & 4;

// More likely intended return: true/false
return 0 === ($foo & 4);
Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
93
                $url = "https://zkillboard.com/api/no-attackers/no-items/orderDirection/asc/afterKillID/{$killID}/corporationID/{$kmGroup['corpID']}/";
94
            }
95 View Code Duplication
            if ($kmGroup['allianceID'] == '0' & $kmGroup['lossMails'] === 'false') {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: ($kmGroup['allianceID'] ...lossMails'] === 'false', Probably Intended Meaning: $kmGroup['allianceID'] =...ossMails'] === 'false')

When comparing the result of a bit operation, we suggest to add explicit parenthesis and not to rely on PHP’s built-in operator precedence to ensure the code behaves as intended and to make it more readable.

Let’s take a look at these examples:

// Returns always int(0).
return 0 === $foo & 4;
return (0 === $foo) & 4;

// More likely intended return: true/false
return 0 === ($foo & 4);
Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
96
                $url = "https://zkillboard.com/api/no-attackers/no-items/kills/orderDirection/asc/afterKillID/{$killID}/corporationID/{$kmGroup['corpID']}/";
97
            }
98 View Code Duplication
            if ($kmGroup['allianceID'] != '0' & $kmGroup['lossMails'] === 'true') {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: ($kmGroup['allianceID'] ...'lossMails'] === 'true', Probably Intended Meaning: $kmGroup['allianceID'] !...lossMails'] === 'true')

When comparing the result of a bit operation, we suggest to add explicit parenthesis and not to rely on PHP’s built-in operator precedence to ensure the code behaves as intended and to make it more readable.

Let’s take a look at these examples:

// Returns always int(0).
return 0 === $foo & 4;
return (0 === $foo) & 4;

// More likely intended return: true/false
return 0 === ($foo & 4);
Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
99
                $url = "https://zkillboard.com/api/no-attackers/no-items/orderDirection/asc/afterKillID/{$killID}/allianceID/{$kmGroup['allianceID']}/";
100
            }
101 View Code Duplication
            if ($kmGroup['allianceID'] != '0' & $kmGroup['lossMails'] === 'false') {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: ($kmGroup['allianceID'] ...lossMails'] === 'false', Probably Intended Meaning: $kmGroup['allianceID'] !...ossMails'] === 'false')

When comparing the result of a bit operation, we suggest to add explicit parenthesis and not to rely on PHP’s built-in operator precedence to ensure the code behaves as intended and to make it more readable.

Let’s take a look at these examples:

// Returns always int(0).
return 0 === $foo & 4;
return (0 === $foo) & 4;

// More likely intended return: true/false
return 0 === ($foo & 4);
Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
102
                $url = "https://zkillboard.com/api/no-attackers/no-items/kills/orderDirection/asc/afterKillID/{$killID}/allianceID/{$kmGroup['allianceID']}/";
103
            }
104
105
            if (!isset($url)) { // Make sure it's always set.
106
                $this->logger->addInfo('Killmails: ERROR - Ensure your config file is setup correctly for killmails.');
107
                return null;
108
            }
109
110
            $kills = json_decode(downloadData($url), true);
111
            $i = 0;
112
            if (isset($kills)) {
113
                foreach ($kills as $kill) {
114
                    if ($i < 10) {
115
                        //if big kill isn't set, disable it
116
                        if (null === $kmGroup['bigKill']) {
117
                            $kmGroup['bigKill'] = 99999999999999999999999999;
118
                        }
119
                        $killID = $kill['killID'];
120
                        $channelID = $kmGroup['channel'];
121
                        $solarSystemID = $kill['solarSystemID'];
122
                        $systemName = systemName($solarSystemID);
123
                        $killTime = $kill['killTime'];
124
                        $victimAllianceName = $kill['victim']['allianceName'];
125
                        $victimName = $kill['victim']['characterName'];
126
                        $victimCorpName = $kill['victim']['corporationName'];
127
                        $victimShipID = $kill['victim']['shipTypeID'];
128
                        $shipName = apiTypeName($victimShipID);
129
                        $rawValue = $kill['zkb']['totalValue'];
130
                        //Check if killmail meets minimum value
131
                        if (isset($kmGroup['minimumValue'])) {
132
                            if ($rawValue < $kmGroup['minimumValue']) {
133
                                $this->logger->addInfo("Killmails: Mail {$killID} ignored for not meeting the minimum value required.");
134
                                setPermCache("{$kmGroup['name']}newestKillmailID", $killID);
135
                                continue;
136
                            }
137
                        }
138
                        $totalValue = number_format($kill['zkb']['totalValue']);
139
                        // Check if it's a structure
140
                        if ($victimName !== '') {
141
                            if ($rawValue >= $kmGroup['bigKill']) {
142
                                $channelID = $kmGroup['bigKillChannel'];
143
                                $msg = "@here \n :warning:***Expensive Killmail***:warning: \n **{$killTime}**\n\n**{$shipName}** worth **{$totalValue} ISK** flown by **{$victimName}** of (***{$victimCorpName}|{$victimAllianceName}***) killed in {$systemName}\nhttps://zkillboard.com/kill/{$killID}/";
144
                            } elseif ($rawValue <= $kmGroup['bigKill']) {
145
                                $msg = "**{$killTime}**\n\n**{$shipName}** worth **{$totalValue} ISK** flown by **{$victimName}** of (***{$victimCorpName}|{$victimAllianceName}***) killed in {$systemName}\nhttps://zkillboard.com/kill/{$killID}/";
146
                            }
147
                        } elseif ($victimName === '') {
148
                            $msg = "**{$killTime}**\n\n**{$shipName}** worth **{$totalValue} ISK** owned by (***{$victimCorpName}|{$victimAllianceName}***) killed in {$systemName}\nhttps://zkillboard.com/kill/{$killID}/";
149
                        }
150
151
                        if (!isset($msg)) { // Make sure it's always set.
152
                            return null;
153
                        }
154
                        queueMessage($msg, $channelID, $this->guild);
155
                        $this->logger->addInfo("Killmails: Mail {$killID} queued.");
156
157
                        $i++;
158
                    } else {
159
                        $updatedID = getPermCache("{$kmGroup['name']}newestKillmailID");
160
                        $this->logger->addInfo("Killmails: Kill posting cap reached, newest kill id for {$kmGroup['name']} is {$updatedID}");
161
                        break;
162
                    }
163
                }
164
                setPermCache("{$kmGroup['name']}newestKillmailID", $killID);
165
            }
166
            $updatedID = getPermCache("{$kmGroup['name']}newestKillmailID");
167
            $this->logger->addInfo("Killmails: All kills posted, newest kill id for {$kmGroup['name']} is {$updatedID}");
168
            continue;
169
        }
170
    }
171
172
    private function getBigKM()
173
    {
174
        $killID = getPermCache('bigKillNewestKillmailID');
175
        if ($this->config['plugins']['getKillmails']['bigKills']['bigKillStartID'] > $killID || null === $killID) {
176
            $killID = $this->config['plugins']['getKillmails']['bigKills']['bigKillStartID'];
177
        }
178
179
        $url = "https://zkillboard.com/api/kills/orderDirection/asc/iskValue/10000000000/afterKillID/{$killID}/";
180
181
        $kills = json_decode(downloadData($url), true);
182
        $i = 0;
183
        if (isset($kills)) {
184
            foreach ($kills as $kill) {
185
                if ($i < 5) {
186
                    $killID = $kill['killID'];
187
                    $channelID = $this->config['plugins']['getKillmails']['bigKills']['bigKillChannel'];
188
                    $solarSystemID = $kill['solarSystemID'];
189
                    $systemName = systemName($solarSystemID);
190
                    $killTime = $kill['killTime'];
191
                    $victimAllianceName = $kill['victim']['allianceName'];
192
                    $victimName = $kill['victim']['characterName'];
193
                    $victimCorpName = $kill['victim']['corporationName'];
194
                    $victimShipID = $kill['victim']['shipTypeID'];
195
                    $shipName = apiTypeName($victimShipID);
196
                    $totalValue = number_format($kill['zkb']['totalValue']);
197
                    // Check if it's a structure
198
                    if ($victimName !== '') {
199
                        $msg = "**10b+ Kill Reported**\n\n**{$killTime}**\n\n**{$shipName}** worth **{$totalValue} ISK** flown by **{$victimName}** of (***{$victimCorpName}|{$victimAllianceName}***) killed in {$systemName}\nhttps://zkillboard.com/kill/{$killID}/";
200
                    } else {
201
                        $msg = "**10b+ Kill Reported**\n\n**{$killTime}**\n\n**{$shipName}** worth **{$totalValue} ISK** owned by (***{$victimCorpName}|{$victimAllianceName}***) killed in {$systemName}\nhttps://zkillboard.com/kill/{$killID}/";
202
                    }
203
                    if (!isset($msg)) { // Make sure it's always set.
204
                        return null;
205
                    }
206
                    queueMessage($msg, $channelID, $this->guild);
207
                    $this->logger->addInfo("Killmails: Mail {$killID} queued.");
208
209
                    $i++;
210
                } else {
211
                    $updatedID = getPermCache('bigKillNewestKillmailID');
212
                    $this->logger->addInfo("Killmails: bigKill posting cap reached, newest kill id is {$updatedID}");
213
                    break;
214
                }
215
            }
216
            $newID = $killID++;
217
            setPermCache('bigKillNewestKillmailID', $newID);
218
        }
219
        $updatedID = getPermCache('bigKillNewestKillmailID');
220
        $this->logger->addInfo("Killmails: All bigKills posted, newest kill id is {$updatedID}");
221
    }
222
}
223