Completed
Pull Request — master (#27)
by Frederic
02:49
created

SendMetricOnMessageConsumed   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 85.71%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 47
ccs 12
cts 14
cp 0.8571
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
A handle() 0 13 3
A isListener() 0 4 1
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('worker.message_consumed', $this->clock->timestampInMs() - $this->messageReceivedAt);
54 3
    }
55
56
    public function isListener($listener)
57
    {
58
        return $listener === $this;
59
    }
60
}
61