roles.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. use App\Models\Role;
  3. if(!function_exists('getRoles')){
  4. function getRoles($key = null): array|string
  5. {
  6. $roles = Role::NAMES;
  7. if($key && isset($roles[$key])){
  8. return $roles[$key];
  9. } else {
  10. return $roles;
  11. }
  12. }
  13. }
  14. if(!function_exists('hasRole')){
  15. function hasRole($roles, $user = null) : bool
  16. {
  17. if(!$user) $user = auth()->user();
  18. if(!$user) return false;
  19. return $user->hasRole($roles);
  20. }
  21. }
  22. if(!function_exists('roleName')) {
  23. function roleName($role): string
  24. {
  25. return Role::NAMES[$role] ?? (string) $role;
  26. }
  27. }
  28. if(!function_exists('hasPermission')) {
  29. function hasPermission(string $permission, $user = null): bool
  30. {
  31. if(!$user) $user = auth()->user();
  32. if(!$user) return false;
  33. return $user->hasPermission($permission);
  34. }
  35. }
  36. if(!function_exists('hasAnyPermission')) {
  37. function hasAnyPermission(array|string $permissions, $user = null): bool
  38. {
  39. if(!$user) $user = auth()->user();
  40. if(!$user) return false;
  41. return $user->hasAnyPermission($permissions);
  42. }
  43. }
  44. if(!function_exists('canViewField')) {
  45. function canViewField(string $module, string $field, ?string $entity = null, $user = null): bool
  46. {
  47. if(!$user) $user = auth()->user();
  48. if(!$user) return false;
  49. return $user->canViewField($module, $field, $entity);
  50. }
  51. }
  52. if(!function_exists('canUpdateField')) {
  53. function canUpdateField(string $module, string $field, ?string $entity = null, $user = null): bool
  54. {
  55. if(!$user) $user = auth()->user();
  56. if(!$user) return false;
  57. return $user->canUpdateField($module, $field, $entity);
  58. }
  59. }
  60. // return current year
  61. if(!function_exists('year')) {
  62. function year(): int
  63. {
  64. return (int)session('year', date('Y'));
  65. }
  66. }
  67. if(!function_exists('glob_safe')) {
  68. function glob_safe(string $str): string
  69. {
  70. return str_replace(['[', ']', '*', '?'], ['[[]', '[]]', '[*]', '[?]'], $str);
  71. }
  72. }
  73. if(!function_exists('fileName')) {
  74. function fileName($file): string
  75. {
  76. return preg_replace('/[\\*\\:\\\\\\/\\?<>]/', '_', $file);
  77. }
  78. }