Passed
Push — master ( 36ec95...f2dea1 )
by Nate
07:31
created

ModelSave::beforeSave()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipbox/spark/blob/master/LICENSE
6
 * @link       https://github.com/flipbox/spark
7
 */
8
9
namespace flipbox\spark\services\traits;
10
11
use Craft;
12
use craft\events\ModelEvent;
13
use flipbox\spark\helpers\RecordHelper;
14
use flipbox\spark\models\Model;
15
use flipbox\spark\records\Record;
16
17
/**
18
 * @package flipbox\spark\services\traits
19
 * @author Flipbox Factory <[email protected]>
20
 * @since 1.0.0
21
 */
22
trait ModelSave
23
{
24
25
    /*******************************************
26
     * ABSTRACTS
27
     *******************************************/
28
29
    /**
30
     * @param Model $model
31
     * @param bool $mirrorScenario
32
     * @return Record
33
     */
34
    abstract protected function toRecord(Model $model, bool $mirrorScenario = true): Record;
35
36
37
    /*******************************************
38
     * SAVE
39
     *******************************************/
40
41
    /**
42
     * @param Model $model
43
     * @param bool $runValidation
44
     * @param null $attributes
45
     * @param bool $mirrorScenario
46
     * @return bool
47
     * @throws \Exception
48
     */
49
    public function save(Model $model, bool $runValidation = true, $attributes = null, bool $mirrorScenario = true)
50
    {
51
52
        // Validate
53
        if ($runValidation && !$model->validate($attributes)) {
54
            Craft::info('Model not saved due to validation error.', __METHOD__);
55
            return false;
56
        }
57
58
        $isNew = (null === $model->id);
59
60
        // a 'beforeSave' event
61
        if(!$this->beforeSave($model, $isNew)) {
62
            return false;
63
        }
64
65
        // Create event
66
        $event = new ModelEvent([
67
            'isNew' => $isNew
68
        ]);
69
70
        // Db transaction
71
        $transaction = RecordHelper::beginTransaction();
72
73
        try {
74
75
            // The 'before' event
76
            if (!$model->beforeSave($event)) {
77
78
                $transaction->rollBack();
79
80
                return false;
81
            }
82
83
            $record = $this->toRecord($model, $mirrorScenario);
84
85
            // Validate
86
            if (!$record->validate($attributes)) {
87
88
                $model->addErrors($record->getErrors());
89
90
                $transaction->rollBack();
91
92
                return false;
93
94
            }
95
96
            // Insert record
97
            if (!$record->save($attributes)) {
0 ignored issues
show
Documentation introduced by
$attributes is of type null, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
98
99
                // Transfer errors to model
100
                $model->addErrors($record->getErrors());
101
102
                $transaction->rollBack();
103
104
                return false;
105
106
            }
107
108
            // Transfer record to model
109
            if ($event->isNew) {
110
                $model->id = $record->id;
111
                $model->dateCreated = $record->dateCreated;
112
                $model->uid = $record->uid;
113
            }
114
            $model->dateUpdated = $record->dateUpdated;
115
116
117
            // The 'after' event
118
            if (!$model->afterSave($event)) {
119
120
                $transaction->rollBack();
121
122
                return false;
123
124
            }
125
126
        } catch (\Exception $e) {
127
128
            $transaction->rollBack();
129
130
            throw $e;
131
132
        }
133
134
        $transaction->commit();
135
136
        // an 'afterSave' event
137
        $this->afterSave($model, $isNew);
138
139
        return true;
140
141
    }
142
143
    /**
144
     * @param Model $model
145
     * @param bool $isNew
146
     * @return bool
147
     */
148
    protected function beforeSave(Model $model, bool $isNew): bool
0 ignored issues
show
Unused Code introduced by
The parameter $model is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $isNew is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
149
    {
150
        return true;
151
    }
152
153
    /**
154
     * @param Model $model
155
     * @param bool $isNew
156
     */
157
    protected function afterSave(Model $model, bool $isNew)
0 ignored issues
show
Unused Code introduced by
The parameter $isNew is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
158
    {
159
160
        Craft::info(sprintf(
161
            "Model '%s' with ID '%s' was saved successfully.",
162
            (string) get_class($model),
163
            (string) $model->id
164
        ), __METHOD__);
165
166
    }
167
168
}
169