Passed
Pull Request — master (#26)
by Bob
03:59
created

twitterOutput::tick()   B

Complexity

Conditions 8
Paths 39

Size

Total Lines 55
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 8
eloc 34
c 5
b 1
f 0
nc 39
nop 0
dl 0
loc 55
rs 7.4033

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
 * 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 twitterOutput
30
 */
31
class twitterOutput
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
    /**
34
     * @var
35
     */
36
    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...
37
    /**
38
     * @var
39
     */
40
    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...
41
    /**
42
     * @var
43
     */
44
    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...
45
46
    /**
47
     * @var
48
     */
49
    var $twitter;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $twitter.

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
52
     */
53
    var $lastCheck;
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 $lastID;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $lastID.

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
     * @var
60
     */
61
    var $channelID;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $channelID.

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...
62
    /**
63
     * @var
64
     */
65
    var $maxID;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $maxID.

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...
66
67
    /**
68
     * @param $config
69
     * @param $discord
70
     * @param $logger
71
     */
72
    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...
73
    {
74
        $this->config = $config;
75
        $this->discord = $discord;
76
        $this->logger = $logger;
77
        $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...
78
        $this->twitter = new Twitter($config["twitter"]["consumerKey"], $config["twitter"]["consumerSecret"], $config["twitter"]["accessToken"], $config["twitter"]["accessTokenSecret"]);
79
        $this->lastCheck = time();
80
        $this->maxID = 0;
81
        $this->channelID = $config["plugins"]["twitterOutput"]["channelID"]; // outputs to the news channel on the 4M server
82
    }
83
84
    /**
85
     *
86
     */
87
    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...
88
    {
89
        $discord = $this->discord;
90
91
        $continue = false;
92
        $data = array();
93
        // If last check + 60 seconds is larger or equal to the current time(), we run
94
        if ($this->lastCheck <= time()) {
95
            // Fetch the last 25 twitter replies and/or searches
96
            try {
97
                $data = $this->twitter->load(Twitter::ME_AND_FRIENDS, 5);
98
                foreach ($data as $message) {
0 ignored issues
show
Bug introduced by
The expression $data of type object<stdClass>|array<integer,object<stdClass>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
99
                    $text = (array) $message->text;
100
                    $createdAt = (array) $message->created_at;
101
                    $postedBy = (array) $message->user->name;
102
                    $screenName = (array) $message->user->screen_name;
103
                    $id = (int) $message->id;
104
                    $this->lastID = getPermCache("twitterLatestID"); // get the last posted ID
105
106
                    if ($id <= $this->lastID) {
107
                        continue;
108
                    }
109
110
                    $this->maxID = max($id, $this->maxID);
111
112
                    $url = "https://twitter.com/" . $screenName[0] . "/status/" . $id;
113
                    $message = array("message" => $text[0], "postedAt" => $createdAt[0], "postedBy" => $postedBy[0], "screenName" => $screenName[0], "url" => $url . $id[0]);
114
                    $msg = "**@" . $screenName[0] . "** (" . $message["postedBy"] . ") / " . htmlspecialchars_decode($message["message"]);
115
                    $messages[$id] = $msg;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$messages was never initialized. Although not strictly required by PHP, it is generally a good practice to add $messages = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
116
117
                    $continue = true;
118
119
                    if (sizeof($data)) {
120
                        setPermCache("twitterLatestID", $this->maxID);
121
                    }
122
                }
123
            } catch (Exception $e) {
124
                //$this->logger->err("Twitter Error: " . $e->getMessage()); // Don't show there was an error, it's most likely just a rate limit
1 ignored issue
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
125
            }
126
127
            if ($continue == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
128
                ksort($messages);
129
130
                foreach ($messages as $id => $msg) {
131
                    // Send the tweets to the channel
132
                    $channelID = $this->channelID;
133
                    $guild = $discord->guilds->get('id', $this->guild);
134
                    $channel = $guild->channels->get('id', $channelID);
135
                    $channel->sendMessage($msg, false);
136
                    sleep(1); // Lets sleep for a second, so we don't rage spam
137
                }
138
            }
139
            $this->lastCheck = time() + 60;
140
        }
141
    }
142
143
    /**
144
     * @param $url
145
     * @return string
146
     */
147
    function shortenUrl($url)
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...
148
    {
149
        return file_get_contents("http://is.gd/api.php?longurl=" . $url);
150
    }
151
152
    /**
153
     * @param $msgData
154
     */
155
    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...
156
    {
157
    }
158
159
    /**
160
     * @return array
161
     */
162
    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...
163
    {
164
        return array(
165
            "name" => "",
166
            "trigger" => array(""),
167
            "information" => ""
168
        );
169
    }
170
}
171