<?php

namespace Webkul\DamBundle\Classes\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Validation;

class UniqueCodeValidator extends ConstraintValidator
{
    private $repo;

    public function __construct($repo = null)
    {
        $this->repo = $repo;
    }

    public function validate($asset, Constraint $constraint)
    {
        $qb = $this->repo->createQueryBuilder('a');
        $expr = $qb->expr();
        if ($asset->getId()) {
            $qb->Andwhere('a.id'.' != :id');
            $qb->setParameter('id', $asset->getId());
        }

        $qb->Andwhere('a.code'.' = :code');
        $qb->setParameter('code', $type->getCode());

        $result = $qb->getQuery()->getResult();
        if (count($result)) {
            $this->context->buildViolation($constraint->message)
                            ->atPath('code')
                            ->addViolation();
        }
    }
}
