Telegram   A
last analyzed

Complexity

Total Complexity 27

Size/Duplication

Total Lines 197
Duplicated Lines 7.11 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 27
lcom 1
cbo 0
dl 14
loc 197
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A apiRequestWebhook() 7 22 4
B exec_curl_request() 0 46 6
B apiRequest() 7 34 7
A apiRequestJson() 0 26 4
A sendMessage() 0 8 1
A kickChatMember() 0 9 1
A deleteMessage() 0 8 1
A setWebhook() 0 9 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * Telegram Client Class.
5
 *
6
 * @author  Alexander Rodriguez <[email protected]>
7
 */
8
9
namespace App;
10
11
class Telegram
12
{
13
    private $token;
14
    private $webhook;
15
    private $apiUrl;
16
17
    public function __construct($config, $pwrtelegram = false)
18
    {
19
        /*
20
         * Can use PWRTelegram for active more power of telegram.
21
         */
22
        $this->apiUrl = ($pwrtelegram) ? 'https://api.pwrtelegram.xyz/bot'.$config['TELEGRAM_TOKEN'].'/' : 'https://api.telegram.org/bot'.$config['TELEGRAM_TOKEN'].'/';
23
        $this->webhook = $config['WEBHOOK_URL'];
24
    }
25
26
    /**
27
     * @param string $method
28
     */
29
    public function apiRequestWebhook($method, $parameters)
30
    {
31
        if (!is_string($method)) {
32
            error_log("El nombre del método debe ser una cadena de texto\n");
33
34
            return false;
35
        }
36
37 View Code Duplication
        if (!$parameters) {
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...
38
            $parameters = [];
39
        } elseif (!is_array($parameters)) {
40
            error_log("Los parámetros deben ser un arreglo/matriz\n");
41
42
            return false;
43
        }
44
45
        $parameters['method'] = $method;
46
        header('Content-Type: application/json');
47
        echo json_encode($parameters);
48
49
        return true;
50
    }
51
52
    /**
53
     * @param resource $handle
54
     */
55
    public function exec_curl_request($handle)
56
    {
57
        $response = curl_exec($handle);
58
        if ($response === false) {
59
            $errno = curl_errno($handle);
60
            $error = curl_error($handle);
61
            error_log("Curl retornó un error $errno: $error\n");
62
            curl_close($handle);
63
64
            return false;
65
        }
66
67
        $http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
68
        curl_close($handle);
69
        if ($http_code >= 500) {
70
71
        // do not wat to DDOS server if something goes wrong
72
73
            sleep(10);
74
75
            return false;
76
        } elseif ($http_code != 200) {
77
            $response = json_decode($response, true);
78
            error_log("La solicitud falló con el error {$response['error_code']}: {$response['description']}\n");
79
            if ($http_code == 401) {
80
                http_response_code(401);
81
82
                throw new \Exception('El token provisto es inválido');
83
            } else {
84
                http_response_code($response['error_code']);
85
86
                throw new \Exception("La solicitud falló con el error {$response['error_code']}: {$response['description']}\n");
87
            }
88
89
            return false;
0 ignored issues
show
Unused Code introduced by
return false; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
90
        } else {
91
            $response = json_decode($response, true);
92
            if (isset($response['description'])) {
93
                error_log("La solicitud fue exitosa: {$response['description']}\n");
94
            }
95
96
            $response = $response['result'];
97
        }
98
99
        return $response;
100
    }
101
102
    /**
103
     * @param string $method
104
     */
105
    public function apiRequest($method, $parameters)
106
    {
107
        if (!is_string($method)) {
108
            error_log("El nombre del método debe ser una cadena de texto\n");
109
110
            return false;
111
        }
112
113 View Code Duplication
        if (!$parameters) {
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...
114
            $parameters = [];
115
        } elseif (!is_array($parameters)) {
116
            error_log("Los parámetros deben ser un arreglo/matriz\n");
117
118
            return false;
119
        }
120
121
        foreach ($parameters as $key => &$val) {
122
123
        // encoding to JSON array parameters, for example reply_markup
124
125
            if (!is_numeric($val) && !is_string($val)) {
126
                $val = json_encode($val);
127
            }
128
        }
129
130
        $url = $this->apiUrl.$method.'?'.http_build_query($parameters);
131
        $handle = curl_init($url);
132
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
133
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
134
        curl_setopt($handle, CURLOPT_TIMEOUT, 60);
135
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
136
137
        return self::exec_curl_request($handle);
138
    }
139
140
    /**
141
     * @param string $method
142
     */
143
    public function apiRequestJson($method, $parameters)
144
    {
145
        if (!is_string($method)) {
146
            error_log("El nombre del método debe ser una cadena de texto\n");
147
148
            return false;
149
        }
150
151
        if (!$parameters) {
152
            $parameters = [];
153
        } elseif (!is_array($parameters)) {
154
            error_log("Los parámetros deben ser un arreglo/matriz\n");
155
156
            return false;
157
        }
158
159
        $parameters['method'] = $method;
160
        $handle = curl_init($this->apiUrl);
161
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
162
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
163
        curl_setopt($handle, CURLOPT_TIMEOUT, 60);
164
        curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
165
        curl_setopt($handle, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
166
167
        return exec_curl_request($handle);
168
    }
169
170
    public function sendMessage($chat_id, $text, $args = [])
171
    {
172
        $parameters = $args;
173
        $parameters['chat_id'] = $chat_id;
174
        $parameters['text'] = $text;
175
176
        return $this->apiRequest('sendMessage', $parameters);
177
    }
178
179
    public function kickChatMember($chat_id, $user_id, $until_date = null)
180
    {
181
        $parameters = [];
182
        $parameters['chat_id'] = $chat_id;
183
        $parameters['user_id'] = $user_id;
184
        $parameters['until_date'] = $until_date;
185
186
        return $this->apiRequest('kickChatMember', $parameters);
187
    }
188
189
    public function deleteMessage($chat_id, $message_id)
190
    {
191
        $parameters = [];
192
        $parameters['chat_id'] = $chat_id;
193
        $parameters['message_id'] = $message_id;
194
195
        return $this->apiRequest('deleteMessage', $parameters);
196
    }
197
198
    public function setWebhook($certificate = null, $max_connections = null, $allowed_updates = [])
199
    {
200
        $parameters['url'] = $this->webhook;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$parameters was never initialized. Although not strictly required by PHP, it is generally a good practice to add $parameters = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
201
        $parameters['certificate'] = $certificate;
202
        $parameters['max_connections'] = $max_connections;
203
        $parameters['allowed_updates'] = $allowed_updates;
204
205
        return $this->apiRequest('setWebhook', $parameters);
206
    }
207
}
208