Completed
Pull Request — master (#27)
by Frederic
04:50 queued 02:40
created

SendMetricOnMessageConsumed::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 11
cts 11
cp 1
rs 9.7333
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Burrow\Event\Listener\Metric;
4
5
use Burrow\Clock;
6
use Burrow\Event\Listener\ListenerException;
7
use Burrow\Event\MessageConsumed;
8
use Burrow\Event\MessageReceived;
9
use Burrow\Metric\MetricService;
10
use Burrow\RealClock;
11
use League\Event\EventInterface;
12
use League\Event\ListenerInterface;
13
14
class SendMetricOnMessageConsumed implements ListenerInterface
15
{
16
    /** @var MetricService */
17
    private $metricService;
18
19
    /** @var Clock */
20
    private $clock;
21
22
    /** @var null|float */
23
    private $messageReceivedAt;
24
25
    /**
26
     * SendMetricOnMessageConsumed constructor.
27
     *
28
     * @param MetricService $metricService
29
     * @param Clock|null    $clock
30
     */
31 9
    public function __construct(MetricService $metricService, Clock $clock = null)
32
    {
33 9
        $this->metricService = $metricService;
34 9
        $this->clock = $clock ?: new RealClock();
35 9
    }
36
37
    /**
38
     * @param EventInterface | MessageConsumed $event
39
     *
40
     * @throws ListenerException
41
     */
42 6
    public function handle(EventInterface $event)
43
    {
44 6
        if ($event instanceof MessageReceived) {
45 3
            $this->messageReceivedAt = $this->clock->timestampInMs();
46 3
            return;
47
        }
48
49 6
        if (!($event instanceof MessageConsumed)) {
50 3
            throw ListenerException::badEventGiven($event);
51
        }
52
53 3
        $this->metricService->timing(
54 3
            'worker.message_consumed',
55 3
            $this->clock->timestampInMs() - $this->messageReceivedAt
56 2
        );
57 3
    }
58
59
    public function isListener($listener)
60
    {
61
        return $listener === $this;
62
    }
63
}
64