PHP code example of fedale / access-control-bundle
1. Go to this page and download the library: Download fedale/access-control-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/ */
use Fedale\AccessControlBundle\Event\AccessDeniedEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Response;
#[AsEventListener]
final class AccessDeniedSubscriber
{
public function __invoke(AccessDeniedEvent $event): void
{
// $event->getRequest() is available for inspection/logging.
$event->setResponse(new Response('Custom forbidden page', Response::HTTP_FORBIDDEN));
}
}
namespace Fedale\AccessControlBundle\Contract;
use Fedale\AccessControlBundle\Dto\AccessRule;
interface RuleProviderInterface
{
/** @return iterable<AccessRule> */
public function getRules(): iterable;
}
use Fedale\AccessControlBundle\Bridge\Doctrine\Entity\AccessControlEntity;
$rule = (new AccessControlEntity())
->setName('admin-area')
->setReason('Admins only')
->setPath('^/admin')
->setRoles(['ROLE_ADMIN'])
->setMethods([]) // any method
->setIps([]) // any IP
->setAllow(true)
->setSort(0)
->setActive(true);
$entityManager->persist($rule);
$entityManager->flush();
// src/Security/StaticRuleProvider.php
namespace App\Security;
use Fedale\AccessControlBundle\Contract\RuleProviderInterface;
use Fedale\AccessControlBundle\Dto\AccessRule;
final class StaticRuleProvider implements RuleProviderInterface
{
public function getRules(): iterable
{
yield new AccessRule(
id: 1,
name: 'admin-area',
reason: 'Admins only',
path: '^/admin',
host: null,
roles: ['ROLE_ADMIN'],
methods: [],
ips: [],
allow: true,
sort: 0,
active: true,
);
yield new AccessRule(
id: 2,
name: 'block-internal',
reason: 'Internal API is private',
path: '^/internal',
host: null,
roles: [],
methods: [],
ips: [],
allow: false,
sort: 10,
active: true,
);
}
}
use Fedale\AccessControlBundle\Cache\CachedRuleProvider;
$pool->deleteItem(CachedRuleProvider::CACHE_KEY);