<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Validator\Constraints;

use Sso\WebserviceBundle\Exception\InvalidConfigurationException;
use Sso\WebserviceBundle\PasswordCrypt\PasswordCryptRepositoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class PasswordEncryptTypeValidator
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\WebserviceBundle\Validator\Constraints
 */
class PasswordEncryptTypeValidator extends ConstraintValidator
{
    /**
     * @var PasswordCryptRepositoryInterface
     */
    private $passwordCryptRepository;

    /**
     * PasswordEncryptTypeValidator constructor.
     * @param PasswordCryptRepositoryInterface $passwordCryptRepository
     */
    public function __construct(PasswordCryptRepositoryInterface $passwordCryptRepository)
    {
        $this->passwordCryptRepository = $passwordCryptRepository;
    }

    /**
     * Checks if the passed value is valid.
     *
     * @param mixed $value The value that should be validated
     * @param Constraint $constraint The constraint for the validation
     */
    public function validate($value, Constraint $constraint)
    {
        if (null === $value) {
            return;
        }

        // Check if password encrypt type is available
        try {
            $this->passwordCryptRepository->getByEncryptType($value);
        } catch (InvalidConfigurationException $exception) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ encrypt_type }}', $value)
                ->addViolation();
        }
    }
}
