@@ -94,17 +94,23 @@ edit a particular object. Here's an example implementation:
94
94
return false;
95
95
}
96
96
97
- // the data object could have for example a method isPrivate()
98
- // which checks the Boolean attribute $private
99
- if ($attribute == self::VIEW && !$post->isPrivate()) {
100
- return true;
101
- }
102
-
103
- // we assume that our data object has a method getOwner() to
104
- // get the current owner user entity for this data object
105
- if ($attribute == self::EDIT && $user->getId() === $post->getOwner()->getId()) {
106
- return true;
107
- }
97
+ switch($attribute) {
98
+ case self::VIEW:
99
+ // the data object could have for example a method isPrivate()
100
+ // which checks the Boolean attribute $private
101
+ if (!$post->isPrivate()) {
102
+ return true;
103
+ }
104
+
105
+ break;
106
+ case self::EDIT:
107
+ // we assume that our data object has a method getOwner() to
108
+ // get the current owner user entity for this data object
109
+ if ($user->getId() === $post->getOwner()->getId()) {
110
+ return true;
111
+ }
112
+
113
+ break;
108
114
109
115
return false;
110
116
}
@@ -195,7 +201,6 @@ from the authorization checker is called.
195
201
196
202
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
197
203
use Symfony\Component\HttpFoundation\Response;
198
- use Symfony\Component\Security\Core\Exception\AccessDeniedException;
199
204
200
205
class PostController extends Controller
201
206
{
@@ -204,9 +209,10 @@ from the authorization checker is called.
204
209
// get a Post instance
205
210
$post = ...;
206
211
207
- // keep in mind, this will call all registered security voters
208
- if (false === $this->get('security.authorization_checker')->isGranted('view', $post)) {
209
- throw new AccessDeniedException('Unauthorised access!');
212
+ $authChecker = $this->get('security.authorization_checker');
213
+
214
+ if (false === $authChecker->isGranted('view', $post)) {
215
+ throw $this->createAccessDeniedException('Unauthorized access!');
210
216
}
211
217
212
218
return new Response('<h1 >'.$post->getName().'</h1 >');
0 commit comments