Skip to content

Commit 53b2c2b

Browse files
committed
bug #4139 cleaned up the code example (gondo)
This PR was submitted for the 2.5 branch but it was merged into the 2.3 branch instead (closes #4139). Discussion ---------- 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 Commits ------- 081b3c7 cleaned up the code example
2 parents b5c9f2a + 1acd1c0 commit 53b2c2b

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
@@ -105,36 +105,38 @@ edit a particular object. Here's an example implementation::
105105
// set the attribute to check against
106106
$attribute = $attributes[0];
107107

108-
// get current logged in user
109-
$user = $token->getUser();
110-
111108
// check if the given attribute is covered by this voter
112109
if (!$this->supportsAttribute($attribute)) {
113110
return VoterInterface::ACCESS_ABSTAIN;
114111
}
115112

113+
// get current logged in user
114+
$user = $token->getUser();
115+
116116
// make sure there is a user object (i.e. that the user is logged in)
117117
if (!$user instanceof UserInterface) {
118118
return VoterInterface::ACCESS_DENIED;
119119
}
120120

121121
switch($attribute) {
122-
case 'view':
122+
case self::VIEW:
123123
// the data object could have for example a method isPrivate()
124124
// which checks the Boolean attribute $private
125125
if (!$post->isPrivate()) {
126126
return VoterInterface::ACCESS_GRANTED;
127127
}
128128
break;
129129

130-
case 'edit':
130+
case self::EDIT:
131131
// we assume that our data object has a method getOwner() to
132132
// get the current owner user entity for this data object
133133
if ($user->getId() === $post->getOwner()->getId()) {
134134
return VoterInterface::ACCESS_GRANTED;
135135
}
136136
break;
137137
}
138+
139+
return VoterInterface::ACCESS_DENIED;
138140
}
139141
}
140142

0 commit comments

Comments
 (0)