Skip to content

Commit 8468423

Browse files
Simplified the voter code a bit
1 parent c14e9db commit 8468423

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

src/AppBundle/Security/PostVoter.php

+10-14
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,17 @@
1717
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
1818

1919
/**
20-
* Decide whether the current user can show, edit or delete a Post object.
20+
* It grants or denies permissions for actions related to blog posts (such as
21+
* showing, editing and deleting posts).
2122
*
2223
* See http://symfony.com/doc/current/security/voters.html
2324
*
2425
* @author Yonel Ceruto <[email protected]>
2526
*/
2627
class PostVoter extends Voter
2728
{
29+
// Defining these constants is overkill for this simple application, but for real
30+
// applications, it's a recommended practice to avoid relying on "magic strings"
2831
const SHOW = 'show';
2932
const EDIT = 'edit';
3033
const DELETE = 'delete';
@@ -34,17 +37,8 @@ class PostVoter extends Voter
3437
*/
3538
protected function supports($attribute, $subject)
3639
{
37-
// if the attribute isn't one we support, return false
38-
if (!in_array($attribute, [self::SHOW, self::EDIT, self::DELETE])) {
39-
return false;
40-
}
41-
42-
// only vote on Post objects inside this voter
43-
if (!$subject instanceof Post) {
44-
return false;
45-
}
46-
47-
return true;
40+
// this voter is only executed for three specific permissions on Post objects
41+
return $subject instanceof Post && in_array($attribute, [self::SHOW, self::EDIT, self::DELETE]);
4842
}
4943

5044
/**
@@ -54,12 +48,14 @@ protected function voteOnAttribute($attribute, $post, TokenInterface $token)
5448
{
5549
$user = $token->getUser();
5650

51+
// the user must be logged in; if not, deny permission
5752
if (!$user instanceof User) {
58-
// the user must be logged in; if not, deny access
5953
return false;
6054
}
6155

62-
// you know $post is a Post object, thanks to supports
56+
// the logic of this voter is pretty simple: if the given user is the
57+
// author of the blog post, grant permission; otherwise, deny it.
58+
// (the supports() method guarantees that $post is a Post object)
6359
return $user === $post->getAuthor();
6460
}
6561
}

0 commit comments

Comments
 (0)