Last active
July 15, 2019 07:24
-
-
Save wapcrazut/9886bbf6ff010a39699bb50949026445 to your computer and use it in GitHub Desktop.
How to manually apply constraints to object.
This file contains hidden or 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 | |
// 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