17
17
use Symfony \Component \Security \Core \Authorization \Voter \Voter ;
18
18
19
19
/**
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).
21
22
*
22
23
* See http://symfony.com/doc/current/security/voters.html
23
24
*
24
25
* @author Yonel Ceruto <[email protected] >
25
26
*/
26
27
class PostVoter extends Voter
27
28
{
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"
28
31
const SHOW = 'show ' ;
29
32
const EDIT = 'edit ' ;
30
33
const DELETE = 'delete ' ;
@@ -34,17 +37,8 @@ class PostVoter extends Voter
34
37
*/
35
38
protected function supports ($ attribute , $ subject )
36
39
{
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 ]);
48
42
}
49
43
50
44
/**
@@ -54,12 +48,14 @@ protected function voteOnAttribute($attribute, $post, TokenInterface $token)
54
48
{
55
49
$ user = $ token ->getUser ();
56
50
51
+ // the user must be logged in; if not, deny permission
57
52
if (!$ user instanceof User) {
58
- // the user must be logged in; if not, deny access
59
53
return false ;
60
54
}
61
55
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)
63
59
return $ user === $ post ->getAuthor ();
64
60
}
65
61
}
0 commit comments