Skip to content

Commit

Permalink
Merge branch 'master' into weather
Browse files Browse the repository at this point in the history
* master:
  Some fixes for nullable user parameters.
  Allow anonymous users.
  Allow null values for $user parameter.
  • Loading branch information
maltehuebner committed Apr 14, 2018
2 parents 5a4eba4 + bfcfa83 commit e7f09ca
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
30 changes: 25 additions & 5 deletions src/AppBundle/Security/Authorization/Voter/AbstractVoter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ protected function voteOnAttribute($attribute, $subject, TokenInterface $token):
{
$user = $token->getUser();

if (!$user instanceof User) {
return false;
}

$canMethodName = $this->getCanMethodName($attribute);

return $this->$canMethodName($subject, $user);
if ($this->isUserMandatory($canMethodName) && !$user instanceof User) {
return false;
} elseif (!$this->isUserMandatory($canMethodName) && !$user instanceof User) {
return $this->$canMethodName($subject, null, $user);
} else {
return $this->$canMethodName($subject, $user);
}
}

protected function supports($attribute, $subject): bool
Expand Down Expand Up @@ -70,4 +72,22 @@ protected function getCanMethodName(string $attribute): string
{
return sprintf('can%s', ucfirst(strtolower($attribute)));
}

protected function isUserMandatory(string $methodName): bool
{
$reflection = new \ReflectionMethod($this, $methodName);
$parameters = $reflection->getParameters();

if (count($parameters) <= 2) {
return true;
}

$userParameter = $parameters[1];

if ($userParameter->getClass()->getName() === User::class) {
return !$userParameter->allowsNull();
}

throw new \InvalidArgumentException('There must be a User accepting parameter');
}
}
2 changes: 1 addition & 1 deletion src/AppBundle/Security/Authorization/Voter/PhotoVoter.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

class PhotoVoter extends AbstractVoter
{
protected function canView(Photo $photo, User $user): bool
protected function canView(Photo $photo, User $user = null, string $username = null): bool
{
return true;
}
Expand Down

0 comments on commit e7f09ca

Please sign in to comment.