<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Security\Authorization;

use Chill\MainBundle\Entity\Workflow\EntityWorkflowStepSignature;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

final class EntityWorkflowStepSignatureVoter extends Voter
{
    public const SIGN = 'CHILL_MAIN_ENTITY_WORKFLOW_SIGNATURE_SIGN';

    public const CANCEL = 'CHILL_MAIN_ENTITY_WORKFLOW_SIGNATURE_CANCEL';

    public const REJECT = 'CHILL_MAIN_ENTITY_WORKFLOW_SIGNATURE_REJECT';

    protected function supports(string $attribute, $subject)
    {
        return $subject instanceof EntityWorkflowStepSignature
            && in_array($attribute, [self::SIGN, self::CANCEL, self::REJECT], true);
    }

    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
    {
        /** @var EntityWorkflowStepSignature $subject */
        if ($subject->getSigner() instanceof Person) {
            return true;
        }

        if ($subject->getSigner() === $token->getUser()) {
            return true;
        }

        return false;
    }
}
