<?php

namespace App\Security\Voter;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;

final class VocabVoter extends Voter
{
    public const EDIT = 'VOCAB_EDIT';
    public const DELETE = 'VOCAB_DELETE';
    public const VIEW = 'VOCAB_VIEW';

    protected function supports(string $attribute, mixed $subject): bool
    {
        // replace with your own logic
        // https://symfony.com/doc/current/security/voters.html
        return in_array($attribute, [self::EDIT, self::VIEW, self::DELETE])
            && $subject instanceof \App\VocabInterface;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();

        // if the user is anonymous, do not grant access
        if (!$user instanceof UserInterface) {
            return false;
        }

        $roles = $user->getRoles();

        // TODO: Better way to check roles?
        switch ($attribute) {
            case self::EDIT:
            case self::DELETE:
                return  in_array('ROLE_ADMIN', $roles)
                        || in_array('ROLE_REVISOR', $roles);
                break;

            case self::VIEW:
                return  ! in_array('ROLE_READER', $roles);
                break;
        }

        return false;
    }
}
