GlipBotman::buildPayload()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
nc 1
nop 1
dl 0
loc 5
c 0
b 0
f 0
cc 1
rs 9.4285
1
<?php
2
3
namespace GlipDriver;
4
5
use Mpociot\BotMan\User;
6
use Mpociot\BotMan\Answer;
7
use Mpociot\BotMan\Message;
8
use Mpociot\BotMan\Question;
9
use Mpociot\BotMan\Drivers\Driver;
10
use Illuminate\Support\Collection;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\HttpFoundation\ParameterBag;
14
use Mpociot\BotMan\Messages\Message as IncomingMessage;
15
use RingCentral\SDK\SDK;
16
17
class GlipBotman extends Driver
18
{
19
    /** @var Collection */
20
    protected $event;
21
22
    /** @var config */
0 ignored issues
show
Bug introduced by
The type GlipDriver\config was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
    protected $config;
24
25
    /** @var GlipClient */
0 ignored issues
show
Bug introduced by
The type GlipDriver\GlipClient was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
    protected $sdk;
27
    protected $platform;
28
29
    const DRIVER_NAME = 'GlipBotman';
30
31
    /** @var Collection|ParameterBag */
32
    protected $payload;
33
34
    protected $endpoint = '/glip/posts';
35
36
37
    /**s
38
     * @param Request $request
39
     */
40
    public function buildPayload(Request $request)
41
    {
42
        $this->payload = new ParameterBag((array) json_decode($request->getContent(), true));
43
        print 'The payload during the glip buildpayload method is ' . PHP_EOL . print_r($this->payload);
44
        $this->event = Collection::make($this->payload->get('event'));
45
    }
46
47
    /**
48
     * Return the driver name.
49
     *
50
     * @return string
51
     */
52
    public function getName()
53
    {
54
        return self::DRIVER_NAME;
55
    }
56
57
    /**
58
     * @param Message $matchingMessage
59
     * @return User
60
     */
61
    public function getUser(Message $matchingMessage)
62
    {
63
        $parameters = [
0 ignored issues
show
Unused Code introduced by
The assignment to $parameters is dead and can be removed.
Loading history...
64
            'chat_id' => $matchingMessage->getChannel(),
65
            'user_id' => $matchingMessage->getUser(),
66
        ];
67
68
        $response = $this->$this->getPlatform()->get('/glip/persons' + $matchingMessage->getUser());
69
        $responseData = json_decode($response->getContent(), true);
70
        $userData = Collection::make($responseData['result']['user']);
71
72
        return new User($userData->get('id'), $userData->get('firstName'), $userData->get('lastName'), $userData->get('avatar'));
73
    }
74
75
    /**
76
     * Determine if the request is for this driver.
77
     *
78
     * @return bool
79
     */
80
    public function matchesRequest()
81
    {
82
        return (! is_null($this->payload->get('body'))) && ! is_null($this->payload->get('event'));
83
    }
84
85
    /**
86
     * @param  Message $message
87
     * @return Answer
88
     */
89
    public function getConversationAnswer(Message $message)
90
    {
91
        print 'Inside the get Conv Answeer' . PHP_EOL . print_r($message);
92
        return Answer::create($message->getMessage())->setMessage($message);
93
    }
94
95
96
    /**
97
     * Retrieve the chat message.
98
     *
99
     * @return array
100
     */
101
    public function getMessages()
102
    {
103
        if ($this->payload->get('body') !== null) {
104
            $callback = Collection::make($this->payload->get('body'));
105
106
            return [new Message($callback->get('text'), $callback->get('creatorId'), $callback->get('groupId'), $this->payload->get('body'))];
107
        }
108
109
    }
110
111
    /**
112
     * @return bool
113
     */
114
    public function isBot()
115
    {
116
        return false;
117
    }
118
119
    /**
120
     * @param Message $matchingMessage
121
     * @return void
122
     */
123
    public function types(Message $matchingMessage)
124
    {
125
        $parameters = [
126
            'chat_id' => $matchingMessage->getChannel(),
127
            'action' => 'typing',
128
        ];
129
        $this->http->post('/glip/posts', $parameters);
130
    }
131
132
    /**
133
     * Convert a Question object into a valid
134
     * quick reply response object.
135
     *
136
     * @param Question $question
137
     * @return array
138
     */
139
    private function convertQuestion(Question $question)
140
    {
141
        $replies = Collection::make($question->getButtons())->map(function ($button) {
142
            return [
143
                [
144
                    'text' => (string) $button['text'],
145
                    'callback_data' => (string) $button['value'],
146
                ],
147
            ];
148
        });
149
150
        return $replies->toArray();
151
    }
152
153
    /**
154
     * @return \RingCentral\SDK\Platform\Platform
155
     */
156
    public function getPlatform()
157
    {
158
159
        $rcsdk = new SDK($this->config->get('GLIP_APPKEY'), $this->config->get('GLIP_APPSECRET'), $this->config->get('GLIP_SERVER'), 'Sample-Bot', '1.0.0');
160
        $platform = $rcsdk->platform();
161
162
        $cacheDir = __DIR__ . DIRECTORY_SEPARATOR . '_cache';
163
        $file = $cacheDir . DIRECTORY_SEPARATOR . 'platform.json';
164
165
        if (!file_exists($cacheDir)) {
166
            mkdir($cacheDir);
167
            print 'The config is :' . PHP_EOL . print_r($this->config);
168
            $platform->login($this->config->get('GLIP_USERNAME'), $this->config->get('GLIP_EXTENSION'), $this->config->get('GLIP_PASSWORD'));
169
            file_put_contents($file, json_encode($platform->auth()->data(), JSON_PRETTY_PRINT));
170
        }
171
172
        $cachedAuth = array();
0 ignored issues
show
Unused Code introduced by
The assignment to $cachedAuth is dead and can be removed.
Loading history...
173
174
        if (file_exists($file)) {
175
            $cachedAuth = json_decode(file_get_contents($file), true);
176
            $platform->auth()->setData($cachedAuth);
177
178
        }
179
180
        try {
181
182
            if($platform->loggedIn()) {
183
                return $platform;
184
            }
185
186
            else {
187
                print 'The Username is : ' . $this->config->get('GLIP_USERNAME');
188
                $refresh = $platform->login($this->config->get('GLIP_USERNAME'), $this->config->get('GLIP_EXTENSION'), $this->config->get('GLIP_PASSWORD'));
189
                file_put_contents($file, json_encode($refresh->jsonArray(), JSON_PRETTY_PRINT));
190
                return $platform;
191
            }
192
        }
193
194
        catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type GlipDriver\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
195
            $platform->login($this->config->get('GLIP_USERNAME'), $this->config->get('GLIP_EXTENSION'), $this->config->get('GLIP_PASSWORD'));
196
            file_put_contents($file, json_encode($platform->auth()->data(), JSON_PRETTY_PRINT));
197
            return $platform;
198
        }
199
    }
200
201
    /**
202
     * Removes the inline keyboard from an interactive
203
     * message.
204
     * @param  int $chatId
205
     * @param  int $messageId
206
     * @return Response
207
     */
208
    private function removeInlineKeyboard($chatId, $messageId)
0 ignored issues
show
Unused Code introduced by
The method removeInlineKeyboard() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
209
    {
210
        $parameters = [
211
            'chat_id' => $chatId,
212
            'message_id' => $messageId,
213
            'inline_keyboard' => [],
214
        ];
215
216
        $this->getPlatform()->post('/glip/posts', $parameters);
217
    }
218
219
    /**
220
     * @param string|Question|IncomingMessage $message
221
     * @param Message $matchingMessage
222
     * @param array $additionalParameters
223
     * @return Response
224
     */
225
    public function reply($message, $matchingMessage, $additionalParameters = [])
226
    {
227
228
        print 'Inside Reply method' . PHP_EOL;
229
        $endpoint = 'sendMessage';
230
        $parameters = array_merge([
231
            'groupId' => $matchingMessage->getChannel(),
232
        ], $additionalParameters);
233
        /*
234
         * If we send a Question with buttons, ignore
235
         * the text and append the question.
236
         */
237
        if ($message instanceof Question) {
238
            $parameters['text'] = $message->getText();
239
            $parameters['reply_markup'] = json_encode([
240
                'inline_keyboard' => $this->convertQuestion($message),
241
            ], true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type integer expected by parameter $options of json_encode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

241
            ], /** @scrutinizer ignore-type */ true);
Loading history...
242
        } elseif ($message instanceof IncomingMessage) {
243
            if (! is_null($message->getImage())) {
244
                if (strtolower(pathinfo($message->getImage(), PATHINFO_EXTENSION)) === 'gif') {
245
                    $endpoint = 'sendDocument';
0 ignored issues
show
Unused Code introduced by
The assignment to $endpoint is dead and can be removed.
Loading history...
246
                    $parameters['document'] = $message->getImage();
247
                } else {
248
                    $endpoint = 'sendPhoto';
249
                    $parameters['photo'] = $message->getImage();
250
                }
251
                $parameters['caption'] = $message->getMessage();
252
            } elseif (! is_null($message->getVideo())) {
253
                $endpoint = 'sendVideo';
254
                $parameters['video'] = $message->getVideo();
255
                $parameters['caption'] = $message->getMessage();
256
            } else {
257
                $parameters['text'] = $message->getMessage();
258
            }
259
        } else {
260
            $parameters['text'] = $message;
261
        }
262
263
        $this->getPlatform()->post('/glip/posts', $parameters);
264
    }
265
266
    /**
267
     * @param string|Question|IncomingMessage $message
268
     * @param Message $matchingMessage
269
     * @param array $additionalParameters
270
     * @return Response
271
     */
272
    public function buildServicePayload($message, $matchingMessage, $additionalParameters = [])
273
    {
274
        $recipient = $matchingMessage->getRecipient() === '' ? $matchingMessage->getSender() : $matchingMessage->getRecipient();
0 ignored issues
show
Bug introduced by
The method getSender() does not exist on Mpociot\BotMan\Message. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

274
        $recipient = $matchingMessage->getRecipient() === '' ? $matchingMessage->/** @scrutinizer ignore-call */ getSender() : $matchingMessage->getRecipient();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method getRecipient() does not exist on Mpociot\BotMan\Message. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

274
        $recipient = $matchingMessage->/** @scrutinizer ignore-call */ getRecipient() === '' ? $matchingMessage->getSender() : $matchingMessage->getRecipient();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
275
        $parameters = array_merge_recursive([
276
            'groupId' => $recipient,
277
        ], $additionalParameters);
278
279
        print 'The mesaage is : ' . PHP_EOL . print_r($message);
280
        /*
281
         * If we send a Question with buttons, ignore
282
         * the text and append the question.
283
         */
284
        if ($message instanceof Question) {
285
            $parameters['text'] = $message->getText();
286
            $parameters['reply_markup'] = json_encode([
287
                'inline_keyboard' => $this->convertQuestion($message),
288
            ], true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type integer expected by parameter $options of json_encode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

288
            ], /** @scrutinizer ignore-type */ true);
Loading history...
289
        } elseif ($message instanceof IncomingMessage) {
290
            if (! is_null($message->getAttachment())) {
0 ignored issues
show
Bug introduced by
The method getAttachment() does not exist on Mpociot\BotMan\Messages\Message. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

290
            if (! is_null($message->/** @scrutinizer ignore-call */ getAttachment())) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
291
                $attachment = $message->getAttachment();
292
                $parameters['caption'] = $message->getText();
0 ignored issues
show
Bug introduced by
The method getText() does not exist on Mpociot\BotMan\Messages\Message. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

292
                /** @scrutinizer ignore-call */ 
293
                $parameters['caption'] = $message->getText();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
293
                if ($attachment instanceof Image) {
0 ignored issues
show
Bug introduced by
The type GlipDriver\Image was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
294
                    if (strtolower(pathinfo($attachment->getUrl(), PATHINFO_EXTENSION)) === 'gif') {
295
                        $this->endpoint = 'sendDocument';
296
                        $parameters['document'] = $attachment->getUrl();
297
                    } else {
298
                        $this->endpoint = 'sendPhoto';
299
                        $parameters['photo'] = $attachment->getUrl();
300
                    }
301
                } elseif ($attachment instanceof Video) {
0 ignored issues
show
Bug introduced by
The type GlipDriver\Video was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
302
                    $this->endpoint = 'sendVideo';
303
                    $parameters['video'] = $attachment->getUrl();
304
                } elseif ($attachment instanceof Audio) {
0 ignored issues
show
Bug introduced by
The type GlipDriver\Audio was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
305
                    $this->endpoint = 'sendAudio';
306
                    $parameters['audio'] = $attachment->getUrl();
307
                } elseif ($attachment instanceof File) {
0 ignored issues
show
Bug introduced by
The type GlipDriver\File was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
308
                    $this->endpoint = 'sendDocument';
309
                    $parameters['document'] = $attachment->getUrl();
310
                } elseif ($attachment instanceof Location) {
0 ignored issues
show
Bug introduced by
The type GlipDriver\Location was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
311
                    $this->endpoint = 'sendLocation';
312
                    $parameters['latitude'] = $attachment->getLatitude();
313
                    $parameters['longitude'] = $attachment->getLongitude();
314
                }
315
            } else {
316
                $parameters['text'] = $message->getText();
317
            }
318
        } else {
319
            $parameters['text'] = $message;
320
        }
321
322
        return $parameters;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $parameters returns the type array|array<mixed,mixed|string> which is incompatible with the documented return type Symfony\Component\HttpFoundation\Response.
Loading history...
323
    }
324
325
    /**
326
     * @param mixed $payload
327
     * @return Response
328
     */
329
    public function sendPayload($payload)
330
    {
331
        print 'Inside GlipTest sendpayload' . PHP_EOL . print_r($payload);
332
        return $this->getPlatform()->post($this->endpoint, $payload);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getPlatfor...is->endpoint, $payload) returns the type RingCentral\SDK\Http\ApiResponse which is incompatible with the documented return type Symfony\Component\HttpFoundation\Response.
Loading history...
333
    }
334
335
    /**
336
     * @return bool
337
     */
338
    public function isConfigured()
339
    {
340
        return ! is_null($this->getPlatform()->loggedIn());
341
    }
342
343
    /**
344
     * Low-level method to perform driver specific API requests.
345
     *
346
     * @param string $endpoint
347
     * @param array $parameters
348
     * @param Message $matchingMessage
349
     * @return Response
350
     */
351
    public function sendRequest($endpoint, array $parameters, Message $matchingMessage)
352
    {
353
        $parameters = array_replace_recursive([
354
            'chat_id' => $matchingMessage->getRecipient(),
355
        ], $parameters);
356
357
        return $this->getPlatform()->post($endpoint, $parameters);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getPlatfor...$endpoint, $parameters) returns the type RingCentral\SDK\Http\ApiResponse which is incompatible with the documented return type Symfony\Component\HttpFoundation\Response.
Loading history...
358
    }
359
}
360