Passed
Pull Request — master (#288)
by Arman
02:44
created

TransactionTrait::commit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Quantum\Libraries\Database\Traits;
4
5
use Quantum\Libraries\Database\Exceptions\DatabaseException;
6
use Quantum\App\Exceptions\BaseException;
7
use Throwable;
8
9
/**
10
 * Trait TransactionTrait
11
 * @package Quantum\Libraries\Database
12
 */
13
trait TransactionTrait
14
{
15
16
    /**
17
     * Begins a transaction
18
     * @throws BaseException
19
     */
20
    public static function beginTransaction(): void
21
    {
22
        self::resolveTransaction(__FUNCTION__);
23
    }
24
25
    /**
26
     * Commits a transaction
27
     * @throws BaseException
28
     * @throws DatabaseException
29
     */
30
    public static function commit(): void
31
    {
32
        self::resolveTransaction(__FUNCTION__);
33
    }
34
35
    /**
36
     * Rolls back a transaction
37
     * @throws BaseException
38
     */
39
    public static function rollback(): void
40
    {
41
        self::resolveTransaction(__FUNCTION__);
42
    }
43
44
    /**
45
     * Resolves the transaction method call
46
     * @param string $method
47
     * @return mixed
48
     * @throws BaseException
49
     */
50
    protected static function resolveTransaction(string $method)
51
    {
52
        $db = self::getInstance()->getOrmClass();
53
54
        if (!method_exists($db, $method)) {
55
            throw DatabaseException::methodNotSupported($method, __CLASS__);
56
        }
57
58
        return $db::$method();
59
    }
60
61
    /**
62
     * Transaction wrapper using a closure
63
     * @param callable $callback
64
     * @return mixed
65
     * @throws BaseException
66
     * @throws DatabaseException
67
     * @throws Throwable
68
     */
69
    public static function transaction(callable $callback)
70
    {
71
        self::beginTransaction();
72
73
        try {
74
            $result = $callback();
75
            self::commit();
76
            return $result;
77
        } catch (Throwable $e) {
78
            self::rollback();
79
            throw $e;
80
        }
81
    }
82
}