<?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\Validator\Constraints\Entity;

use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UserCircleConsistencyValidator extends ConstraintValidator
{
    /**
     * @var AuthorizationHelper
     */
    protected $autorizationHelper;

    public function __construct(AuthorizationHelper $autorizationHelper)
    {
        $this->autorizationHelper = $autorizationHelper;
    }

    /**
     * @param object                $value
     * @param UserCircleConsistency $constraint
     */
    public function validate($value, Constraint $constraint)
    {
        /** @var \Chill\MainBundle\Entity\User $user */
        $user = \call_user_func([$value, $constraint->getUserFunction]);

        if (null === $user) {
            return;
        }

        if (false === $this->autorizationHelper->userHasAccess($user, $value, $constraint->role)) {
            $this->context
                ->buildViolation($constraint->message)
                ->setParameter('{{ username }}', $user->getUsername())
                ->atPath($constraint->path)
                ->addViolation();
        }
    }
}
