Skip to content

Instantly share code, notes, and snippets.

@thedomeffm
Created August 27, 2021 18:40
Show Gist options
  • Save thedomeffm/645550e3009c7087fa77190703e26ca4 to your computer and use it in GitHub Desktop.
Save thedomeffm/645550e3009c7087fa77190703e26ca4 to your computer and use it in GitHub Desktop.
Mongo ODM Unique Assert
<?php declare(strict_types=1);
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class UniqueInCollection extends Constraint
{
public string $message = 'The value "{{ value }}" is already taken.';
}
<?php declare(strict_types=1);
namespace App\Validator\Constraints;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class UniqueInCollectionValidator extends ConstraintValidator
{
public function __construct(private DocumentManager $dm) {}
public function validate($value, Constraint $constraint)
{
if (null === $value || '' === $value) {
return;
}
if (!is_string($value)) {
throw new UnexpectedValueException($value, 'string');
}
if ($this->dm->getRepository($this->context->getClassName())
->findOneBy([$this->context->getPropertyName() => $value])) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $value)
->addViolation();
}
}
}
<?php declare(strict_types=1);
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\Validator\Constraints as Assert;
use App\Validator\Constraints as AppAssert; // <-- this is the new custom assertion
/**
* @ODM\Document(collection="guides")
*/
class YourClass
{
/**
* @ODM\Field(type="string")
*
* @AppAssert\UniqueInCollection
* @Assert\NotBlank()
* @Assert\Length(
* min=6,
* max=120
* )
*/
private string $propThatShouldBeUniqueInCollection = '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment