Completed
Push — master ( ed6650...694f1b )
by Danilo
02:12
created

LongPolling   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 201
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

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

6 Methods

Rating   Name   Duplication   Size   Complexity  
getUpdates() 0 1 ?
initCommands() 0 1 ?
B getUpdateOffsetRedis() 0 26 3
B getUpdatesRedis() 0 39 5
B getUpdateOffsetDatabase() 0 35 4
B getUpdatesDatabase() 0 41 5
1
<?php
2
3
namespace PhpBotFramework\Database;
4
5
trait LongPolling {
6
7
    abstract public function getUpdates(int $offset = 0, int $limit = 100, int $timeout = 60);
8
9
    abstract protected function initCommands();
10
11
    /**
12
     * \addtogroup Bot
13
     * @{
14
     */
15
16
    /**
17
     * \addtogroup LongPollingDatabase Long polling With Database
18
     * \brief Use getUpdates saving and getting offset in redis/sql-database.
19
     * @{
20
     */
21
22
    /**
23
     * \brief (<i>Internal</i>)Get first update offset in redis.
24
     * \details Called by getUpdatesRedis to get the offset saved in redis or to get it from telegram and save it in redis.
25
     * @param $offset_key Name of the variable where the offset is saved on Redis
26
     * @return Id of the first update to process.
27
     */
28
    protected function getUpdateOffsetRedis(string $offset_key) : int {
29
30
        // If offset is already set in redis
31
        if ($this->redis->exists($offset_key)) {
32
33
            // return the value saved
34
            return $this->redis->get($offset_key);
0 ignored issues
show
Bug introduced by
The property redis 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...
35
36
            // Else get the offset from the id from the first update received
37
        } else {
38
39
            do {
40
41
                $update = $this->getUpdates(0, 1);
42
43
            } while (empty($update));
44
45
            $offset = $update[0]['update_id'];
46
47
            $this->redis->set($offset_key, $offset);
48
49
            return $offset_key;
50
51
        }
52
53
    }
54
55
    /**
56
     * \brief Get updates received by the bot, using redis to save and get the last offset.
57
     * \details It check if an offset exists on redis, then get it, or call getUpdates to set it.
58
     * Then it start an infinite loop where it process updates and update the offset on redis.
59
     * Each update is surrounded by a try/catch.
60
     * @see getUpdates
61
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
62
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
63
     * @param $offset_key <i>Optional</i>. Name of the variable where the offset is saved on Redis
64
     */
65
    public function getUpdatesRedis(int $limit = 100, int $timeout = 60, string $offset_key = 'offset') {
66
67
        // Check redis connection
68
        if (!isset($this->redis)) {
69
70
            throw new BotException("Redis connection is not set");
71
72
        }
73
74
        $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...
75
76
        $this->initCommands();
77
78
         // Process all updates received
79
        while (true) {
80
81
            $updates = $this->getUpdates($offset, $limit, $timeout);
82
83
            // Parse all updates received
84
            foreach ($updates as $key => $update) {
85
86
                try {
87
88
                    $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...
89
90
                } 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...
91
92
                    echo $e->getMessage();
93
94
                }
95
96
            }
97
98
            // Update the offset in redis
99
            $this->redis->set($offset_key, $offset + count($updates));
100
101
        }
102
103
    }
104
105
    /**
106
     * \brief (<i>Internal</i>) Get first update offset in database.
107
     * \details Called by getUpdatesDatabase to get the offset saved in database or to get it from telegram and save it in database.
108
     * @param $table_name Name of the table where offset is saved in the database
109
     * @param $column_name Name of the column where the offset is saved in the database
110
     * @return Id of the first update to process.
111
     */
112
    protected function getUpdateOffsetDatabase(string $table_name, string $column_name) : int {
113
114
        // Get the offset from the database
115
        $sth = $this->pdo->prepare('SELECT ' . $column_name . ' FROM ' . $table_name);
0 ignored issues
show
Bug introduced by
The property pdo 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...
116
117
        try {
118
119
            $sth->execute();
120
121
        } 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...
122
123
            echo $e->getMessage();
124
125
        }
126
127
        $offset = $sth->fetchColumn();
128
129
        $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...
130
131
        // Get the offset from the first update to update
132
        if ($offset === false) {
133
134
            do {
135
136
                $update = $this->getUpdates(0, 1);
137
138
            } while (empty($update));
139
140
            $offset = $update[0]['update_id'];
141
142
        }
143
144
        return $offset;
145
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
        if (!isset($this->_database)) {
162
163
            throw new BotException("Database connection is not set");
164
165
        }
166
167
        // Get offset from database
168
        $this->getUpdateOffsetDatabase($table_name, $column_name);
169
170
        $this->initCommands();
171
172
        // Prepare the query for updating the offset in the database
173
        $sth = $this->pdo->prepare('UPDATE "' . $table_name . '" SET "' . $column_name . '" = :new_offset');
174
175
        while (true) {
176
177
            $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...
178
179
            foreach ($updates as $key => $update) {
180
181
                try {
182
183
                    $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...
184
185
                } 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...
186
187
                    echo $e->getMessage();
188
189
                }
190
191
            }
192
193
            // Update the offset on the database
194
            $sth->bindParam(':new_offset', $offset + sizeof($updates));
195
            $sth->execute();
196
197
        }
198
199
    }
200
201
    /** @} */
202
203
    /** @} */
204
205
}
206