Completed
Pull Request — master (#20)
by
unknown
03:12
created

LongPolling::getUpdatesRedis()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 59
Code Lines 21

Duplication

Lines 16
Ratio 27.12 %

Importance

Changes 0
Metric Value
dl 16
loc 59
rs 7.5346
c 0
b 0
f 0
cc 7
eloc 21
nc 9
nop 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace PhpBotFramework\Core;
4
5
trait LongPolling {
6
7
    /**
8
     * \brief Get updates received by the bot, using redis to save and get the last offset.
9
     * \details It check if an offset exists on redis, then get it, or call getUpdates to set it.
10
     * Then it start an infinite loop where it process updates and update the offset on redis.
11
     * Each update is surrounded by a try/catch.
12
     * @see getUpdates
13
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
14
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
15
     * @param $offset_key <i>Optional</i>. Name of the variable where the offset is saved on Redis
16
     */
17
    public function getUpdatesRedis(int $limit = 100, int $timeout = 60, string $offset_key = 'offset') {
0 ignored issues
show
Unused Code introduced by
The parameter $offset_key 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...
18
19
        // Check redis connection
20
        if (!isset($this->redis)) {
21
22
            throw new BotException("Redis connection is not set");
23
24
        }
25
26
        // If offset is already set in redis
27
        if ($this->redis->exists($variable_name)) {
28
29
            // just set $offset as the same value
30
            $offset = $this->redis->get($variable_name);
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...
Bug introduced by
The variable $variable_name 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...
31
32 View Code Duplication
        } else {
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...
33
            // Else get the offset from the id from the first update received
34
35
            do {
36
37
                $update = $this->getUpdates(0, 1);
0 ignored issues
show
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Core\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...
38
39
            } while (empty($update));
40
41
            $offset = $update[0]['update_id'];
42
43
            $this->redis->set($variable_name, $offset);
44
45
            $update = null;
46
47
        }
48
49
        $this->initBot();
0 ignored issues
show
Bug introduced by
It seems like initBot() 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...
50
51
        // Process all updates received
52
        while (true) {
53
54
            $updates = $this->getUpdates($offset, $limit, $timeout);
0 ignored issues
show
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Core\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...
55
56
            // Parse all updates received
57
            foreach ($updates as $key => $update) {
58
59
                try {
60
61
                    $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...
62
63
                } catch (BotException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Core\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...
64
65
                    echo $e->getMessage();
66
67
                }
68
69
            }
70
71
            // Update the offset in redis
72
            $this->redis->set($variable_name, $offset + count($updates));
73
        }
74
75
    }
76
77
    /**
78
     * \brief Get updates received by the bot, and hold the offset in $offset.
79
     * \details Get the update_id 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 $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
84
     * @param $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
        do {
92
93
            // Get updates from telegram
94
            $update = $this->getUpdates(0, 1);
0 ignored issues
show
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Core\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...
95
96
            // While in the array received there aren't updates
97
        } while (empty($update));
98
99
        // Set the offset to the first update recevied
100
        $offset = $update[0]['update_id'];
101
102
        $update = null;
103
104
        $this->initBot();
0 ignored issues
show
Bug introduced by
It seems like initBot() 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...
105
106
        // Process all updates
107
        while (true) {
108
109
            // Set parameter for the url call
110
            $parameters = [
111
                'offset' => $offset,
112
                'limit' => $limit,
113
                'timeout' => $timeout
114
            ];
115
116
            $updates = $this->exec_curl_request($this->_api_url . 'getUpdates?' . http_build_query($parameters));
0 ignored issues
show
Bug introduced by
The property _api_url 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...
Bug introduced by
It seems like exec_curl_request() 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...
117
118
            // Parse all update to receive
119
            foreach ($updates as $key => $update) {
120
121
                try {
122
123
                    // Process one at a time
124
                    $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...
125
126
                } catch (BotException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Core\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...
127
128
                    echo $e->getMessage();
129
130
                }
131
132
            }
133
134
            // Update the offset
135
            $offset += sizeof($updates);
136
137
        }
138
139
    }
140
141
    /**
142
     * \brief Get updates received by the bot, using the sql database to store and get the last offset.
143
     * \details It check if an offset exists on redis, then get it, or call getUpdates to set it.
144
     * Then it start an infinite loop where it process updates and update the offset on redis.
145
     * Each update is surrounded by a try/catch.
146
     * @see getUpdates
147
     * @param $limit <i>Optional</i>. Limits the number of updates to be retrieved. Values between 1—100 are accepted.
148
     * @param $timeout <i>Optional</i>. Timeout in seconds for long polling.
149
     * @param $table_name <i>Optional</i>. Name of the table where offset is saved in the database
150
     * @param $column_name <i>Optional</i>. Name of the column where the offset is saved in the database
151
     */
152
    public function getUpdatesDatabase(int $limit = 100, int $timeout = 0, string $table_name = 'telegram', string $column_name = 'bot_offset') {
153
154
        if (!isset($this->_database)) {
155
156
            throw new BotException("Database connection is not set");
157
158
        }
159
160
        // Get the offset from the database
161
        $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...
162
163
        try {
164
165
            $sth->execute();
166
167
        } catch (PDOException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Core\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...
168
169
            echo $e->getMessage();
170
171
        }
172
173
        $offset = $sth->fetchColumn();
174
        $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...
175
176
        // Get the offset from the first update to update
177 View Code Duplication
        if ($offset === false) {
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...
178
179
            do {
180
181
                $update = $this->getUpdates(0, 1);
0 ignored issues
show
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Core\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...
182
183
            } while (empty($update));
184
185
            $offset = $update[0]['update_id'];
186
187
            $update = null;
188
189
        }
190
191
        // Prepare the query for updating the offset in the database
192
        $sth = $this->pdo->prepare('UPDATE "' . $table_name . '" SET "' . $column_name . '" = :new_offset');
193
194
        $this->initBot();
0 ignored issues
show
Bug introduced by
It seems like initBot() 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...
195
196
        while (true) {
197
198
            $updates = $this->getUpdates($offset, $limit, $timeout);
0 ignored issues
show
Bug introduced by
The method getUpdates() does not exist on PhpBotFramework\Core\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...
199
200
            foreach ($updates as $key => $update) {
201
202
                try {
203
204
                    $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...
205
206
                } catch (BotException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Core\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...
207
208
                    echo $e->getMessage();
209
210
                }
211
212
            }
213
214
            // Update the offset on the database
215
            $sth->bindParam(':new_offset', $offset + sizeof($updates));
216
            $sth->execute();
217
218
        }
219
    }
220
221
}
222