EventMiddleware::execute()   B
last analyzed

Complexity

Conditions 5
Paths 13

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 28
rs 8.439
cc 5
eloc 16
nc 13
nop 2
1
<?php
2
3
namespace TillKruss\LaravelTactician\Middleware;
4
5
use Exception;
6
use Throwable;
7
use League\Tactician\Middleware;
8
use Illuminate\Contracts\Events\Dispatcher;
9
use TillKruss\LaravelTactician\Events\CommandFailed;
10
use TillKruss\LaravelTactician\Events\CommandHandled;
11
use TillKruss\LaravelTactician\Events\CommandReceived;
12
13
class EventMiddleware implements Middleware
14
{
15
    /**
16
     * The event dispatcher instance.
17
     *
18
     * @var \Illuminate\Contracts\Events\Dispatcher
19
     */
20
    protected $dispatcher;
21
22
    /**
23
     * Create a new command events middleware.
24
     *
25
     * @param \Illuminate\Contracts\Events\Dispatcher  $dispatcher
26
     */
27
    public function __construct(Dispatcher $dispatcher)
28
    {
29
        $this->dispatcher = $dispatcher;
30
    }
31
32
    /**
33
     * Dispatch an event whenever a command is received, handled or fails.
34
     *
35
     * @param  object    $command
36
     * @param  callable  $next
37
     * @return mixed
38
     *
39
     * @throws Exception
40
     * @throws Throwable
41
     */
42
    public function execute($command, callable $next)
43
    {
44
        try {
45
            $this->dispatcher->fire('command.received', new CommandReceived($command));
46
47
            $returnValue = $next($command);
48
49
            $this->dispatcher->fire('command.handled', new CommandHandled($command));
50
51
            return $returnValue;
52
        } catch (Exception $exception) {
53
            $event = new CommandFailed($command, $exception);
54
55
            $this->dispatcher->fire('command.failed', $event);
56
57
            if (! $event->isExceptionCaught()) {
58
                throw $exception;
59
            }
60
        } catch (Throwable $exception) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
61
            $event = new CommandFailed($command, $exception);
62
63
            $this->dispatcher->fire('command.failed', $event);
64
65
            if (! $event->isExceptionCaught()) {
66
                throw $exception;
67
            }
68
        }
69
    }
70
}
71