OnExceptionCases   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 27
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A invoke() 0 5 1
A __construct() 0 6 1
A handle() 0 6 2
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\CommandHandling;
4
5
use Throwable;
6
7
/**
8
 * Decorator that invokes the middleware when handling a command failed.
9
 *
10
 * Used to configure middleware that runs when an exception is encountered.
11
 * Such middleware could, for example:
12
 * - log the exception
13
 * - roll back a unit of work or database transaction
14
 * - etc
15
 */
16
final class OnExceptionCases implements Handler
17
{
18
    private $middleware;
19
    private $handler;
20
21
    private function __construct(
22
        ExceptionPathMiddleware $middleware,
23
        Handler $handler
24
    ) {
25
        $this->middleware = $middleware;
26
        $this->handler = $handler;
27
    }
28
29
    public static function invoke(
30
        ExceptionPathMiddleware $middleware,
31
        Handler $handler
32
    ): Handler {
33
        return new self($middleware, $handler);
34
    }
35
36
    /** @inheritdoc */
37
    public function handle(object $command): void
38
    {
39
        try {
40
            $this->handler->handle($command);
41
        } catch (Throwable $exception) {
42
            $this->middleware->invoke($command, $exception);
43
        }
44
    }
45
}
46