TransactionTrait   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 95%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 41
ccs 19
cts 20
cp 0.95
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 4 1
A handleTransaction() 0 18 3
A __destruct() 0 6 2
A transact() 0 5 1
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