<?php
// src/Security/PostVoter.php
namespace App\Security;
use App\Entity\Contact;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ContactVoter extends Voter
{
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT = 'edit';
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT])) {
return false;
}
// only vote on `Post` objects
if (!$subject instanceof Contact) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a Post object, thanks to `supports()`
/** @var Post $post */
$contact = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($contact, $user);
case self::EDIT:
return $this->canEdit($contact, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Contact $contact, User $user): bool
{
// if they can edit, they can view
if ($this->canEdit($contact, $user)) {
return true;
}
return ($contact == $user->getContact() || $contact->getParent() == $user->getContact());
}
private function canEdit(Contact $contact, User $user): bool
{
// this assumes that the Post object has a `getOwner()` method
return ($contact == $user->getContact() || $contact->getParent() == $user->getContact());
}
}