<?php
// src/Security/Voter/CourseVoter.php
namespace App\Security\Voter;
use App\Entity\Course;
use Menke\UserBundle\Entity\User;
use App\Repository\CourseProviderRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class CourseVoter extends Voter
{
public const VIEW = 'COURSE_VIEW';
public const CREATE = 'COURSE_CREATE';
private $courseRepo;
public function __construct(CourseProviderRepository $courseRepo)
{
$this->courseRepo = $courseRepo;
}
protected function supports($attribute, $subject): bool
{
return \in_array($attribute, [self::VIEW, self::CREATE], true) && ($subject instanceof Course || $subject === null);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) return false;
if (\in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return true;
}
$provider = $user->getProvider();
if (!$provider) return false;
switch ($attribute) {
case self::CREATE:
return false; // Provider dürfen keine Kurse anlegen
case self::VIEW:
/** @var Course $course */
$course = $subject;
return $this->courseRepo->existsFor($course->getId(), $provider->getId());
}
return false;
}
}