You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#!php
<?php
namespace AppBundle\Validator\Constraints;
use CCMBenchmark\Ting\Repository\RepositoryFactory;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class UniqueEntityValidator extends ConstraintValidator
{
private $repositoryFactory;
public function __construct(RepositoryFactory $repositoryFactory)
{
$this->repositoryFactory = $repositoryFactory;
}
/**
* @inheritDoc
*/
public function validate($entity, Constraint $constraint)
{
if (!$constraint instanceof UniqueEntity) {
throw new UnexpectedTypeException($constraint, UniqueEntity::class);
}
$repository = $this->repositoryFactory->get($constraint->repository);
$fields = (array)$constraint->fields;
$criteria = [];
foreach ($fields as $field) {
$propertyName = 'get' . $field;
$criteria[$field] = $entity->$propertyName();
}
$myEntity = $repository->getOneBy($criteria);
if ($myEntity !== null) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ data }}', implode(', ', $criteria))
->addViolation();
}
}
}
#!php
<?php
namespace AppBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* Class UniqueEntity
*
* @Annotation
* @Target({"CLASS", "ANNOTATION"})
*/
class UniqueEntity extends Constraint
{
public $message = 'Another entity exists for this data: {{ data }}';
public $repository;
public $fields = array();
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
public function getRequiredOptions()
{
return ['fields', 'repository'];
}
public function getDefaultOption()
{
return ['fields', 'repository'];
}
}
The text was updated successfully, but these errors were encountered:
Original report by Xavier Leune (Bitbucket: [Xavier Leune](https://bitbucket.org/Xavier Leune), ).
Something like that does the job !
The text was updated successfully, but these errors were encountered: