| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Models; |
| 4 |
use FluentCart\Framework\Support\Str; |
| 5 |
|
| 6 |
/** |
| 7 |
* Meta Model - DB Model for Meta table |
| 8 |
* |
| 9 |
* Database Model |
| 10 |
* |
| 11 |
* @package FluentCart\App\Models |
| 12 |
* |
| 13 |
* @version 1.0.0 |
| 14 |
*/ |
| 15 |
class TaxClass extends Model |
| 16 |
{ |
| 17 |
protected $table = 'fct_tax_classes'; |
| 18 |
|
| 19 |
protected $primaryKey = 'id'; |
| 20 |
|
| 21 |
protected $guarded = [ 'id' ]; |
| 22 |
|
| 23 |
protected $fillable = [ |
| 24 |
'title', |
| 25 |
'meta', |
| 26 |
'slug' |
| 27 |
]; |
| 28 |
|
| 29 |
protected static function booted() |
| 30 |
{ |
| 31 |
static::creating(function ($model) { |
| 32 |
if (!$model->slug) { |
| 33 |
$model->slug = static::generateUniqueSlug($model->title); |
| 34 |
} |
| 35 |
}); |
| 36 |
|
| 37 |
static::updating(function ($model) { |
| 38 |
$protectedSlugs = ['standard', 'reduced', 'zero']; |
| 39 |
if ($model->isDirty('title') && !in_array($model->getOriginal('slug'), $protectedSlugs, true)) { |
| 40 |
$model->slug = static::generateUniqueSlug($model->title, $model->id); |
| 41 |
} |
| 42 |
}); |
| 43 |
} |
| 44 |
|
| 45 |
protected static function generateUniqueSlug($title, $ignoreId = null) |
| 46 |
{ |
| 47 |
$base = Str::slug($title); |
| 48 |
if (!$base) { |
| 49 |
$base = 'tax-class'; |
| 50 |
} |
| 51 |
|
| 52 |
$slug = $base; |
| 53 |
$suffix = 2; |
| 54 |
|
| 55 |
while (static::query() |
| 56 |
->when($ignoreId, function ($q) use ($ignoreId) { |
| 57 |
$q->where('id', '!=', $ignoreId); |
| 58 |
}) |
| 59 |
->where('slug', $slug) |
| 60 |
->exists()) { |
| 61 |
$slug = $base . '-' . $suffix; |
| 62 |
$suffix++; |
| 63 |
} |
| 64 |
|
| 65 |
return $slug; |
| 66 |
} |
| 67 |
|
| 68 |
public function setMetaAttribute($value) |
| 69 |
{ |
| 70 |
if ($value) { |
| 71 |
$decoded = \json_encode($value, true); |
| 72 |
if (!($decoded)) { |
| 73 |
$decoded = '[]'; |
| 74 |
} |
| 75 |
} else { |
| 76 |
$decoded = '[]'; |
| 77 |
} |
| 78 |
|
| 79 |
$this->attributes['meta'] = $decoded; |
| 80 |
} |
| 81 |
|
| 82 |
public function getMetaAttribute($value) |
| 83 |
{ |
| 84 |
if (!$value) { |
| 85 |
return []; |
| 86 |
} |
| 87 |
|
| 88 |
return \json_decode($value, true); |
| 89 |
} |
| 90 |
} |
| 91 |
|