<?php
namespace App\Security;
use App\Entity\User;
use App\Entity\Vacancy;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class VacancyVoter extends Voter
{
// these strings are just invented: you can use anything
public const VIEW = 'view';
public const EDIT = 'edit';
/**
* @param string $attribute
* @param mixed $subject
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!\in_array($attribute, [self::VIEW, self::EDIT], true)) {
return false;
}
// only vote on Vacancy objects inside this voter
if (!$subject instanceof Vacancy) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $subject
*/
protected function voteOnAttribute($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 Vacancy object, thanks to supports
/** @var Vacancy $vacancy */
$vacancy = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($vacancy, $user);
case self::EDIT:
return $this->canEdit($vacancy, $user);
}
throw new LogicException('This code should not be reached!');
}
private function canView(Vacancy $vacancy, User $user): bool
{
// if they can edit, they can view
if ($this->canEdit($vacancy, $user)) {
return true;
}
if ($user->hasRole('ROLE_ADMIN_USER') || $user->isSuperAdmin()) {
return true;
}
if ($user->hasRole('ROLE_ADMIN_JOB_OWNER')) {
if ($vacancy->getManagers()->count() && $user->getCompanies()->isEmpty()) {
return $vacancy->getManagers()->contains($user);
}
if ($user->getCompanies()->contains($vacancy->getCompany())) {
return true;
}
}
return false;
}
/**
* @return bool
*/
private function canEdit(Vacancy $vacancy, User $user)
{
return false;
}
}