TransactionMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace Isolate\Tactician;
4
5
use Isolate\Isolate;
6
use League\Tactician\Middleware;
7
8
final class TransactionMiddleware implements Middleware
9
{
10
    /**
11
     * @var Isolate
12
     */
13
    private $isolate;
14
    /**
15
     * @var string
16
     */
17
    private $contextName;
18
19
    /**
20
     * @param Isolate $isolate
21
     * @param string $contextName
22
     */
23
    public function __construct(Isolate $isolate, $contextName = Isolate::DEFAULT_CONTEXT)
24
    {
25
        $this->isolate = $isolate;
26
        $this->contextName = $contextName;
27
    }
28
29
    /**
30
     * @param object $command
31
     * @param callable $next
32
     * @return mixed
33
     * @throws \Exception
34
     */
35
    public function execute($command, callable $next)
36
    {
37
        $context = $this->isolate->getContext($this->contextName);
38
        $transaction = $context->hasOpenTransaction() ? $context->getTransaction() : $context->openTransaction();
39
40
        try {
41
            $returnValue = $next($command);
42
43
            $context->closeTransaction();
44
45
            return $returnValue;
46
        } catch (\Exception $e) {
47
            $transaction->rollback();
48
            throw $e;
49
        }
50
    }
51
}