Completed
Push — master ( 549b3b...080752 )
by Danilo
15:29
created

LongPolling::getUpdateOffsetRedis()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 8
cp 0
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 10
nc 2
nop 1
crap 12
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\Database;
20
21
trait LongPolling
22
{
23
24
    abstract public function getUpdates(int $offset = 0, int $limit = 100, int $timeout = 60);
25
26
    abstract protected function initCommands();
27
28
    /**
29
     * \addtogroup Bot
30
     * @{
31
     */
32
33
    /** Redis connection. */
34
    public $redis;
35
36
    /** Pdo connection to the database. */
37
    public $pdo;
38
39
    /**
40
     * \addtogroup LongPollingDatabase Long polling With Database
41
     * \brief Use getUpdates saving and getting offset in redis/sql-database.
42
     * @{
43
     */
44
45
    /**
46
     * \brief (<i>Internal</i>)Get first update offset in redis.
47
     * \details Called by getUpdatesRedis to get the offset saved in redis or to get it from telegram and save it in redis.
48
     * @param $offset_key Name of the variable where the offset is saved on Redis
49
     * @return Id of the first update to process.
50
     */
51
    protected function getUpdateOffsetRedis(string $offset_key) : int
52
    {
53
54
        // If offset is already set in redis
55
        if ($this->redis->exists($offset_key)) {
56
            // return the value saved
57
            return $this->redis->get($offset_key);
58
59
            // Else get the offset from the id from the first update received
60
        } else {
61
            do {
62
                $update = $this->getUpdates(0, 1);
63
            } while (empty($update));
64
65
            $offset = $update[0]['update_id'];
66
67
            $this->redis->set($offset_key, $offset);
68
69
            return $offset_key;
70
        }
71
    }
72
73
    /**
74
     * \brief Get updates received by the bot, using redis to save and get the last offset.
75
     * \details It check if an offset exists on redis, then get it, or call getUpdates to set it.
76
     * Then it start an infinite loop where it process updates and update the offset on redis.
77
     * Each update is surrounded by a try/catch.
78
     * @see getUpdates
79
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
80
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
81
     * @param $offset_key <i>Optional</i>. Name of the variable where the offset is saved on Redis
82
     */
83
    public function getUpdatesRedis(int $limit = 100, int $timeout = 60, string $offset_key = 'offset')
84
    {
85
86
        // Check redis connection
87
        if (!isset($this->redis)) {
88
            throw new BotException("Redis connection is not set");
89
        }
90
91
        $offset = $this->getUpdateOffsetRedis();
0 ignored issues
show
Bug introduced by
The call to getUpdateOffsetRedis() misses a required argument $offset_key.

This check looks for function calls that miss required arguments.

Loading history...
92
93
        $this->initCommands();
94
95
         // Process all updates received
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->getUpdates($offset, $limit, $timeout);
98
99
            // Parse all updates received
100
            foreach ($updates as $key => $update) {
101
                try {
102
                    $this->processUpdate($update);
0 ignored issues
show
Bug introduced by
It seems like processUpdate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
103
                } catch (BotException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Database\BotException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
104
                    echo $e->getMessage();
105
                }
106
            }
107
108
            // Update the offset in redis
109
            $this->redis->set($offset_key, $offset + count($updates));
110
        }
111
    }
112
113
    /**
114
     * \brief (<i>Internal</i>) Get first update offset in database.
115
     * \details Called by getUpdatesDatabase to get the offset saved in database or to get it from telegram and save it in database.
116
     * @param $table_name Name of the table where offset is saved in the database
117
     * @param $column_name Name of the column where the offset is saved in the database
118
     * @return Id of the first update to process.
119
     */
120
    protected function getUpdateOffsetDatabase(string $table_name, string $column_name) : int
121
    {
122
123
        // Get the offset from the database
124
        $sth = $this->pdo->prepare('SELECT ' . $column_name . ' FROM ' . $table_name);
125
126
        try {
127
            $sth->execute();
128
        } catch (PDOException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Database\PDOException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
129
            echo $e->getMessage();
130
        }
131
132
        $offset = $sth->fetchColumn();
133
134
        $sth = null;
0 ignored issues
show
Unused Code introduced by
$sth 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...
135
136
        // Get the offset from the first update to update
137
        if ($offset === false) {
138
            do {
139
                $update = $this->getUpdates(0, 1);
140
            } while (empty($update));
141
142
            $offset = $update[0]['update_id'];
143
        }
144
145
        return $offset;
146
    }
147
148
    /**
149
     * \brief Get updates received by the bot, using the sql database to store and get the last offset.
150
     * \details It check if an offset exists on redis, then get it, or call getUpdates to set it.
151
     * Then it start an infinite loop where it process updates and update the offset on redis.
152
     * Each update is surrounded by a try/catch.
153
     * @see getUpdates
154
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
155
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
156
     * @param $table_name <i>Optional</i>. Name of the table where offset is saved in the database
157
     * @param $column_name <i>Optional</i>. Name of the column where the offset is saved in the database
158
     */
159
    public function getUpdatesDatabase(int $limit = 100, int $timeout = 0, string $table_name = 'telegram', string $column_name = 'bot_offset')
160
    {
161
162
        if (!isset($this->_database)) {
163
            throw new BotException("Database connection is not set");
164
        }
165
166
        // Get offset from database
167
        $this->getUpdateOffsetDatabase($table_name, $column_name);
168
169
        $this->initCommands();
170
171
        // Prepare the query for updating the offset in the database
172
        $sth = $this->pdo->prepare('UPDATE "' . $table_name . '" SET "' . $column_name . '" = :new_offset');
173
174
        while (true) {
175
            $updates = $this->getUpdates($offset, $limit, $timeout);
0 ignored issues
show
Bug introduced by
The variable $offset does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
176
177
            foreach ($updates as $key => $update) {
178
                try {
179
                    $this->processUpdate($update);
0 ignored issues
show
Bug introduced by
It seems like processUpdate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
180
                } catch (BotException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Database\BotException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
181
                    echo $e->getMessage();
182
                }
183
            }
184
185
            // Update the offset on the database
186
            $sth->bindParam(':new_offset', $offset + sizeof($updates));
187
            $sth->execute();
188
        }
189
    }
190
191
    /** @} */
192
193
    /** @} */
194
}
195