Created
August 27, 2021 18:40
-
-
Save thedomeffm/645550e3009c7087fa77190703e26ca4 to your computer and use it in GitHub Desktop.
Mongo ODM Unique Assert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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.'; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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