Completed
Push — master ( a95f7d...eaa6fe )
by Danilo
02:55
created

BasicBot::processChannelPost()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 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
    public function __construct(string $token)
48
    {
49
        parent::__construct($token);
50
51
        // Add alias for entity classes
52
        class_alias('PhpBotFramework\Entities\Message', 'PhpBotFramework\Entities\EditedMessage');
53
        class_alias('PhpBotFramework\Entities\Message', 'PhpBotFramework\Entities\ChannelPost');
54
        class_alias('PhpBotFramework\Entities\Message', 'PhpBotFramework\Entities\EditedChannelPost');
55
    }
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
        // While there aren't updates to process
89
        while (empty($update = $this->getUpdates(0, 1))) {
0 ignored issues
show
Unused Code introduced by
This while loop is empty and can be removed.

This check looks for while loops that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

Consider removing the loop.

Loading history...
90
        }
91
92
        $offset = $update[0]['update_id'];
93
        $this->initCommands();
94
95
        // Process all updates
96 View Code Duplication
        while (true) {
0 ignored issues
show
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...
97
            $updates = $this->execRequest("getUpdates?offset=$offset&limit=$limit&timeout=$timeout");
98
99
            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...
100
                try {
101
                    $this->processUpdate($update);
102
                } catch (BotException $e) {
103
                    echo $e->getMessage();
104
                }
105
            }
106
107
            $offset += sizeof($updates);
108
        }
109
    }
110
111
    /** @} */
112
113
    /**
114
     * @internal
115
     * \brief Dispatch each update to the right method (processMessage, processCallbackQuery, etc).
116
     * \details Set $chat_id for each update, $text, $data and $query are set for each update that contains them.
117
     * @param array $update Reference to the update received.
118
     * @return int The id of the update processed.
119
     */
120
    protected function processUpdate(array $update) : int
121
    {
122
        static $updates_type = ['message' => 'Message',
123
            'callback_query' => 'CallbackQuery',
124
            'inline_query' => 'InlineQuery',
125
            'channel_post' => 'ChannelPost',
126
            'edited_message' => 'EditedMessage',
127
            'edited_channel_post' => 'EditedChannelPost',
128
            'chosen_inline_result' => 'ChosenInlineResult'];
129
130
        if ($this->processCommands($update)) {
131
            return $update['update_id'];
132
        }
133
134
        foreach ($updates_type as $offset => $class) {
135
            if (isset($update[$offset])) {
136
                $object_class = "PhpBotFramework\Entities\\$class";
137
                $object = new $object_class($update[$offset]);
138
139
                $this->_chat_id = $object->getChatID();
140
141
                if (method_exists($object, 'getBotParameter')) {
142
                    $var = $object->getBotParameter();
143
                    $this->{$var['var']} = $var['id'];
144
                }
145
146
                $this->{"process$class"}($object);
147
148
                return $update['update_id'];
149
            }
150
        }
151
    }
152
153
    /**
154
     * \brief Called every message received by the bot.
155
     * \details Override it to script the bot answer for each message.
156
     * <code>$chat_id</code> and <code>$text</code>, if the message contains text(use getMessageText() to access it), set inside of this function.
157
     * @param Message $message Reference to the message received.
158
     */
159
    protected function processMessage(Message $message)
160
    {
161
    }
162
163
    /**
164
     * \brief Called every callback query received by the bot.
165
     * \details Override it to script the bot answer for each callback.
166
     * <code>$chat_id</code> and <code>$data</code>, if set in the callback query(use getCallbackData() to access it) set inside of this function.
167
     * @param CallbackQuery $callback_query Reference to the callback query received.
168
     */
169
    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...
170
    {
171
    }
172
173
    /**
174
     * \brief Called every inline query received by the bot.
175
     * \details Override it to script the bot answer for each inline query.
176
     * $chat_id and $query(use getInlineQuery() to access it) set inside of this function.
177
     * @param InlineQuery $inline_query Reference to the inline query received.
178
     */
179
    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...
180
    {
181
    }
182
183
    /**
184
     * \brief Called every chosen inline result received by the bot.
185
     * \details Override it to script the bot answer for each chosen inline result.
186
     * <code>$chat_id</code> set inside of this function.
187
     * @param ChosenInlineResult $chosen_inline_result Reference to the chosen inline result received.
188
     */
189
    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...
190
    {
191
    }
192
193
    /**
194
     * \brief Called every chosen edited message received by the bot.
195
     * \details Override it to script the bot answer for each edited message.
196
     * <code>$chat_id</code> set inside of this function.
197
     * @param Message $edited_message The message edited by the user.
198
     */
199
    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...
200
    {
201
    }
202
203
    /**
204
     * \brief Called every new post in the channel where the bot is in.
205
     * \details Override it to script the bot answer for each post sent in a channel.
206
     * <code>$chat_id</code> set inside of this function.
207
     * @param Message $post The message sent in the channel.
208
     */
209
    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...
210
    {
211
    }
212
213
    /**
214
     * \brief Called every time a post get edited in the channel where the bot is in.
215
     * \details Override it to script the bot answer for each post edited  in a channel.
216
     * <code>$chat_id</code> set inside of this function.
217
     * @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...
218
     */
219
    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...
220
    {
221
    }
222
223
    /** @} */
224
}
225