Symfony et Voters

Par Phaze, il y a 7 ans


Bonjour,

Je souhaite afficher les objets détenus par mon utilisateur, voici comment je procède :

/** * @Route("/infrastructures", name="infrastructure.home") * @param InfrastructureRepository $repo * @return \Symfony\Component\HttpFoundation\Response */ public function infrastructureList(InfrastructureRepository $repo) { $infrastructure = $repo->findBy([ 'owner' => $this->getUser() ]); return $this->render('infrastructure/home.html.twig', [ 'infrastructures' => $infrastructure, ]); }

J'ai lu dans la doc qu'il y avait le système dit Voters dans symfony.

Est-il possible par exemple de partir sur un findAll() et filtrant le résultat avec la gestion des Voters pour n'afficher que les objets détenus par l'utilisateur ?

Merci d'avance pour vos lumières.

2 réponses

Digivia, il y a 7 ans

Bien sur, les Voters sont faits pour cela :)

Regarde la signature de la méthode suivante dans un voter (https://symfony.com/doc/current/security/voters.html#creating-the-custom-voter):
protected function voteOnAttribute($attribute, $infrastructure, TokenInterface $token)

  • $attribute, c'est ton action (par exemple 'EDIT')
  • $infrastructure, c'est l'entité sur laquelle tu souhaite effectuer le test (dans ton cas une instance d'Infrastructure)
    • $token c'est un token, d'où tu peux récupérer le user ($user = $token->getUser();)
      Donc tu peux faire le test :
// If user has created this record, grant access if ($user->getId() === $infrastructure->getUser()->getId()) { return true; } // By default, deny access to that return false;

En partant du principe que dans Infrastructure tu as une propriété $user ManyToOne (ou OneToOne) vers User (User qui implémente UserInterface)

Phaze, il y a 7 ans

Merci beaucoup, je vais tester ça.