Record::delete()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
/**
3
 * Spiral, Core Components
4
 *
5
 * @author Wolfy-J
6
 */
7
8
namespace Spiral\ORM;
9
10
use Spiral\Models\ActiveEntityInterface;
11
12
/**
13
 * Adds ActiveRecord abilities to RecordEntity.
14
 */
15
abstract class Record extends RecordEntity implements ActiveEntityInterface
16
{
17
    /**
18
     * Sync entity with database, when no transaction is given ActiveRecord will create and run it
19
     * automatically.
20
     *
21
     * @param TransactionInterface|null $transaction
22
     * @param bool                      $queueRelations
23
     *
24
     * @return int
25
     */
26
    public function save(TransactionInterface $transaction = null, bool $queueRelations = true): int
27
    {
28
        /*
29
         * First, per interface agreement calculate entity state after save command being called.
30
         */
31
        if (!$this->isLoaded()) {
32
            $state = self::CREATED;
33
        } elseif (!$this->hasChanges()) {
34
            $state = self::UPDATED;
35
        } else {
36
            $state = self::UNCHANGED;
37
        }
38
39
        if (empty($transaction)) {
40
            /*
41
             * When no transaction is given we will create our own and run it immediately.
42
             */
43
            $transaction = $transaction ?? new Transaction();
44
            $transaction->store($this, $queueRelations);
45
            $transaction->run();
46
        } else {
47
            $transaction->addCommand($this->queueStore($queueRelations));
48
        }
49
50
        return $state;
51
    }
52
53
    /**
54
     * Delete entity in database, when no transaction is given ActiveRecord will create and run it
55
     * automatically.
56
     *
57
     * @param TransactionInterface|null $transaction
58
     */
59
    public function delete(TransactionInterface $transaction = null)
60
    {
61
        if (empty($transaction)) {
62
            /*
63
             * When no transaction is given we will create our own and run it immediately.
64
             */
65
            $transaction = $transaction ?? new Transaction();
66
            $transaction->delete($this);
67
            $transaction->run();
68
        } else {
69
            $transaction->addCommand($this->queueDelete());
70
        }
71
    }
72
}