MessageQueue   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 67
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A push() 0 24 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Zanzara;
6
7
use React\EventLoop\LoopInterface;
8
use React\EventLoop\TimerInterface;
9
use Zanzara\Telegram\Telegram;
10
use Zanzara\Telegram\Type\Response\TelegramException;
11
12
/**
13
 *
14
 */
15
class MessageQueue
16
{
17
18
    /**
19
     * @var LoopInterface
20
     */
21
    private $loop;
22
23
    /**
24
     * @var Telegram
25
     */
26
    private $telegram;
27
28
    /**
29
     * @var ZanzaraLogger
30
     */
31
    private $logger;
32
33
    /**
34
     * @var Config
35
     */
36
    private $config;
37
38
    /**
39
     * MessageQueue constructor.
40
     * @param Telegram $telegram
41
     * @param ZanzaraLogger $logger
42
     * @param LoopInterface $loop
43
     * @param Config $config
44
     */
45
    public function __construct(Telegram $telegram, ZanzaraLogger $logger, LoopInterface $loop, Config $config)
46
    {
47
        $this->telegram = $telegram;
48
        $this->logger = $logger;
49
        $this->loop = $loop;
50
        $this->config = $config;
51
    }
52
53
    /**
54
     * @param array $chatIds
55
     * @param string $text
56
     * @param array $opt
57
     */
58
    public function push(array $chatIds, string $text, array $opt = [])
59
    {
60
        $payload = []; // indexed array of Telegram params
61
        $opt['text'] = $text;
62
        // prepare the params array for each chatId
63
        foreach ($chatIds as $chatId) {
64
            $clone = $opt;
65
            $clone['chat_id'] = $chatId;
66
            array_push($payload, $clone);
67
        }
68
        $dequeue = function (TimerInterface $timer) use (&$payload) {
69
            // if there's no more message to dequeue cancel the timer
70
            if (!$payload) {
71
                $this->loop->cancelTimer($timer);
72
                return;
73
            }
74
75
            // pop and process
76
            $params = array_pop($payload);
77
            $this->telegram->doSendMessage($params)->/** @scrutinizer ignore-call */ otherwise(function (TelegramException $error) {
78
                $this->logger->error("Failed to send message in bulk mode, reason: $error");
79
            });
80
        };
81
        $this->loop->addPeriodicTimer($this->config->getBulkMessageInterval(), $dequeue);
82
    }
83
84
}
85