PermissionSeeder.php 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace Database\Seeders;
  3. use App\Models\Permission;
  4. use Illuminate\Database\Seeder;
  5. use App\Services\PermissionService;
  6. class PermissionSeeder extends Seeder
  7. {
  8. public function __construct(
  9. protected PermissionService $permissionService,
  10. ) {}
  11. public function run(): void
  12. {
  13. $permissions = [
  14. [
  15. "scope" => "dashboard",
  16. "description" => "Dashboard",
  17. "bits" => Permission::ALL_PERMS,
  18. "children" => [],
  19. ],
  20. [
  21. "scope" => "franchisee",
  22. "description" => "Franchisee",
  23. "bits" => Permission::ALL_PERMS,
  24. "children" => [],
  25. ],
  26. [
  27. "scope" => "config",
  28. "description" => "Configurações",
  29. "bits" => Permission::MENU | Permission::VIEW,
  30. "children" => [
  31. [
  32. "scope" => "config.user",
  33. "description" => "Configurações de Usuários",
  34. "bits" => Permission::CRUD,
  35. "children" => [],
  36. ],
  37. [
  38. "scope" => "config.permission",
  39. "description" => "Configurações de Permissões",
  40. "bits" => Permission::CRUD,
  41. "children" => [],
  42. ],
  43. [
  44. "scope" => "config.city",
  45. "description" => "Configurações de Cidades",
  46. "bits" => Permission::CRUD,
  47. "children" => [],
  48. ],
  49. [
  50. "scope" => "config.country",
  51. "description" => "Configurações de Países",
  52. "bits" => Permission::CRUD,
  53. "children" => [],
  54. ],
  55. [
  56. "scope" => "config.state",
  57. "description" => "Configurações de Estados",
  58. "bits" => Permission::CRUD,
  59. "children" => [],
  60. ],
  61. ],
  62. ],
  63. ];
  64. $this->createPermissionsAndChildren(permissions: $permissions);
  65. }
  66. /**
  67. * Recursively creates or updates permissions and handles nesting.
  68. *
  69. * @param array $permissions The array of permission data.
  70. * @param Permission|null $parent The parent Permission object (for nested sets).
  71. */
  72. private function createPermissionsAndChildren(
  73. array $permissions,
  74. ?Permission $parent = null,
  75. ): void {
  76. foreach ($permissions as $permissionData) {
  77. $children = $permissionData["children"];
  78. unset($permissionData["children"]);
  79. $permissionNode = Permission::updateOrCreate(
  80. ["scope" => $permissionData["scope"]],
  81. $permissionData,
  82. );
  83. if ($parent) {
  84. $parent->appendNode($permissionNode);
  85. }
  86. if (!empty($children)) {
  87. $this->createPermissionsAndChildren(
  88. permissions: $children,
  89. parent: $permissionNode,
  90. );
  91. }
  92. }
  93. }
  94. }