BakeryTransactionalAware::endTransaction()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
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