Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
66.67% |
10 / 15 |
|
33.33% |
2 / 6 |
CRAP | |
0.00% |
0 / 1 |
| MenuItem | |
66.67% |
10 / 15 |
|
33.33% |
2 / 6 |
21.26 | |
0.00% |
0 / 1 |
| menu | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| parent | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| children | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| url | |
66.67% |
4 / 6 |
|
0.00% |
0 / 1 |
8.81 | |||
| categoryUrl | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
| booted | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Models; |
| 4 | |
| 5 | use App\Service\CacheService; |
| 6 | use Illuminate\Database\Eloquent\Factories\HasFactory; |
| 7 | use Illuminate\Database\Eloquent\Model; |
| 8 | use Illuminate\Database\Eloquent\Relations\BelongsTo; |
| 9 | use Illuminate\Database\Eloquent\Relations\HasMany; |
| 10 | use Illuminate\Support\Facades\Route; |
| 11 | |
| 12 | class MenuItem extends Model |
| 13 | { |
| 14 | use HasFactory; |
| 15 | |
| 16 | protected $fillable = ['menu_id', 'parent_id', 'label', 'type', 'value', 'icon', 'new_tab', 'sort_order']; |
| 17 | |
| 18 | protected $casts = [ |
| 19 | 'new_tab' => 'boolean', |
| 20 | 'sort_order' => 'integer', |
| 21 | ]; |
| 22 | |
| 23 | public function menu(): BelongsTo |
| 24 | { |
| 25 | return $this->belongsTo(Menu::class); |
| 26 | } |
| 27 | |
| 28 | public function parent(): BelongsTo |
| 29 | { |
| 30 | return $this->belongsTo(self::class, 'parent_id'); |
| 31 | } |
| 32 | |
| 33 | public function children(): HasMany |
| 34 | { |
| 35 | return $this->hasMany(self::class, 'parent_id')->orderBy('sort_order'); |
| 36 | } |
| 37 | |
| 38 | /** Resolve this item to a live URL for the storefront. */ |
| 39 | public function url(): string |
| 40 | { |
| 41 | return match ($this->type) { |
| 42 | 'route' => Route::has($this->value) ? route($this->value) : '#', |
| 43 | 'category' => $this->categoryUrl(), |
| 44 | 'page' => url('/' . ltrim((string) $this->value, '/')), |
| 45 | default => $this->value ?: '#', |
| 46 | }; |
| 47 | } |
| 48 | |
| 49 | private function categoryUrl(): string |
| 50 | { |
| 51 | $category = Category::find($this->value); |
| 52 | |
| 53 | return $category && Route::has('category.product') |
| 54 | ? route('category.product', [$category->name, $category->id]) |
| 55 | : '#'; |
| 56 | } |
| 57 | |
| 58 | protected static function booted(): void |
| 59 | { |
| 60 | static::saved(fn () => CacheService::forgetMenusBuilder()); |
| 61 | static::deleted(fn () => CacheService::forgetMenusBuilder()); |
| 62 | } |
| 63 | } |