<?php

namespace App\Security\Voter;

use App\Entity\Snip;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;

class SnipVoter extends Voter
{
    public const string EDIT = 'edit';
    public const string VIEW = '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])
            && $subject instanceof Snip;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token,/* , ?Vote $vote = null */): bool
    {
        /** @var Snip $subject */

        $user = $token->getUser();

        switch ($attribute) {
            case self::VIEW:
                if ($subject->public) {
                    return true;
                }
            case self::EDIT:
                if (!$user instanceof UserInterface) {
                    return false;
                }
                if ($subject->createdBy === $user) {
                    return true;
                }
                break;
        }

        return false;
    }
}
