Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Static Roles Bundle Laravel Package

becklyn/static-roles-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require becklyn/static-roles-bundle
    

    Register the bundle in config/bundles.php (Laravel) or AppKernel.php (Symfony):

    Becklyn\StaticRolesBundle\BecklynStaticRolesBundle::class => ['all' => true],
    
  2. Configure Roles Edit config/packages/security.yaml (Laravel) or app/config/security.yml (Symfony):

    becklyn_static_roles:
        roles:
            ROLE_ADMIN:
                title: "Admin"
                included_roles: [ROLE_USER]
            ROLE_USER:
                title: "User"
                description: "Default frontend user"
                tags: [frontend]
    
  3. First Use Case Use the StaticRoleType in a form to assign roles to a user:

    use Becklyn\StaticRolesBundle\Form\Type\StaticRoleType;
    
    $builder->add('roles', StaticRoleType::class, [
        'label' => 'Select Roles',
        'multiple' => true,
        'expanded' => true,
    ]);
    

Implementation Patterns

Role Assignment Workflow

  1. Form Integration Extend your user entity form with StaticRoleType:

    $builder->add('roles', StaticRoleType::class, [
        'multiple' => true,
        'by_reference' => false, // Required for role assignment
    ]);
    
  2. Validation Use the StaticRoleValidator to ensure submitted roles exist:

    use Becklyn\StaticRolesBundle\Validator\Constraints\StaticRole;
    
    /**
     * @Assert\All({
     *     @Assert\Type(type="string"),
     *     @StaticRole()
     * })
     */
    private $roles;
    
  3. Hierarchy Enforcement Automatically include parent roles when saving:

    use Becklyn\StaticRolesBundle\Service\RoleHierarchyService;
    
    $hierarchyService = $this->container->get(RoleHierarchyService::class);
    $user->setRoles($hierarchyService->expandRoles($user->getRoles()));
    

Common Use Cases

  • Role Selection UI: Render a checkbox list of roles with StaticRoleType:
    $builder->add('roles', StaticRoleType::class, [
        'expanded' => true,
        'multiple' => true,
    ]);
    
  • Role Filtering: Filter roles by tags in forms:
    becklyn_static_roles:
        roles:
            ROLE_SUPERVISOR:
                tags: [backend, management]
    
    $builder->add('roles', StaticRoleType::class, [
        'tag_filter' => ['backend'],
    ]);
    
  • Role-Based Access Control (RBAC): Use RoleHierarchyService to check permissions:
    if ($hierarchyService->hasRole($user, 'ROLE_ADMIN')) {
        // Grant access
    }
    

Integration Tips

  • Symfony Security Integration: Replace Symfony’s default role_hierarchy with this bundle’s configuration.
  • Doctrine Lifecycle: Use prePersist/preUpdate to expand roles:
    use Doctrine\ORM\Event\LifecycleEventArgs;
    
    public function prePersist(LifecycleEventArgs $args) {
        $user = $args->getObject();
        $user->setRoles($this->roleHierarchyService->expandRoles($user->getRoles()));
    }
    
  • API Responses: Serialize roles with metadata:
    return [
        'roles' => array_map(function($role) {
            return [
                'name' => $role,
                'title' => $this->roleManager->getRoleTitle($role),
            ];
        }, $user->getRoles()),
    ];
    

Gotchas and Tips

Pitfalls

  1. Role Hierarchy Conflicts

    • Issue: Circular dependencies in included_roles (e.g., ROLE_A includes ROLE_B, which includes ROLE_A).
    • Fix: Validate hierarchy during bundle compilation or use a third-party validator like symfony/validator.
  2. Form Submission Quirks

    • Issue: Roles may not persist if by_reference is true in StaticRoleType.
    • Fix: Always set 'by_reference' => false for role assignment forms.
  3. Caching Headaches

    • Issue: Role configurations are cached aggressively. Changes to security.yml may not reflect immediately.
    • Fix: Clear the cache after updates:
      php bin/console cache:clear
      
  4. Tag Filtering Edge Cases

    • Issue: Case-sensitive tag matching (e.g., ['Backend'] vs ['backend']).
    • Fix: Normalize tags in configuration:
      tags: [backend, management]  # Lowercase for consistency
      

Debugging Tips

  • Validate Configuration Use the becklyn:static-roles:validate command to check for hierarchy issues:
    php bin/console becklyn:static-roles:validate
    
  • Log Role Expansion Enable debug logging for Becklyn\StaticRolesBundle\Service\RoleHierarchyService to trace role expansion:
    monolog:
        handlers:
            main:
                level: debug
                channels: ["!event"]
    
  • Inspect Role Metadata Dump role data for debugging:
    $roleManager = $this->container->get('becklyn_static_roles.role_manager');
    dump($roleManager->getAllRolesWithMetadata());
    

Extension Points

  1. Custom Role Metadata Extend the Role class or use a custom DTO:

    class ExtendedRole {
        public function __construct(
            private string $name,
            private ?string $title = null,
            private array $tags = [],
            private array $customData = []
        ) {}
    }
    

    Override the bundle’s RoleManager to support additional fields.

  2. Dynamic Role Loading Load roles from a database or external API by implementing RoleProviderInterface:

    class DatabaseRoleProvider implements RoleProviderInterface {
        public function getRoles(): array {
            return $this->entityManager->getRepository(Role::class)->findAll();
        }
    }
    

    Register it in services.yaml:

    Becklyn\StaticRolesBundle\:
        resource: '../vendor/becklyn/static-roles-bundle/Resources/config/services.yaml'
        arguments:
            $roleProvider: '@database_role_provider'
    
  3. Custom Role Hierarchy Logic Override the RoleHierarchyService to implement custom hierarchy rules:

    class CustomHierarchyService extends RoleHierarchyService {
        public function expandRoles(array $roles): array {
            // Custom logic here
            return parent::expandRoles($roles);
        }
    }
    

    Bind it in services.yaml:

    Becklyn\StaticRolesBundle\Service\RoleHierarchyService: '@custom_hierarchy_service'
    
  4. Localization Support Add translations for role titles/descriptions:

    # config/packages/translation.yaml
    frameworks:
        translator:
            paths: ['%kernel.project_dir%/translations']
    

    Create translations/messages.en.yaml:

    role:
        ROLE_ADMIN: "Administrator"
        ROLE_USER: "Regular User"
    

    Update the StaticRoleType to use translations:

    $builder->add('roles', StaticRoleType::class, [
        'translation_domain' => 'messages',
    ]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums