Passed
Push — main ( 8a9455...e00516 )
by Michael
03:45
created

HandlesDatabaseTransactions::withTransaction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MichaelRubel\EnhancedPipeline\Traits;
6
7
use Illuminate\Support\Facades\DB;
8
9
trait HandlesDatabaseTransactions
10
{
11
    /**
12
     * Determines whether class uses transaction.
13
     *
14
     * @var bool
15
     */
16
    protected bool $useTransaction = false;
17
18
    /**
19
     * Enable transaction in pipeline.
20
     *
21
     * @return static
22
     */
23 2
    public function withTransaction(): static
24
    {
25 2
        $this->useTransaction = true;
26
27 2
        return $this;
28
    }
29
30
    /**
31
     * Begin the transaction if enabled.
32
     *
33
     * @return void
34
     */
35 20
    protected function beginTransaction(): void
36
    {
37 20
        if (! $this->useTransaction) {
38 18
            return;
39
        }
40
41 2
        DB::beginTransaction();
42
    }
43
44
    /**
45
     * Commit the transaction if enabled.
46
     *
47
     * @return void
48
     */
49 12
    protected function commitTransaction(): void
50
    {
51 12
        if (! $this->useTransaction) {
52 11
            return;
53
        }
54
55 1
        DB::commit();
56
    }
57
58
    /**
59
     * Rollback the transaction if enabled.
60
     *
61
     * @return void
62
     */
63 4
    protected function rollbackTransaction(): void
64
    {
65 4
        if (! $this->useTransaction) {
66 3
            return;
67
        }
68
69 1
        DB::rollBack();
70
    }
71
}
72