TransactionTrait::handleTransaction()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 18
c 0
b 0
f 0
ccs 11
cts 11
cp 1
rs 9.4285
cc 3
eloc 12
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Buttress\ConcreteClient\Transaction;
4
5
use Buttress\ConcreteClient\Exception\TransactionException;
6
7
trait TransactionTrait
8
{
9
    private $transacting = false;
10
11 10
    public function __invoke(callable $transaction)
12
    {
13 10
        return $this->handleTransaction($transaction);
14
    }
15
16 16
    protected function handleTransaction(callable $transaction)
17
    {
18 16
        $this->transacting = true;
19
        try {
20 16
            $result = $transaction();
21 12
        } catch (\Exception $e) {
22 5
            $this->transacting = false;
23
            // Catch any exceptions
24 5
            throw new TransactionException('Transaction raised an exception: ' . $e->getMessage(), 500, $e);
25 1
        } catch (\Throwable $e) {
26 1
            $this->transacting = false;
27
            // Catch extra stuff in PHP 7+
28 1
            throw new TransactionException('Transaction raised an exception: ' . $e->getMessage(), 500, $e);
29
        }
30 10
        $this->transacting = false;
31
32 10
        return $result;
33
    }
34
35 16
    public function __destruct()
36
    {
37 16
        if ($this->transacting) {
38
            throw new TransactionException('Transaction exited prematurely.');
39
        }
40 16
    }
41
42 10
    public static function transact(callable $callable)
43
    {
44 10
        $transaction = new static;
45 10
        return $transaction($callable);
46
    }
47
}
48