Option::afterSave()   A
last analyzed

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 0
1
<?php namespace Bedard\Shop\Models;
2
3
use Exception;
4
use Lang;
5
use Model;
6
7
/**
8
 * Option Model.
9
 */
10
class Option extends Model
11
{
12
    use \October\Rain\Database\Traits\Purgeable,
13
        \October\Rain\Database\Traits\Validation;
14
15
    /**
16
     * @var string The database table used by the model.
17
     */
18
    public $table = 'bedard_shop_options';
19
20
    /**
21
     * @var array Default attributes
22
     */
23
    public $attributes = [
24
        'name' => '',
25
        'placeholder' => '',
26
        'sort_order' => 0,
27
    ];
28
29
    /**
30
     * @var array Attribute casting
31
     */
32
    protected $casts = [
33
        'id' => 'integer',
34
    ];
35
36
    /**
37
     * @var array Guarded fields
38
     */
39
    protected $guarded = ['*'];
40
41
    /**
42
     * @var array Fillable fields
43
     */
44
    protected $fillable = [
45
        'name',
46
        'placeholder',
47
        'sort_order',
48
        'value_data',
49
    ];
50
51
    /**
52
     * @var array Purgeable fields
53
     */
54
    public $purgeable = [
55
        'value_data',
56
    ];
57
58
    /**
59
     * @var array Relations
60
     */
61
    public $belongsTo = [
62
        'product' => [
63
            'Bedard\Shop\Models\Product',
64
        ],
65
    ];
66
67
    public $hasMany = [
68
        'values' => [
69
            'Bedard\Shop\Models\OptionValue',
70
            'delete' => true,
71
            'order' => 'sort_order asc',
72
        ],
73
    ];
74
75
    /**
76
     * @var array Validation
77
     */
78
    public $rules = [
79
        'name' => 'required',
80
    ];
81
82
    /**
83
     * After save.
84
     *
85
     * @return void
86
     */
87
    public function afterSave()
88
    {
89
        $this->saveValues();
90
    }
91
92
    /**
93
     * After validate.
94
     *
95
     * @return void
96
     */
97
    public function afterValidate()
98
    {
99
        $this->validateValues();
100
    }
101
102
    /**
103
     * Save related values.
104
     *
105
     * @return void
106
     */
107
    protected function saveValues()
108
    {
109
        $values = $this->getOriginalPurgeValue('value_data') ?: [];
110
111
        if (count($values)) {
112
            foreach ($values as $value) {
113
                $model = $value['id'] !== null
114
                        ? OptionValue::findOrNew($value['id'])
115
                        : new OptionValue;
116
117 View Code Duplication
                if (array_key_exists('_deleted', $value) && $value['_deleted'] && $model->exists()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
                    // delete the model if it has the _deleted flag
119
                    $model->delete();
120
                } else {
121
                    // otherwise update the model's values
122
                    $model->name = $value['name'];
123
                    $model->option_id = $this->id;
124
                    $model->sort_order = $value['sort_order'];
125
                    $model->save();
126
                }
127
            }
128
        }
129
    }
130
131
    /**
132
     * Validate option values.
133
     *
134
     * @return void
135
     */
136
    protected function validateValues()
137
    {
138
        $names = [];
139
        $values = $this->value_data ?: [];
140
141
        // don't validate deleted values
142
        $nonDeletedValues = array_filter($values, function ($value) {
143
            return ! array_key_exists('_deleted', $value) || ! $value['_deleted'];
144
        });
145
146
        foreach ($nonDeletedValues as $value) {
147
            // validate each value individually
148
            $model = new OptionValue($value);
149
            $model->validate();
150
151
            // ensure that the name is unique to this option
152
            if (in_array($value['name'], $names)) {
153
                throw new Exception(Lang::get('bedard.shop::lang.options.form.values_unique'));
154
            }
155
156
            $names[] = $value['name'];
157
        }
158
159
        // ensure that at least one value was provided
160
        if (count($names) < 1) {
161
            throw new Exception(Lang::get('bedard.shop::lang.options.form.values_required'));
162
        }
163
    }
164
}
165