Menu.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Models;
  3. use App\Constants\Util;
  4. class Menu extends BaseModel
  5. {
  6. protected $table = 'menus';
  7. protected $fillable = ['parent_id', 'title', 'icon' ,'uri' ,'permission_name' ,'sort' ,'status' ,'type' ];
  8. const TYPE_MENU = 1;
  9. const TYPE_BUTTON = 2;
  10. const STATUS_SHOW = 1;
  11. const STATUS_HIDE = 2;
  12. public static function isImageIcon(string $value): bool
  13. {
  14. $value = trim($value);
  15. if ($value === '') return true;
  16. if (preg_match('#^https?://#i', $value)) {
  17. return filter_var($value, FILTER_VALIDATE_URL) !== false;
  18. }
  19. return preg_match('#^/(?!/)\S+$#u', $value) === 1;
  20. }
  21. protected function getIconAttribute($value): string
  22. {
  23. $value = trim((string) $value);
  24. return self::isImageIcon($value) ? (string) Util::ensureUrl($value) : '';
  25. }
  26. protected function setIconAttribute($value): void
  27. {
  28. $value = trim((string) $value);
  29. $baseUrl = rtrim((string) config('app.url', ''), '/');
  30. if ($baseUrl !== '' && str_starts_with($value, $baseUrl . '/')) {
  31. $value = substr($value, strlen($baseUrl));
  32. }
  33. $this->attributes['icon'] = $value;
  34. }
  35. public function children()
  36. {
  37. return $this->hasMany(Menu::class, 'parent_id');
  38. }
  39. public function parent()
  40. {
  41. return $this->belongsTo(Menu::class, 'parent_id');
  42. }
  43. }