Last active
November 9, 2015 19:27
-
-
Save backbone87/4bd02388a0e96815c3a6 to your computer and use it in GitHub Desktop.
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 | |
use Symfony\Component\Validator\Constraint; | |
/** | |
* @Annotation | |
* @author Oliver Hoff <oliver@hofff.com> | |
*/ | |
class Validate extends Constraint { | |
/** | |
* @var array<string, string|array<string>> | |
*/ | |
public $map; | |
/** | |
* @param string $options | |
*/ | |
public function __construct($options = null) { | |
parent::__construct($options); | |
is_array($this->map) || $this->map = array(); | |
if($this->map) { | |
isset($this->groups) || $this->groups = array(); | |
$this->groups = array_unique(array_merge($this->groups, array_keys($this->map))); | |
} | |
} | |
/** | |
* @see \Symfony\Component\Validator\Constraint::getDefaultOption() | |
*/ | |
public function getDefaultOption() { | |
return 'map'; | |
} | |
} |
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 | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\ConstraintValidator; | |
use Symfony\Component\Validator\Context\ExecutionContextInterface; | |
use Symfony\Component\Validator\Exception\UnexpectedTypeException; | |
/** | |
* @author Oliver Hoff <oliver@hofff.com> | |
*/ | |
class ValidateValidator extends ConstraintValidator { | |
/** | |
* @see \Symfony\Component\Validator\ConstraintValidatorInterface::validate() | |
*/ | |
public function validate($value, Constraint $constraint) { | |
if(!$constraint instanceof Validate) { | |
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Validate'); | |
} | |
if(null === $value) { | |
return; | |
} | |
/* @var $context ExecutionContextInterface */ | |
$context = $this->context; | |
$validationGroup = $context->getGroup(); | |
$groups = isset($constraint->map[$validationGroup]) | |
? $constraint->map[$validationGroup] | |
: null; | |
$context->getValidator() | |
->inContext($context) | |
->validate($value, null, $groups); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment