OnExceptionCases::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
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