LoggerEventBusMiddleware::__invoke()   A
last analyzed

Complexity

Conditions 3
Paths 5

Size

Total Lines 12
Code Lines 8

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
dl 12
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 5
nop 2
1
<?php
2
3
namespace NilPortugues\MessageBus\EventBus;
4
5
use Exception;
6
use NilPortugues\MessageBus\EventBus\Contracts\Event;
7
use NilPortugues\MessageBus\EventBus\Contracts\EventBusMiddleware as EventBusMiddlewareInterface;
8
use Psr\Log\LoggerInterface;
9
10
/**
11
 * Class LoggerEventBusMiddleware.
12
 */
13 View Code Duplication
class LoggerEventBusMiddleware implements EventBusMiddlewareInterface
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
14
{
15
    /** @var LoggerInterface */
16
    protected $logger;
17
18
    /**
19
     * CachingEventBus constructor.
20
     *
21
     * @param LoggerInterface $logger
22
     */
23
    public function __construct(LoggerInterface $logger)
24
    {
25
        $this->logger = $logger;
26
    }
27
28
    /**
29
     * @param Event         $event
30
     * @param callable|null $next
31
     */
32
    public function __invoke(Event $event, callable $next = null)
33
    {
34
        try {
35
            if ($next) {
36
                $this->preEventLog($event);
37
                $next($event);
38
                $this->postEventLog($event);
39
            }
40
        } catch (Exception $e) {
41
            $this->logException($e);
42
        }
43
    }
44
45
    /**
46
     * @param Event $event
47
     */
48
    protected function preEventLog(Event $event)
49
    {
50
        $this->logger->info(sprintf('Starting %s handling.', get_class($event)));
51
    }
52
53
    /**
54
     * @param Event $event
55
     */
56
    protected function postEventLog(Event $event)
57
    {
58
        $this->logger->info(sprintf('%s was handled successfully.', get_class($event)));
59
    }
60
61
    /**
62
     * @param Exception $e
63
     */
64
    protected function logException(Exception $e)
65
    {
66
        $this->logger->alert(sprintf('[%s:%s] %s', $e->getFile(), $e->getLine(), $e->getMessage()));
67
    }
68
}
69