<?php
namespace App\Security\Voter;
use App\Entity\Media\Media;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class MediaVoter extends Voter
{
// these strings are just invented: you can use anything
const SHOW = 'show';
const EDIT = 'edit';
const DELETE = 'delete';
const CHAT = 'chat';
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::SHOW, self::EDIT, self::DELETE, self::CHAT])) {
return false;
}
// only vote on `Post` objects
if (!$subject instanceof Media) {
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 Media $media */
$media = $subject;
switch ($attribute) {
case self::SHOW:
return $this->canView($media, $user);
case self::EDIT:
return $this->canEdit($media, $user);
case self::DELETE:
return $this->canDelete($media, $user);
case self::CHAT:
return $this->canChat($media, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Media $media, User $user): bool
{
// if they can edit, they can view
/*if ($this->canEdit($media, $user)) {
return true;
}*/
// the Post object could have, for example, a method `isPrivate()`
return $media->getCreatedBy() === $user;
}
private function canEdit(Media $media, User $user): bool
{
return $media->getCreatedBy() === $user;
// this assumes that the Post object has a `getOwner()` method
//return $user === $post->getOwner();
}
private function canDelete(Media $media, User $user): bool
{
return $media->getCreatedBy() === $user;
}
private function canChat(Media $media, User $user): bool
{
return $media->getCreatedBy() === $user;
}
}