<?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  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Validator\Constraints;

use Sso\WebserviceBundle\Generator\ApplicationAttribute\GeneratorInterface;
use Sso\WebserviceBundle\Services\UserApplicationAttribute\Add\Request\AttributeTypeInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 * Class ApplicationAttributeValueValidator
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\WebserviceBundle\Validator\Constraints
 */
class ApplicationAttributeValueValidator extends ConstraintValidator
{
    /**
     * @var GeneratorInterface[]
     */
    private $generators = [];

    /**
     * @param GeneratorInterface $generator
     */
    public function addGenerator(GeneratorInterface $generator): void
    {
        $this->generators[] = $generator;
    }

    /**
     * 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;
        }

        if (!$value instanceof AttributeTypeInterface) {
            throw new UnexpectedTypeException($value, AttributeTypeInterface::class);
        }

        if ($value->getType() !== 'generator') {
            return;
        }

        if (!$this->isValidGenerator($value->getValue())) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ string }}', $value->getValue())
                ->addViolation();
        }
    }

    /**
     * @param string $generatorName
     * @return bool
     */
    private function isValidGenerator(string $generatorName): bool
    {
        foreach ($this->generators as $generator) {
            if ($generator->getName() === $generatorName) {
                return true;
            }
        }

        return false;
    }
}
