Completed
Push — master ( c389b9...cf77f1 )
by Anton
10:39 queued 06:52
created

TransactionMiddleware::addCommand()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * spiral
4
 *
5
 * @author    Wolfy-J
6
 */
7
8
namespace Spiral\Http\Middlewares;
9
10
use Psr\Http\Message\ResponseInterface as Response;
11
use Psr\Http\Message\ServerRequestInterface as Request;
12
use Spiral\Http\MiddlewareInterface;
13
use Spiral\ORM\CommandInterface;
14
use Spiral\ORM\TransactionInterface;
15
16
class TransactionMiddleware implements TransactionInterface, MiddlewareInterface
17
{
18
    /**
19
     * @var TransactionInterface
20
     */
21
    private $transaction;
22
23
    /**
24
     * @var bool
25
     */
26
    private $enabled = true;
27
28
    /**
29
     * @param \Spiral\ORM\TransactionInterface $transaction
30
     * @param bool                             $enabled
31
     */
32
    public function __construct(TransactionInterface $transaction, bool $enabled = true)
33
    {
34
        $this->transaction = $transaction;
35
        $this->enabled = $enabled;
36
    }
37
38
    /**
39
     * @param \Psr\Http\Message\ServerRequestInterface $request
40
     * @param \Psr\Http\Message\ResponseInterface      $response
41
     * @param callable                                 $next
42
     *
43
     * @return mixed
44
     */
45
    public function __invoke(Request $request, Response $response, callable $next)
46
    {
47
        try {
48
            return $next($request, $response);
49
        } finally {
50
            if ($this->enabled) {
51
                //By outer transaction
52
                $this->transaction->run();
53
            }
54
        }
55
    }
56
57
    /**
58
     * @param \Spiral\ORM\CommandInterface $command
59
     */
60
    public function addCommand(CommandInterface $command)
61
    {
62
        return $this->transaction->addCommand($command);
63
    }
64
65
    /**
66
     * Forwarded to outer tranasction.
67
     */
68
    public function run()
69
    {
70
        $this->transaction->run();
71
    }
72
}