Completed
Push — master ( 805b95...6605a7 )
by Elf
01:47
created

Message::getNotification()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace ElfSundae\BearyChat;
4
5
use JsonSerializable;
6
7
class Message implements JsonSerializable
8
{
9
    /**
10
     * The BearyChat client for sending message.
11
     *
12
     * @var \ElfSundae\BearyChat\Client
13
     */
14
    protected $client;
15
16
    /**
17
     * The text to be sent with the message.
18
     *
19
     * @var string
20
     */
21
    protected $text;
22
23
    /**
24
     * The notification for the text.
25
     *
26
     * @var string
27
     */
28
    protected $notification;
29
30
    /**
31
     * Indicates the text field should be parsed as markdown syntax.
32
     *
33
     * @var bool
34
     */
35
    protected $markdown;
36
37
    /**
38
     * The channel that the message should be sent to.
39
     *
40
     * @var string
41
     */
42
    protected $channel;
43
44
    /**
45
     * The user that the message should be sent to.
46
     *
47
     * @var string
48
     */
49
    protected $user;
50
51
    /**
52
     * The attachments to be sent.
53
     *
54
     * @var array
55
     */
56
    protected $attachments = [];
57
58
    /**
59
     * The default values for each attachment.
60
     *
61
     * @var array
62
     */
63
    protected $attachmentDefaults = [];
64
65
    /**
66
     * Create a new message.
67
     *
68
     * @param  \ElfSundae\BearyChat\Client|null $client
69
     */
70 13
    public function __construct(Client $client = null)
71
    {
72 13
        if ($this->client = $client) {
73
            $this->configureDefaults($client->getMessageDefaults());
74
        }
75 13
    }
76
77
    /**
78
     * Get the BearyChat client for sending message.
79
     *
80
     * @return \ElfSundae\BearyChat\Client
81
     */
82
    public function getClient()
83
    {
84
        return $this->client;
85
    }
86
87
    /**
88
     * Get the text.
89
     *
90
     * @return string
91
     */
92 2
    public function getText()
93
    {
94 2
        return $this->text;
95
    }
96
97
    /**
98
     * Set the text.
99
     *
100
     * @param  string  $text
101
     * @return $this
102
     */
103 2
    public function setText($text)
104
    {
105 2
        $this->text = $text ? (string) $text : null;
106
107 2
        return $this;
108
    }
109
110
    /**
111
     * Set the text.
112
     *
113
     * @param  string  $text
114
     * @return $this
115
     */
116 2
    public function text($text)
117
    {
118 2
        return $this->setText($text);
119
    }
120
121
    /**
122
     * Get the notification.
123
     *
124
     * @return string
125
     */
126 2
    public function getNotification()
127
    {
128 2
        return $this->notification;
129
    }
130
131
    /**
132
     * Set the notification.
133
     *
134
     * @param  string  $notification
135
     * @return $this
136
     */
137 1
    public function setNotification($notification)
138
    {
139 1
        $this->notification = $notification ? (string) $notification : null;
140
141 1
        return $this;
142
    }
143
144
    /**
145
     * Set the notification.
146
     *
147
     * @param  string  $notification
148
     * @return $this
149
     */
150 1
    public function notification($notification)
151
    {
152 1
        return $this->setNotification($notification);
153
    }
154
155
    /**
156
     * Get the markdown.
157
     *
158
     * @return bool
159
     */
160 2
    public function getMarkdown()
161
    {
162 2
        return $this->markdown;
163
    }
164
165
    /**
166
     * Set the markdown.
167
     *
168
     * @param  bool $markdown
169
     * @return $this
170
     */
171 1
    public function setMarkdown($markdown)
172
    {
173 1
        $this->markdown = (bool) $markdown;
174
175 1
        return $this;
176
    }
177
178
    /**
179
     * Set the markdown.
180
     *
181
     * @param  bool $markdown
182
     * @return $this
183
     */
184 1
    public function markdown($markdown = true)
185
    {
186 1
        return $this->setMarkdown($markdown);
187
    }
188
189
    /**
190
     * Get the channel which the message should be sent to.
191
     *
192
     * @return string
193
     */
194 3
    public function getChannel()
195
    {
196 3
        return $this->channel;
197
    }
198
199
    /**
200
     * Set the channel which the message should be sent to.
201
     *
202
     * @param  string  $channel
203
     * @return $this
204
     */
205 3
    public function setChannel($channel)
206
    {
207 3
        $this->channel = $channel ? (string) $channel : null;
208
209 3
        return $this;
210
    }
211
212
    /**
213
     * Set the channel which the message should be sent to.
214
     *
215
     * @param  string  $channel
216
     * @return $this
217
     */
218 1
    public function channel($channel)
219
    {
220 1
        return $this->setChannel($channel);
221
    }
222
223
    /**
224
     * Get the user which the message should be sent to.
225
     *
226
     * @return string
227
     */
228 3
    public function getUser()
229
    {
230 3
        return $this->user;
231
    }
232
233
    /**
234
     * Set the user which the message should be sent to.
235
     *
236
     * @param  string  $user
237
     * @return $this
238
     */
239 3
    public function setUser($user)
240
    {
241 3
        $this->user = $user ? (string) $user : null;
242
243 3
        return $this;
244
    }
245
246
    /**
247
     * Set the user which the message should be sent to.
248
     *
249
     * @param  string  $user
250
     * @return $this
251
     */
252 1
    public function user($user)
253
    {
254 1
        return $this->setUser($user);
255
    }
256
257
    /**
258
     * Set the target (user or channel) that the message should be sent to.
259
     *
260
     * The target may be started with '@' for sending to user, and the channel's
261
     * starter mark '#' is optional.
262
     *
263
     * It will remove all targets if the given target is null.
264
     *
265
     * @param  string  $target
266
     * @return $this
267
     */
268 2
    public function to($target)
269
    {
270 2
        $this->setChannel(null);
271 2
        $this->setUser(null);
272
273 2
        if (! empty($target)) {
274 2
            $target = (string) $target;
275
276 2
            $mark = mb_substr($target, 0, 1);
277 2
            $to = mb_substr($target, 1);
278
279 2
            if ($mark === '@' && ! empty($to)) {
280 2
                $this->setUser($to);
281 1
            } elseif ($mark === '#' && ! empty($to)) {
282 1
                $this->setChannel($to);
283
            } else {
284 1
                $this->setChannel($target);
285
            }
286
        }
287
288 2
        return $this;
289
    }
290
291
    /**
292
     * Get the attachments for the message.
293
     *
294
     * @return array
295
     */
296 5
    public function getAttachments()
297
    {
298 5
        return $this->attachments;
299
    }
300
301
    /**
302
     * Set the attachments for the message.
303
     *
304
     * @param  mixed  $attachments
305
     * @return $this
306
     */
307 1
    public function setAttachments($attachments)
308
    {
309 1
        $this->removeAttachments();
310
311 1
        if (is_array($attachments)) {
312 1
            foreach ($attachments as $attachment) {
313 1
                $this->addAttachment($attachment);
314
            }
315
        }
316
317 1
        return $this;
318
    }
319
320
    /**
321
     * Set the attachments for the message.
322
     *
323
     * @param  mixed  $attachments
324
     * @return $this
325
     */
326
    public function attachments($attachments)
327
    {
328
        return $this->setAttachments($attachments);
329
    }
330
331
    /**
332
     * Add an attachment to the message.
333
     *
334
     * The parameter can be an payload array that contains all of attachment's fields.
335
     * The parameters can also be attachment's fields that in order of
336
     * text, title, images and color. Except the text, other parameters
337
     * can be ignored.
338
     *
339
     * @param  mixed  $attachment
340
     * @return $this
341
     */
342 5
    public function addAttachment($attachment)
343
    {
344 5
        if (! is_array($attachment)) {
345 4
            $attachment = $this->getAttachmentPayloadFromArguments(func_get_args());
346
        }
347
348 5
        if (! empty($attachment)) {
349 5
            $attachment += $this->attachmentDefaults;
350
351 5
            $this->attachments[] = $attachment;
352
        }
353
354 5
        return $this;
355
    }
356
357
    /**
358
     * Convert arguments list to attachment payload.
359
     *
360
     * @param  array  $arguments
361
     * @return array
362
     */
363 4
    protected function getAttachmentPayloadFromArguments($arguments)
364
    {
365 4
        $attachment = [];
366
367 4
        foreach ($arguments as $index => $value) {
368 4
            if (empty($value)) {
369 1
                continue;
370
            }
371
372 4
            if ($index === 0) {
373 4
                $attachment['text'] = $this->stringValue($value);
374 1
            } elseif ($index === 1) {
375 1
                $attachment['title'] = $this->stringValue($value);
376 1
            } elseif ($index === 2) {
377 1
                $images = [];
378 1
                foreach ((array) $value as $img) {
379 1
                    if (is_array($img) && isset($img['url'])) {
380
                        $img = $img['url'];
381
                    }
382 1
                    if (is_string($img) && ! empty($img)) {
383 1
                        $images[] = ['url' => $img];
384
                    }
385
                }
386 1
                if ($images) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $images of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
387 1
                    $attachment['images'] = $images;
388
                }
389 1
            } elseif ($index === 3) {
390 4
                $attachment['color'] = (string) $value;
391
            }
392
        }
393
394 4
        return $attachment;
395
    }
396
397
    /**
398
     * Get the attachments' defaults.
399
     *
400
     * @return array
401
     */
402 1
    public function getAttachmentDefaults()
403
    {
404 1
        return $this->attachmentDefaults;
405
    }
406
407
    /**
408
     * Set the attachments' defaults.
409
     *
410
     * @param  array  $defaults
411
     * @return $this
412
     */
413 2
    public function setAttachmentDefaults(array $defaults)
414
    {
415 2
        $this->attachmentDefaults = $defaults;
416
417 2
        return $this;
418
    }
419
420
    /**
421
     * Add an attachment to the message.
422
     * It alias to `addAttachment`.
423
     *
424
     * @param  mixed  $attachment
425
     * @return $this
426
     */
427 3
    public function add($attachment)
0 ignored issues
show
Unused Code introduced by
The parameter $attachment 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...
428
    {
429 3
        return call_user_func_array([$this, 'addAttachment'], func_get_args());
430
    }
431
432
    /**
433
     * Remove attachment[s] for the message.
434
     *
435
     * @return $this
436
     */
437 2
    public function removeAttachments()
438
    {
439 2
        if (func_num_args() > 0) {
440 1
            $indices = is_array(func_get_arg(0)) ? func_get_arg(0) : func_get_args();
441
442 1
            foreach ($indices as $index) {
443 1
                unset($this->attachments[$index]);
444
            }
445
446 1
            $this->attachments = array_values($this->attachments);
447
        } else {
448 2
            $this->attachments = [];
449
        }
450
451 2
        return $this;
452
    }
453
454
    /**
455
     * Remove attachment[s] for the message.
456
     * It alias to `removeAttachments`.
457
     *
458
     * @return $this
459
     */
460 1
    public function remove()
461
    {
462 1
        return call_user_func_array([$this, 'removeAttachments'], func_get_args());
463
    }
464
465
    /**
466
     * Configure message defaults.
467
     *
468
     * @param  array  $defaults
469
     */
470
    protected function configureDefaults(array $defaults)
471
    {
472
        if (isset($defaults[MessageDefaults::CHANNEL])) {
473
            $this->setChannel($defaults[MessageDefaults::CHANNEL]);
474
        }
475
        if (isset($defaults[MessageDefaults::USER])) {
476
            $this->setUser($defaults[MessageDefaults::USER]);
477
        }
478
        if (isset($defaults[MessageDefaults::MARKDOWN])) {
479
            $this->setMarkdown($defaults[MessageDefaults::MARKDOWN]);
480
        }
481
        if (isset($defaults[MessageDefaults::NOTIFICATION])) {
482
            $this->setNotification($defaults[MessageDefaults::NOTIFICATION]);
483
        }
484
        if (isset($defaults[MessageDefaults::ATTACHMENT_COLOR])) {
485
            $this->attachmentDefaults['color'] = $defaults[MessageDefaults::ATTACHMENT_COLOR];
486
        }
487
    }
488
489
    /**
490
     * Convert any type to string.
491
     *
492
     * @param  mixed  $value
493
     * @param  int  $jsonOptions
494
     * @return string
495
     */
496 4
    protected function stringValue($value, $jsonOptions = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
497
    {
498 4
        if (is_object($value)) {
499
            if (method_exists($value, '__toString')) {
500
                return (string) $value;
501
            }
502
503
            if (method_exists($value, 'toArray')) {
504
                $value = $value->toArray();
505
            }
506
        }
507
508 4
        return is_string($value) ? $value : json_encode($value, $jsonOptions);
509
    }
510
511
    /**
512
     * Convert the message to an array.
513
     *
514
     * @return array
515
     */
516 1
    public function toArray()
517
    {
518 1
        return array_filter(
519
            [
520 1
                'text' => $this->getText(),
521 1
                'notification' => $this->getNotification(),
522 1
                'markdown' => $this->getMarkdown(),
523 1
                'channel' => $this->getChannel(),
524 1
                'user' => $this->getUser(),
525 1
                'attachments' => $this->getAttachments(),
526
            ],
527 1
            function ($value, $key) {
528
                return ! (
529 1
                    is_null($value) ||
530 1
                    ($key === 'markdown' && $value === true) ||
531 1
                    (is_array($value) && empty($value))
532
                );
533 1
            },
534 1
            ARRAY_FILTER_USE_BOTH
535
        );
536
    }
537
538
    /**
539
     * Convert the message to JSON string.
540
     *
541
     * @param  int  $options
542
     * @return string
543
     */
544
    public function toJson($options = 0)
545
    {
546
        return json_encode($this->jsonSerialize(), $options);
547
    }
548
549
    /**
550
     * Serializes the object to a value that can be serialized natively by json_encode().
551
     *
552
     * @return array
553
     */
554
    public function jsonSerialize()
555
    {
556
        return $this->toArray();
557
    }
558
559
    /**
560
     * Send the message.
561
     *
562
     * The parameters can be `($text, $markdown, $notification)`, and the $text and
563
     * the $notification can be `null` that does not modify the exist field.
564
     * The parameters can also be
565
     * `($text, $attachment_text, $attachment_title, $attachment_images, $attachment_color)`.
566
     *
567
     * @return bool
568
     */
569
    public function send()
570
    {
571
        if (! $this->client) {
572
            return false;
573
        }
574
575
        if ($count = func_num_args()) {
576
            $firstArg = func_get_arg(0);
577
578
            if (1 === $count && (is_array($firstArg) || is_object($firstArg))) {
579
                return $this->client->sendMessage($firstArg);
580
            }
581
582
            if (! is_null($firstArg)) {
583
                $this->setText($firstArg);
584
            }
585
586
            if ($count > 1 && is_bool(func_get_arg(1))) {
587
                $this->setMarkdown(func_get_arg(1));
588
589
                if ($count > 2 && ! is_null(func_get_arg(2))) {
590
                    $this->setNotification(func_get_arg(2));
591
                }
592
            } elseif ($count > 1) {
593
                call_user_func_array(
594
                    [$this, 'addAttachment'],
595
                    array_slice(func_get_args(), 1)
596
                );
597
            }
598
        }
599
600
        return $this->client->sendMessage($this);
601
    }
602
603
    /**
604
     * Send the message to the given target.
605
     *
606
     * @param  mixed  $target
607
     * @return bool
608
     */
609
    public function sendTo($target)
610
    {
611
        $this->to($target);
612
613
        return call_user_func_array([$this, 'send'], array_slice(func_get_args(), 1));
614
    }
615
616
    /**
617
     * Convert the message to its string representation.
618
     *
619
     * @return string
620
     */
621
    public function __toString()
622
    {
623
        return $this->toJson();
624
    }
625
}
626