Skip to content

Instantly share code, notes, and snippets.

@tarlepp
Last active September 12, 2020 17:15
Show Gist options
  • Select an option

  • Save tarlepp/b75d6f2e50ac0526fd9f373cd7a0f958 to your computer and use it in GitHub Desktop.

Select an option

Save tarlepp/b75d6f2e50ac0526fd9f373cd7a0f958 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types = 1);
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
* @Target({"CLASS"})
*/
class UniqueEmail extends Constraint
{
public const IS_UNIQUE_EMAIL_ERROR = 'd487278d-8b13-4da0-b4cc-f862e6e99af6';
public const MESSAGE = 'This email is already taken.';
protected static $errorNames = [
self::IS_UNIQUE_EMAIL_ERROR => 'IS_UNIQUE_EMAIL_ERROR',
];
public function getTargets(): string
{
return self::CLASS_CONSTRAINT;
}
}
<?php
declare(strict_types = 1);
namespace App\Validator\Constraints;
use App\Entity\Interfaces\UserInterface;
use App\Repository\UserRepository;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class UniqueEmailValidator extends ConstraintValidator
{
private UserRepository $repository;
public function __construct(UserRepository $repository)
{
$this->repository = $repository;
}
public function validate($value, Constraint $constraint): void
{
if ($value instanceof UserInterface
&& !$this->repository->isEmailAvailable($value->getEmail(), $value->getId())
) {
$this->context
->buildViolation(UniqueEmail::MESSAGE)
->setCode(UniqueEmail::IS_UNIQUE_EMAIL_ERROR)
->addViolation();
}
}
}
<?php
declare(strict_types = 1);
use App\Validator\Constraints as AppAssert;
/**
* @AppAssert\UniqueEmail()
*/
class UserDto
{
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment