Skip to content

Commit 081b3c7

Browse files
committed
cleaned up the code example
- added final return for `vote()` function - moved `$user` below attribute check. if attribute fails, we don't need user - used already declared constants in switch statement, rather than harcoded strings
1 parent bb39863 commit 081b3c7

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

cookbook/security/voters_data_permission.rst

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,36 +108,38 @@ edit a particular object. Here's an example implementation:
108108
// set the attribute to check against
109109
$attribute = $attributes[0];
110110
111-
// get current logged in user
112-
$user = $token->getUser();
113-
114111
// check if the given attribute is covered by this voter
115112
if (!$this->supportsAttribute($attribute)) {
116113
return VoterInterface::ACCESS_ABSTAIN;
117114
}
118115
116+
// get current logged in user
117+
$user = $token->getUser();
118+
119119
// make sure there is a user object (i.e. that the user is logged in)
120120
if (!$user instanceof UserInterface) {
121121
return VoterInterface::ACCESS_DENIED;
122122
}
123123
124124
switch($attribute) {
125-
case 'view':
125+
case self::VIEW:
126126
// the data object could have for example a method isPrivate()
127127
// which checks the Boolean attribute $private
128128
if (!$post->isPrivate()) {
129129
return VoterInterface::ACCESS_GRANTED;
130130
}
131131
break;
132132
133-
case 'edit':
133+
case self::EDIT:
134134
// we assume that our data object has a method getOwner() to
135135
// get the current owner user entity for this data object
136136
if ($user->getId() === $post->getOwner()->getId()) {
137137
return VoterInterface::ACCESS_GRANTED;
138138
}
139139
break;
140140
}
141+
142+
return VoterInterface::ACCESS_DENIED;
141143
}
142144
}
143145

0 commit comments

Comments
 (0)