Passed
Branch dev (745ef0)
by
unknown
03:03
created

twitterOutput   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 93
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
C tick() 0 51 8
A shortenUrl() 0 4 1
A init() 0 11 1
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
    public $config;
34
    public $discord;
35
    public $logger;
36
    public $guild;
37
    private $twitter;
38
    private $lastCheck;
39
    private $lastID;
40
    private $channelID;
41
    private $maxID;
42
43
    /**
44
     * @param $config
45
     * @param $discord
46
     * @param $logger
47
     */
48
    public function init($config, $discord, $logger)
49
    {
50
        $this->config = $config;
51
        $this->discord = $discord;
52
        $this->logger = $logger;
53
        $this->guild = $config['bot']['guild'];
54
        $this->twitter = new Twitter($config['twitter']['consumerKey'], $config['twitter']['consumerSecret'], $config['twitter']['accessToken'], $config['twitter']['accessTokenSecret']);
55
        $this->lastCheck = time();
56
        $this->maxID = 0;
57
        $this->channelID = $config['plugins']['twitterOutput']['channelID']; // outputs to the news channel on the 4M server
58
    }
59
60
    /**
61
     *
62
     */
63
    public function tick()
64
    {
65
        $continue = false;
66
        $data = array();
67
        // If last check + 60 seconds is larger or equal to the current time(), we run
68
        if ($this->lastCheck <= time()) {
69
            // Fetch the last 25 twitter replies and/or searches
70
            try {
71
                $data = $this->twitter->load(Twitter::ME_AND_FRIENDS, 5);
72
                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...
73
                    $text = (array) $message->text;
74
                    $createdAt = (array) $message->created_at;
75
                    $postedBy = (array) $message->user->name;
76
                    $screenName = (array) $message->user->screen_name;
77
                    $id = (int) $message->id;
78
                    $this->lastID = getPermCache('twitterLatestID'); // get the last posted ID
79
80
                    if ($id <= $this->lastID) {
81
                        continue;
82
                    }
83
84
                    $this->maxID = max($id, $this->maxID);
85
86
                    $url = 'https://twitter.com/' . $screenName[0] . '/status/' . $id;
87
                    $message = array('message' => $text[0], 'postedAt' => $createdAt[0], 'postedBy' => $postedBy[0], 'screenName' => $screenName[0], 'url' => $url . $id[0]);
88
                    $msg = '**@' . $screenName[0] . '** (' . $message['postedBy'] . ') / ' . htmlspecialchars_decode($message['message']);
89
                    $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...
90
91
                    $continue = true;
92
93
                    if (count($data)) {
94
                        setPermCache('twitterLatestID', $this->maxID);
95
                    }
96
                }
97
            } catch (Exception $e) {
98
                //$this->logger->err("Twitter Error: " . $e->getMessage()); // Don't show there was an error, it's most likely just a rate limit
99
            }
100
101
            if ($continue === true) {
102
                ksort($messages);
103
104
                foreach ($messages as $id => $msg) {
105
                    // Send the tweets to the channel
106
                    $channelID = $this->channelID;
107
                    queueMessage($msg, $channelID, $this->guild);
108
                    $this->logger->addInfo('twitterOutput: Tweet queued.');
109
                }
110
            }
111
            $this->lastCheck = time() + 60;
112
        }
113
    }
114
115
    /**
116
     * @param $url
117
     * @return string
118
     */
119
    public function shortenUrl($url)
120
    {
121
        return file_get_contents('http://is.gd/api.php?longurl=' . $url);
122
    }
123
}
124