Completed
Pull Request — master (#52)
by
unknown
02:40
created

EventCollection::handle()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 15
ccs 12
cts 12
cp 1
rs 8.8571
cc 5
eloc 8
nc 5
nop 1
crap 5
1
<?php
2
3
namespace TelegramBot\Api\Events;
4
5
use Closure;
6
use ReflectionFunction;
7
use TelegramBot\Api\Botan;
8
use TelegramBot\Api\Types\Update;
9
10
class EventCollection
11
{
12
    /**
13
     * Array of events.
14
     *
15
     * @var array
16
     */
17
    protected $events;
18
19
    /**
20
     * Botan tracker
21
     *
22
     * @var \TelegramBot\Api\Botan
23
     */
24
    protected $tracker;
25
26
    /**
27
     * EventCollection constructor.
28
     *
29
     * @param string $trackerToken
30
     */
31 13
    public function __construct($trackerToken = null)
32
    {
33 13
        if ($trackerToken) {
34 2
            $this->tracker = new Botan($trackerToken);
35 2
        }
36 13
    }
37
38
39
    /**
40
     * Add new event to collection
41
     *
42
     * @param Closure $event
43
     * @param Closure|null $checker
44
     *
45
     * @return \TelegramBot\Api\Events\EventCollection
46
     */
47 4
    public function add(Closure $event, $checker = null)
48
    {
49 4
        $this->events[] = !is_null($checker) ? new Event($event, $checker)
50 1
            : new Event($event, function () {
51
                return true;
52 1
            });
53
54 4
        return $this;
55
    }
56
57
    /**
58
     * @param \TelegramBot\Api\Types\Update
59
     */
60 2
    public function handle(Update $update)
61
    {
62 2
        foreach ($this->events as $event) {
63
            /* @var \TelegramBot\Api\Events\Event $event */
64 2
            if ($event->executeChecker($update) === true) {
65 2
                if (false === $event->executeAction($update)) {
66 1
                    if (!is_null($this->tracker)) {
67 1
                        $checker = new ReflectionFunction($event->getChecker());
68 1
                        $this->tracker->track($update->getMessage(), $checker->getStaticVariables()['name']);
69 1
                    }
70 1
                    break;
71
                }
72 1
            }
73 2
        }
74 2
    }
75
}
76