Completed
Push — master ( 5edef7...e95395 )
by Mattias
02:05
created

ReactRunner   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 53
rs 10
c 1
b 1
f 0
ccs 21
cts 21
cp 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 7 1
A __construct() 0 4 1
A setLoopTimeout() 0 4 1
A runBot() 0 16 3
1
<?php
2
namespace TelegramBot;
3
4
use React\EventLoop\Factory as EventLoopFactory;
5
6
use React\EventLoop\LoopInterface;
7
8
/**
9
 * @class TelegramBot\ReactRunner
10
 *
11
 * runner for a bot using react event loop
12
 */
13
class ReactRunner implements RunnerInterface
14
{
15 1
    public static function create() :ReactRunner
16
    {
17
        /** @var LoopInterface */
18 1
      $loop = EventLoopFactory::create();
19
20 1
        return new self($loop);
21
    }
22
23
    /** @var LoopInterface */
24
    private $loop;
25
    /** @var int */
26
    private $loopTimeout = 2;
27
    /** @var int */
28
    private $loopCounter = 0;
29
30
31
    /**
32
     * @param \React\EventLoop\LoopInterface
33
     * @param \React\HttpClient\Client
34
     */
35 4
    public function __construct(LoopInterface $loop)
36
    {
37 4
        $this->loop = $loop;
38 4
    }
39
40 1
    public function setLoopTimeout(int $timeout)
41
    {
42 1
      $this->loopTimeout = $timeout;
43 1
    }
44
45
    /**
46
     * @param BotInterface
47
     * @param integer $maxTimesToPoll
48
     */
49 2
    public function runBot(BotInterface $bot, $maxTimesToPoll = null)
50
    {
51 2
        $this->loopCounter = 0;
52
53 2
        $this->loop->addPeriodicTimer(
54 2
          $this->loopTimeout,
55 2
          function (\React\EventLoop\Timer\Timer $timer) use ($bot, $maxTimesToPoll) {
56 2
            $bot->poll();
57 1
            $this->loopCounter++;
58 1
            if (!is_null($maxTimesToPoll) && ($maxTimesToPoll >= $this->loopCounter)) {
59 1
                $this->loop->cancelTimer($timer);
60
            }
61 2
        });
62
63 2
        $this->loop->run();
64 1
    }
65
}
66