| 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 |
'description', |
| 26 |
'meta', |
| 27 |
'slug' |
| 28 |
]; |
| 29 |
|
| 30 |
protected static function booted() |
| 31 |
{ |
| 32 |
static::creating(function ($model) { |
| 33 |
$model->slug = static::generateUniqueSlug($model->title); |
| 34 |
}); |
| 35 |
|
| 36 |
static::updating(function ($model) { |
| 37 |
if ($model->isDirty('title')) { |
| 38 |
$model->slug = static::generateUniqueSlug($model->title, $model->id); |
| 39 |
} |
| 40 |
}); |
| 41 |
} |
| 42 |
|
| 43 |
protected static function generateUniqueSlug($title, $ignoreId = null) |
| 44 |
{ |
| 45 |
$base = Str::slug($title); |
| 46 |
if (!$base) { |
| 47 |
$base = 'tax-class'; |
| 48 |
} |
| 49 |
|
| 50 |
$slug = $base; |
| 51 |
$suffix = 2; |
| 52 |
|
| 53 |
while (static::query() |
| 54 |
->when($ignoreId, function ($q) use ($ignoreId) { |
| 55 |
$q->where('id', '!=', $ignoreId); |
| 56 |
}) |
| 57 |
->where('slug', $slug) |
| 58 |
->exists()) { |
| 59 |
$slug = $base . '-' . $suffix; |
| 60 |
$suffix++; |
| 61 |
} |
| 62 |
|
| 63 |
return $slug; |
| 64 |
} |
| 65 |
|
| 66 |
public function setMetaAttribute($value) |
| 67 |
{ |
| 68 |
if ($value) { |
| 69 |
$decoded = \json_encode($value, true); |
| 70 |
if (!($decoded)) { |
| 71 |
$decoded = '[]'; |
| 72 |
} |
| 73 |
} else { |
| 74 |
$decoded = '[]'; |
| 75 |
} |
| 76 |
|
| 77 |
$this->attributes['meta'] = $decoded; |
| 78 |
} |
| 79 |
|
| 80 |
public function getMetaAttribute($value) |
| 81 |
{ |
| 82 |
if (!$value) { |
| 83 |
return []; |
| 84 |
} |
| 85 |
|
| 86 |
return \json_decode($value, true); |
| 87 |
} |
| 88 |
} |
| 89 |
|