Passed
Push — master ( cc9e47...487c66 )
by Alexander
02:55
created

Transaction::call()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 15
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 11
nc 4
nop 2
crap 20
1
<?php
2
3
4
namespace Horat1us\Yii\Database;
5
6
use Horat1us\Yii\Interfaces\TransactionInterface;
7
8
use yii\db\Connection;
9
10
11
/**
12
 * Class Transaction
13
 * @package Horat1us\Yii\Database
14
 */
15
class Transaction implements TransactionInterface
16
{
17
    /** @var  Connection */
18
    protected $connection;
19
20
    /**
21
     * Transaction constructor.
22
     * @param Connection $connection
23
     */
24
    public function __construct(Connection $connection)
25
    {
26
        $this->connection = $connection;
27
    }
28
29
    /**
30
     * @param callable $callable
31
     * @param array ...$args
32
     * @return mixed
33
     * @throws \Throwable
34
     */
35
    public function call(callable $callable, ...$args)
36
    {
37
        if ($this->connection->transaction && $this->connection->transaction->isActive) {
38
            return call_user_func_array($callable, $args);
39
        }
40
41
        $transaction = $this->connection->beginTransaction();
42
        try {
43
            $result = call_user_func_array($callable, $args);
44
45
            $transaction->commit();
46
47
            return $result;
48
        } catch (\Throwable $exception) {
49
            $transaction->rollBack();
50
51
            throw $exception;
52
        }
53
    }
54
}