PermissionSeeder.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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" => "config",
  22. "description" => "Configurações",
  23. "bits" => Permission::MENU | Permission::VIEW,
  24. "children" => [
  25. [
  26. "scope" => "config.user",
  27. "description" => "Configurações de Usuários",
  28. "bits" => Permission::CRUD,
  29. "children" => [],
  30. ],
  31. [
  32. "scope" => "config.permission",
  33. "description" => "Configurações de Permissões",
  34. "bits" => Permission::CRUD,
  35. "children" => [],
  36. ],
  37. [
  38. "scope" => "config.city",
  39. "description" => "Configurações de Cidades",
  40. "bits" => Permission::CRUD,
  41. "children" => [],
  42. ],
  43. [
  44. "scope" => "config.country",
  45. "description" => "Configurações de Países",
  46. "bits" => Permission::CRUD,
  47. "children" => [],
  48. ],
  49. [
  50. "scope" => "config.state",
  51. "description" => "Configurações de Estados",
  52. "bits" => Permission::CRUD,
  53. "children" => [],
  54. ],
  55. ],
  56. ],
  57. ];
  58. $this->createPermissionsAndChildren(permissions: $permissions);
  59. }
  60. /**
  61. * Recursively creates or updates permissions and handles nesting.
  62. *
  63. * @param array $permissions The array of permission data.
  64. * @param Permission|null $parent The parent Permission object (for nested sets).
  65. */
  66. private function createPermissionsAndChildren(
  67. array $permissions,
  68. ?Permission $parent = null,
  69. ): void {
  70. foreach ($permissions as $permissionData) {
  71. $children = $permissionData["children"];
  72. unset($permissionData["children"]);
  73. $permissionNode = Permission::updateOrCreate(
  74. ["scope" => $permissionData["scope"]],
  75. $permissionData,
  76. );
  77. if ($parent) {
  78. $parent->appendNode($permissionNode);
  79. }
  80. if (!empty($children)) {
  81. $this->createPermissionsAndChildren(
  82. permissions: $children,
  83. parent: $permissionNode,
  84. );
  85. }
  86. }
  87. }
  88. }