PHP code example of fedale / access-control-voter-bundle

1. Go to this page and download the library: Download fedale/access-control-voter-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fedale / access-control-voter-bundle example snippets


// config/bundles.php
return [
    // ...
    Fedale\RbacBundle\FedaleRbacBundle::class => ['all' => true],
];

use Fedale\RbacBundle\Security\AssignedRolesAwareInterface;

class User implements UserInterface, AssignedRolesAwareInterface
{
    /** @var string[] */
    private array $assignedRoles = [];

    public function setAssignedRoles(array $roles): void
    {
        $this->assignedRoles = $roles;
    }

    public function getRoles(): array
    {
        return array_values(array_unique($this->assignedRoles));
    }
}

use Fedale\RbacBundle\Contract\RuleInterface;
use Fedale\RbacBundle\Dto\AuthItem;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

// Auto-tagged 'fedale_rbac.rule' via autoconfigure.
final class AuthorRule implements RuleInterface
{
    public function execute(TokenInterface $token, AuthItem $item, mixed $params = null): bool
    {
        return $params instanceof Post && $params->getAuthor() === $token->getUser();
    }
}

// Controller
use Fedale\RbacBundle\Security\CanTrait;

class InvoiceController extends AbstractController
{
    use CanTrait;

    public function edit(Invoice $invoice): Response
    {
        if (!$this->can('EDIT_INVOICE', $invoice)) {
            throw $this->createAccessDeniedException();
        }
        // ...
    }
}

// Or via the native flow (DynamicVoter answers on permission attributes)
#[IsGranted('EDIT_INVOICE', subject: 'invoice')]
public function edit(Invoice $invoice): Response { /* ... */ }

public function addItem(string $name, AuthItemType $type, ?string $description = null, ?string $ruleName = null): void;
public function removeItem(string $name): void;
public function addChild(string $parent, string $child): void;
public function removeChild(string $parent, string $child): void;
public function assign(string $userId, string $item): void;
public function revoke(string $userId, string $item): void;
public function addRule(string $name, ?string $serviceId = null, ?string $expression = null): void;
public function removeRule(string $name): void;

subject.getAuthor() == user
user === subject["author"] and subject["post"].isPublished()
bash
php bin/console rbac:list-items
php bin/console rbac:list-assignments <user>
php bin/console rbac:check <user> <item>   # static reachability (rules NOT evaluated)