Completed
Push — master ( 69097b...4e1c03 )
by Danilo
04:33
created

BasicBot   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 191
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 33.96%

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 3
dl 0
loc 191
ccs 18
cts 53
cp 0.3396
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A processWebhookUpdate() 0 7 1
A __construct() 0 9 1
B getUpdatesLocal() 0 25 5
B processUpdate() 0 32 5
A processMessage() 0 3 1
A processCallbackQuery() 0 3 1
A processInlineQuery() 0 3 1
A processChosenInlineResult() 0 3 1
A processEditedMessage() 0 3 1
A processChannelPost() 0 3 1
A processEditedChannelPost() 0 3 1
1
<?php
2
3
/*
4
 * This file is part of the PhpBotFramework.
5
 *
6
 * PhpBotFramework is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, version 3.
9
 *
10
 * PhpBotFramework is distributed in the hope that it will be useful, but
11
 * WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace PhpBotFramework;
20
21
use PhpBotFramework\Exceptions\BotException;
22
23
use PhpBotFramework\Entities\Message;
24
use PhpBotFramework\Entities\CallbackQuery;
25
use PhpBotFramework\Entities\ChosenInlineResult;
26
use PhpBotFramework\Entities\InlineQuery;
27
28
/**
29
 * \class Bot Bot
30
 * \brief Bot class to handle updates and commands.
31
 * \details Class Bot to handle task like API request, or more specific API method like sendMessage, editMessageText, etc..
32
 * An example of its usage is available in webhook.php
33
 *
34
 */
35
class BasicBot extends Core\CoreBot
36
{
37
    use \PhpBotFramework\Commands\CommandHandler;
38
39
    /** @internal
40
      * \brief True if the bot is using webhook? */
41
    protected $_is_webhook;
42
43
    /**
44
     * \brief Construct an empty base bot.
45
     * \details Construct a base bot that can handle updates.
46
     */
47 1
    public function __construct(string $token)
48
    {
49 1
        parent::__construct($token);
50
51
        // Add alias for entity classes
52 1
        class_alias('PhpBotFramework\Entities\Message', 'PhpBotFramework\Entities\EditedMessage');
53 1
        class_alias('PhpBotFramework\Entities\Message', 'PhpBotFramework\Entities\ChannelPost');
54 1
        class_alias('PhpBotFramework\Entities\Message', 'PhpBotFramework\Entities\EditedChannelPost');
55 1
    }
56
57
    /** @} */
58
59
    /**
60
     * \addtogroup Bot
61
     * @{
62
     */
63
64
    /**
65
     * \brief Get update and process it.
66
     * \details Call this method if user is using webhook.
67
     * It'll get bot's update from php::\input, check it and then process it using <b>processUpdate</b>.
68
     */
69
    public function processWebhookUpdate()
70
    {
71
        $this->_is_webhook = true;
72
73
        $this->initCommands();
74
        $this->processUpdate(json_decode(file_get_contents('php://input'), true));
75
    }
76
77
    /**
78
     * \brief Get updates received by the bot, and hold the offset in $offset.
79
     * \details Get the <code>update_id</code> of the first update to parse, set it in $offset and
80
     * then it start an infinite loop where it processes updates and keep $offset on the update_id of the last update received.
81
     * Each processUpdate() method call is surrounded by a try/catch.
82
     * @see getUpdates
83
     * @param int $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
84
     * @param int $timeout <i>Optional</i>. Timeout in seconds for long polling.
85
     */
86
    public function getUpdatesLocal(int $limit = 100, int $timeout = 60)
87
    {
88
        $update = [];
0 ignored issues
show
Unused Code introduced by
$update 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...
89
90
        // While there aren't updates to process
91
        while (empty($update = $this->getUpdates(0, 1)));
92
93
        $offset = $update[0]['update_id'];
94
        $this->initCommands();
95
96
        // Process all updates
97
        while (true) {
98
            $updates = $this->execRequest("getUpdates?offset=$offset&limit=$limit&timeout=$timeout");
99
100
            foreach ($updates as $key => $update) {
0 ignored issues
show
Bug introduced by
The expression $updates of type array|false 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...
101
                try {
102
                    $this->processUpdate($update);
103
                } catch (BotException $e) {
104
                    echo $e->getMessage();
105
                }
106
            }
107
108
            $offset += sizeof($updates);
109
        }
110
    }
111
112
    /** @} */
113
114
    /**
115
     * @internal
116
     * \brief Dispatch each update to the right method (processMessage, processCallbackQuery, etc).
117
     * \details Set $chat_id for each update, $text, $data and $query are set for each update that contains them.
118
     * @param array $update Reference to the update received.
119
     * @return int The id of the update processed.
120
     */
121 3
    protected function processUpdate(array $update) : int
122
    {
123 3
        static $updates_type = ['message' => 'Message',
124
            'callback_query' => 'CallbackQuery',
125
            'inline_query' => 'InlineQuery',
126
            'channel_post' => 'ChannelPost',
127
            'edited_message' => 'EditedMessage',
128
            'edited_channel_post' => 'EditedChannelPost',
129
            'chosen_inline_result' => 'ChosenInlineResult'];
130
131 3
        if ($this->processCommands($update)) {
132 1
            return $update['update_id'];
133
        }
134
135 2
        foreach ($updates_type as $offset => $class) {
136 2
            if (isset($update[$offset])) {
137 2
                $object_class = "PhpBotFramework\Entities\\$class";
138 2
                $object = new $object_class($update[$offset]);
139
140 2
                $this->_chat_id = $object->getChatID();
141
142 2
                if (method_exists($object, 'getBotParameter')) {
143
                    $var = $object->getBotParameter();
144
                    $this->{$var['var']} = $var['id'];
145
                }
146
147 2
                $this->{"process$class"}($object);
148
149 2
                return $update['update_id'];
150
            }
151
        }
152
    }
153
154
    /**
155
     * \brief Called every message received by the bot.
156
     * \details Override it to script the bot answer for each message.
157
     * <code>$chat_id</code> and <code>$text</code>, if the message contains text(use getMessageText() to access it), set inside of this function.
158
     * @param Message $message Reference to the message received.
159
     */
160
    protected function processMessage(Message $message)
161
    {
162
    }
163
164
    /**
165
     * \brief Called every callback query received by the bot.
166
     * \details Override it to script the bot answer for each callback.
167
     * <code>$chat_id</code> and <code>$data</code>, if set in the callback query(use getCallbackData() to access it) set inside of this function.
168
     * @param CallbackQuery $callback_query Reference to the callback query received.
169
     */
170
    protected function processCallbackQuery(CallbackQuery $callback_query)
0 ignored issues
show
Unused Code introduced by
The parameter $callback_query 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...
171
    {
172
    }
173
174
    /**
175
     * \brief Called every inline query received by the bot.
176
     * \details Override it to script the bot answer for each inline query.
177
     * $chat_id and $query(use getInlineQuery() to access it) set inside of this function.
178
     * @param InlineQuery $inline_query Reference to the inline query received.
179
     */
180
    protected function processInlineQuery(InlineQuery $inline_query)
0 ignored issues
show
Unused Code introduced by
The parameter $inline_query 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...
181
    {
182
    }
183
184
    /**
185
     * \brief Called every chosen inline result received by the bot.
186
     * \details Override it to script the bot answer for each chosen inline result.
187
     * <code>$chat_id</code> set inside of this function.
188
     * @param ChosenInlineResult $chosen_inline_result Reference to the chosen inline result received.
189
     */
190
    protected function processChosenInlineResult(ChosenInlineResult $chosen_inline_result)
0 ignored issues
show
Unused Code introduced by
The parameter $chosen_inline_result 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...
191
    {
192
    }
193
194
    /**
195
     * \brief Called every chosen edited message received by the bot.
196
     * \details Override it to script the bot answer for each edited message.
197
     * <code>$chat_id</code> set inside of this function.
198
     * @param Message $edited_message The message edited by the user.
199
     */
200
    protected function processEditedMessage(Message $edited_message)
0 ignored issues
show
Unused Code introduced by
The parameter $edited_message 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...
201
    {
202
    }
203
204
    /**
205
     * \brief Called every new post in the channel where the bot is in.
206
     * \details Override it to script the bot answer for each post sent in a channel.
207
     * <code>$chat_id</code> set inside of this function.
208
     * @param Message $post The message sent in the channel.
209
     */
210
    protected function processChannelPost(Message $post)
0 ignored issues
show
Unused Code introduced by
The parameter $post 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...
211
    {
212
    }
213
214
    /**
215
     * \brief Called every time a post get edited in the channel where the bot is in.
216
     * \details Override it to script the bot answer for each post edited  in a channel.
217
     * <code>$chat_id</code> set inside of this function.
218
     * @param Message $post The message edited in the channel.
0 ignored issues
show
Bug introduced by
There is no parameter named $post. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
219
     */
220
    protected function processEditedChannelPost(Message $edited_post)
0 ignored issues
show
Unused Code introduced by
The parameter $edited_post 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...
221
    {
222
    }
223
224
    /** @} */
225
}
226