BakeryTransactionalAware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 9
c 1
b 0
f 0
dl 0
loc 55
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A bootBakeryTransactionalAware() 0 4 1
A startTransaction() 0 4 1
A endTransaction() 0 4 1
A inTransaction() 0 3 1
1
<?php
2
3
namespace Bakery\Eloquent\Traits;
4
5
use Illuminate\Support\Facades\Event;
6
use Illuminate\Database\Eloquent\Model;
7
8
trait BakeryTransactionalAware
9
{
10
    protected $inTransaction = false;
11
12
    /**
13
     * Fire the given event for the model.
14
     *
15
     * @param  string  $event
16
     * @param  bool  $halt
17
     * @return mixed
18
     */
19
    abstract protected function fireModelEvent($event, $halt = true);
20
21
    /**
22
     * The "booting" method of the Bakery events trait.
23
     *
24
     * @return void
25
     */
26
    public static function bootBakeryTransactionalAware()
27
    {
28
        Event::listen('eloquent.booted: '.static::class, function (Model $model) {
29
            $model->addObservableEvents(['persisting', 'persisted']);
30
        });
31
    }
32
33
    /**
34
     * Start the transaction for this model.
35
     *
36
     * @return void
37
     */
38
    public function startTransaction()
39
    {
40
        $this->inTransaction = true;
41
        $this->fireModelEvent('persisting');
42
    }
43
44
    /**
45
     * End the transaction for this model.
46
     *
47
     * @return void
48
     */
49
    public function endTransaction()
50
    {
51
        $this->inTransaction = false;
52
        $this->fireModelEvent('persisted');
53
    }
54
55
    /**
56
     * Return if the model is currently in transaction.
57
     *
58
     * @return bool
59
     */
60
    public function inTransaction(): bool
61
    {
62
        return $this->inTransaction;
63
    }
64
}
65