LoggerCommandBusMiddleware::__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\CommandBus;
4
5
use Exception;
6
use NilPortugues\MessageBus\CommandBus\Contracts\Command;
7
use NilPortugues\MessageBus\CommandBus\Contracts\CommandBusMiddleware as CommandBusMiddlewareInterface;
8
use Psr\Log\LoggerInterface;
9
10 View Code Duplication
class LoggerCommandBusMiddleware implements CommandBusMiddlewareInterface
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...
11
{
12
    /** @var LoggerInterface */
13
    protected $logger;
14
15
    /**
16
     * CachingCommandBus constructor.
17
     *
18
     * @param LoggerInterface $logger
19
     */
20
    public function __construct(LoggerInterface $logger)
21
    {
22
        $this->logger = $logger;
23
    }
24
25
    /**
26
     * @param Command       $command
27
     * @param callable|null $next
28
     */
29
    public function __invoke(Command $command, callable $next = null)
30
    {
31
        try {
32
            if ($next) {
33
                $this->preCommandLog($command);
34
                $next($command);
35
                $this->postCommandLog($command);
36
            }
37
        } catch (Exception $e) {
38
            $this->logException($e);
39
        }
40
    }
41
42
    /**
43
     * @param Command $command
44
     */
45
    protected function preCommandLog(Command $command)
46
    {
47
        $this->logger->info(sprintf('Starting %s handling.', get_class($command)));
48
    }
49
50
    /**
51
     * @param Command $command
52
     */
53
    protected function postCommandLog(Command $command)
54
    {
55
        $this->logger->info(sprintf('%s was handled successfully.', get_class($command)));
56
    }
57
58
    /**
59
     * @param Exception $e
60
     */
61
    protected function logException(Exception $e)
62
    {
63
        $this->logger->alert(sprintf('[%s:%s] %s', $e->getFile(), $e->getLine(), $e->getMessage()));
64
    }
65
}
66