Skip to content

Instantly share code, notes, and snippets.

Created December 12, 2015 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/c44fc5a1068b13e9ca22 to your computer and use it in GitHub Desktop.
Save anonymous/c44fc5a1068b13e9ca22 to your computer and use it in GitHub Desktop.
Validator Component in a standalone project
<?php
namespace Company\Entity;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
abstract class EntityValidator
{
public function validate(ValidatorInterface $validator, array $groups = array())
{
return $this->parseValidationMessages(
$validator->validate($this, $groups)
);
}
private function parseValidationMessages(ConstraintViolationListInterface $messages)
{
if (count($messages) == 0) {
return array();
}
$errors = array();
/** @var ConstraintViolationInterface $message */
foreach ($messages as $message) {
$propertyPath = $message->getPropertyPath();
if (empty($propertyPath) && is_object($message->getInvalidValue())) {
$propertyPath = "class";
}
$errors[$propertyPath][] = $message->getMessage();
}
return $errors;
}
}
<?php
namespace Company\User;
use Symfony\Component\Validator\Constraints as Assert;
use Company\Entity\EntityValidator;
class UserEntity extends EntityValidator
{
/**
* @var string
*
* @Assert\NotBlank(
* message = "The username should not be empty!",
* groups = {"insert", "update"}
* )
*/
protected $username;
}
<?php
namespace Company\Services;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Cache\FilesystemCache;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Validation;
class ValidatorFactory
{
private $translator;
private $config;
private $debug;
public function __construct(Translator $translator, array $config, $debug = false)
{
$this->translator = $translator;
$this->config = $config;
$this->debug = $debug;
}
public function getValidator()
{
$builder = Validation::createValidatorBuilder();
$builder->setTranslator($this->translator);
$builder->setTranslationDomain("constraints");
AnnotationRegistry::registerAutoloadNamespace(
"Symfony\\Component\\Validator\\Constraint",
realpath($this->config['source'] . "_vendor" . DS . "symfony" . DS . "validator" . DS)
);
$annotationReader = new AnnotationReader();
$cache = new FilesystemCache($this->config['cache']);
$builder->enableAnnotationMapping(new CachedReader($annotationReader, $cache, true));
return $builder->getValidator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment