Skip to content
This repository has been archived by the owner on Feb 24, 2023. It is now read-only.

[@IsGranted] Updated exception handling when the $subject is an array of values #630

Closed
wants to merge 7 commits into from
11 changes: 10 additions & 1 deletion EventListener/IsGrantedListener.php
Expand Up @@ -97,14 +97,23 @@ private function getIsGrantedString(IsGranted $isGranted)
$attributes = array_map(function ($attribute) {
return sprintf('"%s"', $attribute);
}, (array) $isGranted->getAttributes());

if (1 === \count($attributes)) {
$argsString = reset($attributes);
} else {
$argsString = sprintf('[%s]', implode(', ', $attributes));
}

if (null !== $isGranted->getSubject()) {
$argsString = sprintf('%s, %s', $argsString, $isGranted->getSubject());
$subjects = array_map(function ($subject) {
return sprintf('%s', $subject);
}, (array) $isGranted->getSubject());

if (1 === \count($subjects)) {
$argsString = sprintf('%s, %s', $argsString, reset($subjects));
} else {
$argsString = sprintf('%s, [%s]', $argsString, implode(', ', $subjects));
}
}

return $argsString;
Expand Down
6 changes: 5 additions & 1 deletion Tests/EventListener/IsGrantedListenerTest.php
Expand Up @@ -125,7 +125,9 @@ public function testAccessDeniedMessages(array $attributes, $subject, $expectedM
// avoid the error of the subject not being found in the request attributes
$arguments = [];
if (null !== $subject) {
$arguments[$subject] = 'bar';
foreach ((array) $subject as $value) {
$arguments[$value] = 'bar';
}
}

$listener = new IsGrantedListener($this->createArgumentNameConverter($arguments), $authChecker);
Expand All @@ -146,6 +148,8 @@ public function getAccessDeniedMessageTests()
yield [['ROLE_ADMIN'], null, 'Access Denied by controller annotation @IsGranted("ROLE_ADMIN")'];
yield [['ROLE_ADMIN', 'ROLE_USER'], null, 'Access Denied by controller annotation @IsGranted(["ROLE_ADMIN", "ROLE_USER"])'];
yield [['ROLE_ADMIN', 'ROLE_USER'], 'product', 'Access Denied by controller annotation @IsGranted(["ROLE_ADMIN", "ROLE_USER"], product)'];
yield [['ROLE_ADMIN', 'ROLE_USER'], ['product'], 'Access Denied by controller annotation @IsGranted(["ROLE_ADMIN", "ROLE_USER"], product)'];
yield [['ROLE_ADMIN', 'ROLE_USER'], ['product', 'feature'], 'Access Denied by controller annotation @IsGranted(["ROLE_ADMIN", "ROLE_USER"], [product, feature])'];
}

/**
Expand Down