<?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\Services\UserApplicationAttribute\Add\Request\AttributeTypeInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 * Class UserApplicationAttributesValidator
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\WebserviceBundle\Validator\Constraints
 */
class UserApplicationAttributesValidator extends ConstraintValidator
{
    /**
     * 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 (!is_iterable($value)) {
            throw new UnexpectedTypeException($value, 'array');
        }

        $validatedNames = [];
        foreach ($value as $item) {
            if (!$item instanceof AttributeTypeInterface) {
                throw new UnexpectedTypeException($item, AttributeTypeInterface::class);
            }

            if ('one' === $item->getType()) {
                if (in_array($item->getName(), $validatedNames)) {
                    $this->context->buildViolation($constraint->message)
                        ->setParameter('{{ name }}', $item->getName())
                        ->addViolation();
                } else {
                    $validatedNames[] = $item->getName();
                }
            }
        }
    }
}
