Skip to content

Instantly share code, notes, and snippets.

@ostrolucky
Created December 17, 2017 01:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostrolucky/7b4a7133e51f6b5ffcb598a287acb5f7 to your computer and use it in GitHub Desktop.
Save ostrolucky/7b4a7133e51f6b5ffcb598a287acb5f7 to your computer and use it in GitHub Desktop.
UniqueDTOValidator
<?php
declare(strict_types=1);
namespace App\Validator\Constraints;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Checks if entity associatied to DTO is unique.
*
* @Annotation
* @Target({"CLASS", "ANNOTATION"})
*/
class UniqueDTO extends UniqueEntity
{
/**
* Class on which will be DTO transferred before uniqueness check.
*
* @var string
*/
public $mapToEntityClass;
/**
* Entity class which will be used for uniqueness check.
*
* @var string
*/
public $entityClass;
/**
* @return string[]
*/
public function getRequiredOptions(): array
{
return ['fields', 'entityClass'];
}
public function validatedBy(): string
{
return UniqueDTOValidator::class;
}
}
<?php
declare(strict_types=1);
namespace App\Validator\Constraints;
use AutoMapperPlus\AutoMapperInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class UniqueDTOValidator extends ConstraintValidator
{
/**
* @var UniqueEntityValidator
*/
private $uniqueEntityValidator;
/**
* @var AutoMapperInterface
*/
private $autoMapper;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(
UniqueEntityValidator $uniqueEntityValidator,
AutoMapperInterface $autoMapper,
EntityManagerInterface $entityManager
) {
$this->autoMapper = $autoMapper;
$this->uniqueEntityValidator = $uniqueEntityValidator;
$this->entityManager = $entityManager;
}
/**
* @param object $dtoObject
* @param UniqueDTO|Constraint $constraint
*/
public function validate($dtoObject, Constraint $constraint): void
{
$entity = $this->getEntity($dtoObject, $constraint);
$this->uniqueEntityValidator->context = $this->context;
$this->uniqueEntityValidator->validate($entity, $constraint);
}
/**
* @param object $dtoObject
* @param UniqueDTO|Constraint $constraint
*
* @return object
*/
private function getEntity($dtoObject, Constraint $constraint)
{
$entityClass = $constraint->mapToEntityClass ?: $constraint->entityClass;
if (property_exists($dtoObject, 'id')) {
$entity = $this->entityManager->getRepository($entityClass)->find($dtoObject->id);
return $this->autoMapper->mapToObject($dtoObject, $entity);
}
return $this->autoMapper->map($dtoObject, $entityClass);
}
}
@maxson007
Copy link

Merci

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment