Completed
Push — master ( 23095d...54d687 )
by Danilo
02:12
created

LongPolling::getUpdateOffsetRedis()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 26
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 2
nop 1
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace PhpBotFramework\Database;
4
5
trait LongPolling {
6
7
    /**
8
     * \addtogroup LongPollingDatabase Long polling With Database
9
     * \brief Use getUpdates saving and getting offset in redis/sql-database.
10
     * @{
11
     */
12
13
    /**
14
     * \brief (<i>Internal</i>)Get first update offset in redis.
15
     * \details Called by getUpdatesRedis to get the offset saved in redis or to get it from telegram and save it in redis.
16
     * @param $offset_key Name of the variable where the offset is saved on Redis
17
     * @return Id of the first update to process.
18
     */
19
    protected function getUpdateOffsetRedis(string $offset_key) : int {
20
21
        // If offset is already set in redis
22
        if ($this->redis->exists($offset_key)) {
23
24
            // return the value saved
25
            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...
26
27
            // Else get the offset from the id from the first update received
28
        } else {
29
30
            do {
31
32
                $update = $this->getUpdates(0, 1);
0 ignored issues
show
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Database\LongPolling. Did you maybe mean getUpdatesRedis()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
33
34
            } while (empty($update));
35
36
            $offset = $update[0]['update_id'];
37
38
            $this->redis->set($offset_key, $offset);
39
40
            return $offset_key;
41
42
        }
43
44
    }
45
46
    /**
47
     * \brief Get updates received by the bot, using redis to save and get the last offset.
48
     * \details It check if an offset exists on redis, then get it, or call getUpdates to set it.
49
     * Then it start an infinite loop where it process updates and update the offset on redis.
50
     * Each update is surrounded by a try/catch.
51
     * @see getUpdates
52
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
53
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
54
     * @param $offset_key <i>Optional</i>. Name of the variable where the offset is saved on Redis
55
     */
56
    public function getUpdatesRedis(int $limit = 100, int $timeout = 60, string $offset_key = 'offset') {
57
58
        // Check redis connection
59
        if (!isset($this->redis)) {
60
61
            throw new BotException("Redis connection is not set");
62
63
        }
64
65
        $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...
66
67
        // If CommandHandler trait is used and initCommands method exists
68
        if (method_exists($this, 'initCommands')) {
69
70
            $this->initCommands();
0 ignored issues
show
Bug introduced by
It seems like initCommands() 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...
71
72
        }
73
74
        // Process all updates received
75
        while (true) {
76
77
            $updates = $this->getUpdates($offset, $limit, $timeout);
0 ignored issues
show
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Database\LongPolling. Did you maybe mean getUpdatesRedis()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
78
79
            // Parse all updates received
80
            foreach ($updates as $key => $update) {
81
82
                try {
83
84
                    $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...
85
86
                } 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...
87
88
                    echo $e->getMessage();
89
90
                }
91
92
            }
93
94
            // Update the offset in redis
95
            $this->redis->set($offset_key, $offset + count($updates));
96
        }
97
98
    }
99
100
    /**
101
     * \brief (<i>Internal</i>) Get first update offset in database.
102
     * \details Called by getUpdatesDatabase to get the offset saved in database or to get it from telegram and save it in database.
103
     * @param $table_name Name of the table where offset is saved in the database
104
     * @param $column_name Name of the column where the offset is saved in the database
105
     * @return Id of the first update to process.
106
     */
107
    protected function getUpdateOffsetDatabase(string $table_name, string $column_name) : int {
108
109
        // Get the offset from the database
110
        $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...
111
112
        try {
113
114
            $sth->execute();
115
116
        } 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...
117
118
            echo $e->getMessage();
119
120
        }
121
122
        $offset = $sth->fetchColumn();
123
        $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...
124
125
        // Get the offset from the first update to update
126
        if ($offset === false) {
127
128
            do {
129
130
                $update = $this->getUpdates(0, 1);
0 ignored issues
show
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Database\LongPolling. Did you maybe mean getUpdatesRedis()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
131
132
            } while (empty($update));
133
134
            $offset = $update[0]['update_id'];
135
136
        }
137
138
        return $offset;
139
140
    }
141
142
    /**
143
     * \brief Get updates received by the bot, using the sql database to store and get the last offset.
144
     * \details It check if an offset exists on redis, then get it, or call getUpdates to set it.
145
     * Then it start an infinite loop where it process updates and update the offset on redis.
146
     * Each update is surrounded by a try/catch.
147
     * @see getUpdates
148
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
149
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
150
     * @param $table_name <i>Optional</i>. Name of the table where offset is saved in the database
151
     * @param $column_name <i>Optional</i>. Name of the column where the offset is saved in the database
152
     */
153
    public function getUpdatesDatabase(int $limit = 100, int $timeout = 0, string $table_name = 'telegram', string $column_name = 'bot_offset') {
154
155
        if (!isset($this->_database)) {
156
157
            throw new BotException("Database connection is not set");
158
159
        }
160
161
        // Get offset from database
162
        $this->getUpdateOffsetDatabase($table_name, $column_name);
163
164
        // If CommandHandler trait is used and initCommands method exists
165
        if (method_exists($this, 'initCommands')) {
166
167
            $this->initCommands();
0 ignored issues
show
Bug introduced by
It seems like initCommands() 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...
168
169
        }
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
176
            $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...
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Database\LongPolling. Did you maybe mean getUpdatesRedis()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
177
178
            foreach ($updates as $key => $update) {
179
180
                try {
181
182
                    $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...
183
184
                } 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...
185
186
                    echo $e->getMessage();
187
188
                }
189
190
            }
191
192
            // Update the offset on the database
193
            $sth->bindParam(':new_offset', $offset + sizeof($updates));
194
            $sth->execute();
195
196
        }
197
198
    }
199
200
    /** @} */
201
202
}
203