Skip to content

Instantly share code, notes, and snippets.

@wapcrazut
Last active July 15, 2019 07:24
Show Gist options
  • Save wapcrazut/9886bbf6ff010a39699bb50949026445 to your computer and use it in GitHub Desktop.
Save wapcrazut/9886bbf6ff010a39699bb50949026445 to your computer and use it in GitHub Desktop.
How to manually apply constraints to object.
<?php
// Symfony 4 Manual Constraints.
// $obj is your entity object.
private $validator;
// Class ...
public function __constuct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
public function getErrors($obj)
{
$input = [
'origin' => $obj->getOrigin(),
'campaign' => $obj->getCampaign()
];
$constraints = new Collection([
'origin' => new NotBlank(),
'campaign' => new NotBlank()
]);
$violations = $this->validator->validate($input, $constraints);
$errorMessages = [];
if (count($violations) > 0) {
$accessor = PropertyAccess::createPropertyAccessor();
foreach ($violations as $violation) {
$accessor->setValue($errorMessages,
$violation->getPropertyPath(),
$violation->getMessage());
}
}
return $errorMessages
}
//...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment