Completed
Pull Request — develop (#132)
by
unknown
01:16
created

Attribute::boot()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
cc 4
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Attributes\Models;
6
7
use Illuminate\Support\Str;
8
use Spatie\Sluggable\SlugOptions;
9
use Rinvex\Support\Traits\HasSlug;
10
use Spatie\EloquentSortable\Sortable;
11
use Illuminate\Database\Eloquent\Model;
12
use Rinvex\Support\Traits\HasTranslations;
13
use Rinvex\Support\Traits\ValidatingTrait;
14
use Spatie\EloquentSortable\SortableTrait;
15
use Illuminate\Database\Eloquent\Relations\HasMany;
16
17
/**
18
 * Rinvex\Attributes\Models\Attribute.
19
 *
20
 * @property int                 $id
21
 * @property string              $slug
22
 * @property array               $name
23
 * @property array               $description
24
 * @property int                 $sort_order
25
 * @property string              $group
26
 * @property string              $type
27
 * @property bool                $is_required
28
 * @property bool                $is_collection
29
 * @property string              $default
30
 * @property \Carbon\Carbon|null $created_at
31
 * @property \Carbon\Carbon|null $updated_at
32
 * @property array               $entities
33
 * @property-read \Rinvex\Attributes\Support\ValueCollection|\Rinvex\Attributes\Models\Value[] $values
34
 *
35
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute ordered($direction = 'asc')
36
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereCreatedAt($value)
37
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereDefault($value)
38
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereDescription($value)
39
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereGroup($value)
40
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereId($value)
41
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereIsCollection($value)
42
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereIsRequired($value)
43
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereSlug($value)
44
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereSortOrder($value)
45
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereName($value)
46
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereType($value)
47
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Attributes\Models\Attribute whereUpdatedAt($value)
48
 * @mixin \Eloquent
49
 */
50
class Attribute extends Model implements Sortable
51
{
52
    use HasSlug;
53
    use SortableTrait;
54
    use HasTranslations;
55
    use ValidatingTrait;
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    protected $fillable = [
61
        'name',
62
        'slug',
63
        'description',
64
        'sort_order',
65
        'group',
66
        'type',
67
        'is_required',
68
        'is_collection',
69
        'default',
70
        'entities',
71
    ];
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    protected $casts = [
77
        'slug' => 'string',
78
        'sort_order' => 'integer',
79
        'group' => 'string',
80
        'type' => 'string',
81
        'is_required' => 'boolean',
82
        'is_collection' => 'boolean',
83
        'default' => 'string',
84
    ];
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    protected $observables = [
90
        'validating',
91
        'validated',
92
    ];
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    public $translatable = [
98
        'name',
99
        'description',
100
    ];
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public $sortable = [
106
        'order_column_name' => 'sort_order',
107
    ];
108
109
    /**
110
     * The entities that need to be attached to this attribute.
111
     *
112
     * @var mixed
113
     */
114
    protected $entitiesToSave = false;
115
116
    /**
117
     * The default rules that the model will validate against.
118
     *
119
     * @var array
120
     */
121
    protected $rules = [];
122
123
    /**
124
     * Whether the model should throw a
125
     * ValidationException if it fails validation.
126
     *
127
     * @var bool
128
     */
129
    protected $throwValidationExceptions = true;
130
131
    /**
132
     * An array to map class names to their type names in database.
133
     *
134
     * @var array
135
     */
136
    protected static $typeMap = [];
137
138
    /**
139
     * {@inheritdoc}
140
     */
141
    public static function boot()
142
    {
143
        parent::boot();
144
        static::saved(function ($attribute) {
145
            if ($attribute->entitiesToSave !== false) {
146
                // Wrap this in a transaction so that we don't lose attached entities if `createMany` fails.
147
                \DB::transaction(function () use ($attribute) {
148
                    $entities = $attribute->entitiesToSave ?: [];
149
                    $attribute->entities()->delete();
150
                    ! $entities || $attribute->entities()->createMany(array_map(function ($entity) {
151
                        return ['entity_type' => $entity];
152
                    }, $entities));
153
                    $attribute->entitiesToSave = false;
154
                });
155
            }
156
            $attribute->clearAttributableCache();
157
        });
158
        static::deleted(function ($attribute) {
159
            $attribute->clearAttributableCache();
160
        });
161
    }
162
163
    /**
164
     * Create a new Eloquent model instance.
165
     *
166
     * @param array $attributes
167
     */
168
    public function __construct(array $attributes = [])
169
    {
170
        parent::__construct($attributes);
171
172
        $this->setTable(config('rinvex.attributes.tables.attributes'));
173
        $this->setRules([
174
            'name' => 'required|string|strip_tags|max:150',
175
            'description' => 'nullable|string|max:32768',
176
            'slug' => 'required|alpha_dash|max:150|unique:'.config('rinvex.attributes.tables.attributes').',slug',
177
            'sort_order' => 'nullable|integer|max:100000',
178
            'group' => 'nullable|string|strip_tags|max:150',
179
            'type' => 'required|string|strip_tags|max:150',
180
            'is_required' => 'sometimes|boolean',
181
            'is_collection' => 'sometimes|boolean',
182
            'default' => 'nullable|string|strip_tags|max:32768',
183
        ]);
184
    }
185
186
    /**
187
     * Enforce clean slugs.
188
     *
189
     * @param string $value
190
     *
191
     * @return void
192
     */
193
    public function setSlugAttribute($value): void
194
    {
195
        $this->attributes['slug'] = Str::slug($value, $this->getSlugOptions()->slugSeparator, $this->getSlugOptions()->slugLanguage);
196
    }
197
198
    /**
199
     * Set or get the type map for attribute types.
200
     *
201
     * @param array|null $map
202
     * @param bool       $merge
203
     *
204
     * @return array
205
     */
206
    public static function typeMap(array $map = null, $merge = true)
207
    {
208
        if (is_array($map)) {
209
            static::$typeMap = $merge && static::$typeMap
0 ignored issues
show
Bug Best Practice introduced by
The expression static::$typeMap of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
210
                ? $map + static::$typeMap : $map;
211
        }
212
213
        return static::$typeMap;
214
    }
215
216
    /**
217
     * Get the model associated with a custom attribute type.
218
     *
219
     * @param string $alias
220
     *
221
     * @return string|null
222
     */
223
    public static function getTypeModel($alias)
224
    {
225
        return self::$typeMap[$alias] ?? null;
226
    }
227
228
    /**
229
     * Access entities relation and retrieve entity types as an array,
230
     * Accessors/Mutators preceeds relation value when called dynamically.
231
     *
232
     * @return array
233
     */
234
    public function getEntitiesAttribute(): array
235
    {
236
        return $this->entities()->pluck('entity_type')->toArray() ?: $this->entitiesToSave ?: [];
237
    }
238
239
    /**
240
     * Set the attribute attached entities.
241
     *
242
     * @param \Illuminate\Support\Collection|array $value
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
243
     * @param mixed                                $entities
244
     *
245
     * @return void
246
     */
247
    public function setEntitiesAttribute($entities): void
248
    {
249
        $this->entitiesToSave = (array) $entities;
250
    }
251
252
    /**
253
     * Get the options for generating the slug.
254
     *
255
     * @return \Spatie\Sluggable\SlugOptions
256
     */
257
    public function getSlugOptions(): SlugOptions
258
    {
259
        return SlugOptions::create()
260
                          ->usingSeparator('_')
261
                          ->doNotGenerateSlugsOnUpdate()
262
                          ->generateSlugsFrom('name')
263
                          ->saveSlugsTo('slug');
264
    }
265
266
    /**
267
     * Get the entities attached to this attribute.
268
     *
269
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
270
     */
271
    public function entities(): HasMany
272
    {
273
        return $this->hasMany(config('rinvex.attributes.models.attribute_entity'), 'attribute_id', 'id');
274
    }
275
276
    /**
277
     * Get the entities attached to this attribute.
278
     *
279
     * @param string $value
280
     *
281
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
282
     */
283
    public function values(string $value): HasMany
284
    {
285
        return $this->hasMany($value, 'attribute_id', 'id');
286
    }
287
288
    /**
289
     * Clears the attributable cache for all entities that are attached to this attribute.
290
     *
291
     * @return void
292
     */
293
    public function clearAttributableCache()
294
    {
295
        foreach ($this->entities as $entity) {
296
            // Ensure that the class exists before creating an instance as the database
297
            // could contain a model that no longer exists.
298
            if (class_exists($entity)) {
299
                $entityInstance = app()->make($entity);
300
                $entityInstance->clearAttributableCache();
301
            }
302
        }
303
    }
304
}
305