Completed
Push — master ( e5a473...e29741 )
by Mattias
02:38
created

Bot::getMassagesRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace TelegramBot;
4
5
use React\HttpClient\Client;
6
use React\HttpClient\Request;
7
use React\HttpClient\Response;
8
9
class Bot implements BotInterface {
10
11
  use \League\Event\EmitterTrait;
12
13
  /** @var string */
14
  private $botToken;
15
  /** @var int */
16
  private $offset;
17
  /** @var \React\HttpClient\Client */
18
  private $client;
19
20
  /**
21
   * @param string $botToken
22
   */
23 5
  public function __construct(string $botToken)
24
  {
25 5
      $this->botToken = $botToken;
26 5
  }
27
28
  /**
29
   * @param \React\HttpClient\Client
30
   */
31 5
  public function setClient(Client $client) {
32 5
    $this->client = $client;
33 5
  }
34
35
  public function poll() {
36
    $request = $this->getMassagesRequest();
37
    $request->on('response', [$this, '_handlePollResponse']);
38
    $request->end();
39
  }
40
41
  /**
42
   * @param \React\HttpClient\Response $response
43
   */
44
  public function _handlePollResponse(Response $response) {
45
    $response->on('data', [$this, '_handlePollData']);
46
    $response->on('error', [$this, '_handlePollError']);
47
  }
48
49
  /**
50
   * @param array $data
51
   * @param \React\HttpClient\Response $response
52
   */
53
  public function _handlePollData($data, $response) {
0 ignored issues
show
Unused Code introduced by
The parameter $response 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...
54
    $data = json_decode($data, 1);
55
    $messageData = $data['result'];
56
57
    foreach ($messageData as $message) {
58
59
      if (!isset($message['message']['text'])) {
60
        continue;
61
      }
62
63
      $this->getEmitter()->emit(
64
        $message['message']['text'],
65
        ['message' => $message, 'responder' => $this->getResponder($message)]
0 ignored issues
show
Unused Code introduced by
The call to EmitterInterface::emit() has too many arguments starting with array('message' => $mess...getResponder($message)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
66
      );
67
68
      $this->setUpdateId($message['update_id']);
69
    }
70
  }
71
72
  /**
73
   * @param \React\HttpClient\Response $response
74
   */
75
  public function _handlePollError(Response $response) {
76
    print('Error: ');
77
    print_r($response);
78
  }
79
80
  /**
81
   * @param string $message
82
   */
83
  public function getResponder($message) {
84 1
    return function ($text) use($message){
85
        $this->sendResponse($text, $message);
0 ignored issues
show
Documentation introduced by
$message is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
86 1
    };
87
  }
88
89 1
  public function getMassagesRequest(): Request {
90 1
    return $this->client->request(
91 1
      'GET',
92 1
      $this->botCommand('getUpdates', ['offset' => $this->offset])
93
    );
94
  }
95
96 1
  public function sendResponse(string $responseText, array $incomingMessage) {
97 1
    $responseData = $this->postDataEncoder([
98 1
      'chat_id' => $incomingMessage['message']['chat']['id'],
99 1
      'reply_to_message_id' => $incomingMessage['message']['message_id'],
100 1
      'text' => $responseText
101
    ]);
102
103 1
    $responseCall = $this->client->request(
104 1
      'POST',
105 1
      $this->botCommand('sendMessage'),
106 1
      $this->getResponseHeaders($responseData)
107
    );
108
109 1
    $responseCall->end($responseData);
110 1
  }
111
112
  public function setUpdateId($id) {
113
    $this->offset = $id+1;
114
  }
115
116
117 2
  private function botCommand(string $command, array $params = []) :string {
118 2
    $params = (count($params)) ? '?' . $this->postDataEncoder($params) : '';
119
120 2
    return $this->assembleUri($command, $params);
121
  }
122
123
124 2
  private function assembleUri($command, $params) :string {
125 2
    return sprintf(
126 2
      'https://api.telegram.org/bot%s/%s%s',
127 2
      $this->botToken,
128
      $command,
129
      $params
130
    );
131
  }
132
133 2
  public function getResponseHeaders(string $responseString) :array {
134
    return [
135 2
      'Content-Type' =>  'application/x-www-form-urlencoded',
136 2
      'Content-Length' => strlen($responseString)
137
    ];
138
  }
139
140 2
  private function postDataEncoder(array $data) :string {
141 2
    $string = '';
142
143 2
    foreach ($data as $k => $v) {
144 2
      $string .= $k . '=' . urlencode($v) . '&';
145
    }
146
147 2
    return $string;
148
  }
149
}
150