A constraint can be defined on a class, an option or a getter method. The Constraint class encapsulates all the configuration required for validating this class, option or getter result successfully. Constraint instances are immutable and serializable.
Author: Bernhard Schussek (bschussek@gmail.com)
 /**
  * Checks if current workflow item allows transition
  *
  * @param WorkflowData $value
  * @param TransitionIsAllowed $constraint
  */
 public function validate($value, Constraint $constraint)
 {
     /** @var WorkflowItem $workflowItem */
     $workflowItem = $constraint->getWorkflowItem();
     $transitionName = $constraint->getTransitionName();
     $workflow = $this->registry->getWorkflow($workflowItem->getWorkflowName());
     $errors = new ArrayCollection();
     $result = false;
     try {
         $result = $workflow->isTransitionAllowed($workflowItem, $transitionName, $errors, true);
     } catch (InvalidTransitionException $e) {
         switch ($e->getCode()) {
             case InvalidTransitionException::UNKNOWN_TRANSITION:
                 $errors->add(array('message' => $constraint->unknownTransitionMessage, 'parameters' => array('{{ transition }}' => $transitionName)));
                 break;
             case InvalidTransitionException::NOT_START_TRANSITION:
                 $errors->add(array('message' => $constraint->notStartTransitionMessage, 'parameters' => array('{{ transition }}' => $transitionName)));
                 break;
             case InvalidTransitionException::STEP_HAS_NO_ALLOWED_TRANSITION:
                 $errors->add(array('message' => $constraint->stepHasNotAllowedTransitionMessage, 'parameters' => array('{{ transition }}' => $transitionName, '{{ step }}' => $workflowItem->getCurrentStep()->getName())));
                 break;
         }
     }
     if (!$result) {
         if ($errors->count()) {
             foreach ($errors as $error) {
                 $this->context->addViolation($error['message'], $error['parameters']);
             }
         } else {
             $this->context->addViolation($constraint->someConditionsNotMetMessage);
         }
     }
 }
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof TokenEntity) {
         throw new \InvalidArgumentException('Given constraint must ne instance of TokenEntity class');
     }
     if ($value) {
         $configValidation = false;
         try {
             /** @var StorageApi $storageApi */
             $storageApi = $constraint->getStorageApi();
             $token = $storageApi->getToken($value);
             if (!$token) {
                 throw new \Exception('Token does not exists');
             }
             $userToken = new Token($storageApi);
             $configValidation = true;
             $components = new Components(new StorageApi(array('token' => $token['token'], 'url' => $storageApi->getApiUrl(), 'userAgent' => $storageApi->getUserAgent())));
             $components->listComponents(new ListConfigurationsOptions());
         } catch (\Exception $e) {
             if ($e instanceof \Keboola\StorageApi\ClientException && $e->getCode() === 403) {
                 //@FIXME jak zmenit api exception code
                 if ($configValidation) {
                     $this->context->addViolation($constraint->configMessage, array('%string%' => $value), null, null, 'TOKEN_PERMISSION');
                 } else {
                     $this->context->addViolation($constraint->permissionsMessage, array(), null, null, 'TOKEN_PERMISSION');
                 }
             } else {
                 $this->context->addViolation($constraint->message, array('%string%' => $value));
             }
             return;
         }
         //@FIXME doplnit validaci na master token!!!
     }
 }
 /**
  * {@inheritdoc}
  *
  * @throws UnexpectedTypeException When the constraint isn't a subclass of {@see AbstractAssertionConstraint}
  * @throws ConstraintDefinitionException When the assertion doesn't exist on the assertion class
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof AbstractAssertionConstraint) {
         throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\AbstractAssertionConstraint');
     }
     $methodName = $constraint->getAssertionMethodName();
     $callable = [static::$assertClass, $methodName];
     $override = null;
     if (is_callable($callable) === false) {
         throw new ConstraintDefinitionException('Must be a valid callable on the assertion class');
     }
     $parameters = array($value);
     foreach ($constraint->getAssertionParameterNames() as $name) {
         $parameters[] = $constraint->{$name};
     }
     try {
         call_user_func_array($callable, $parameters);
     } catch (\Exception $e) {
         if ($e instanceof static::$assertExceptionClass) {
             $this->context->buildViolation($e->getMessage())->setParameter('{{ value }}', $this->formatValue($value))->setCode($e->getCode())->setCause($e)->addViolation();
         } else {
             throw $e;
         }
     }
 }
 /**
  * Returns the validator for the supplied constraint.
  *
  * @param Constraint $constraint A constraint
  *
  * @return ConstraintValidatorInterface A validator for the supplied constraint
  *
  * @throws UnexpectedTypeException When the validator is not an instance of ConstraintValidatorInterface
  */
 public function getInstance(Constraint $constraint)
 {
     $name = $constraint->validatedBy();
     if (!isset($this->validators[$name])) {
         switch (get_class($constraint)) {
             case self::BASE_NAMESPACE . '\\All':
                 $name = self::BASE_NAMESPACE . '\\LegacyAllValidator';
                 break;
             case self::BASE_NAMESPACE . '\\Choice':
                 $name = self::BASE_NAMESPACE . '\\LegacyChoiceValidator';
                 break;
             case self::BASE_NAMESPACE . '\\Collection':
                 $name = self::BASE_NAMESPACE . '\\LegacyCollectionValidator';
                 break;
             case self::BASE_NAMESPACE . '\\Count':
                 $name = self::BASE_NAMESPACE . '\\LegacyCountValidator';
                 break;
             case self::BASE_NAMESPACE . '\\Length':
                 $name = self::BASE_NAMESPACE . '\\LegacyLengthValidator';
                 break;
             case self::FORM_BASE_NAMESPACE . '\\Form':
                 $name = self::FORM_BASE_NAMESPACE . '\\LegacyFormValidator';
                 break;
         }
         $this->validators[$name] = new $name();
     } elseif (is_string($this->validators[$name])) {
         $this->validators[$name] = $this->container->get($this->validators[$name]);
     }
     if (!$this->validators[$name] instanceof ConstraintValidatorInterface) {
         throw new UnexpectedTypeException($this->validators[$name], 'Symfony\\Component\\Validator\\ConstraintValidatorInterface');
     }
     return $this->validators[$name];
 }
 /**
  * Checks if the passed value is valid.
  *
  * @param mixed $value The value that should be validated
  * @param Constraint $constraint The constraint for the validation
  * @return bool
  */
 public function validate($value, Constraint $constraint)
 {
     /** @var EntityExists $constraint */
     if ($constraint->validate($value)) {
         $this->context->addViolation($constraint->message, ['{{ type }}' => $constraint->entityClass, '{{ value }}' => $value]);
     }
 }
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof OrchestrationTableEntity) {
         throw new \InvalidArgumentException('Given constraint must ne instance of OrchestrationTableEntity class');
     }
     if ($value) {
         // table exists
         try {
             /** @var StorageApi $storageApi */
             $storageApi = $constraint->getStorageApi();
             if (!$storageApi->tableExists($value)) {
                 throw new \Exception('Configuration table does not exists');
             }
         } catch (\Exception $e) {
             $this->context->addViolation($constraint->message, array('%string%' => $value));
             return;
         }
         // table structure
         try {
             /** @var StorageApi $storageApi */
             $storageApi = $constraint->getStorageApi();
             $table = $storageApi->getTable($value);
             $token = new Token($storageApi);
             $requiredColumns = self::getRequiredColumns();
             $missingColumns = array_diff($requiredColumns, $table['columns']);
             if (!empty($missingColumns)) {
                 throw new \Exception('Invalid configuration table structure');
             }
         } catch (\Exception $e) {
             $this->context->addViolation($constraint->structureMessage, array('%string%' => implode(', ', $requiredColumns)));
             return;
         }
     }
 }
 /**
  * {@inheritDoc}
  */
 public function getInstance(Constraint $constraint)
 {
     $className = $constraint->validatedBy();
     if (!isset($this->validators[$className]) || $className === 'Symfony\\Component\\Validator\\Constraints\\CollectionValidator') {
         $this->validators[$className] = new $className();
     }
     return $this->validators[$className];
 }
 /**
  * {@inheritdoc}
  */
 public function getInstance(Constraint $constraint)
 {
     $class_name = $constraint->validatedBy();
     if (!isset($this->validators[$class_name])) {
         $this->validators[$class_name] = $this->classResolver->getInstanceFromDefinition($class_name);
     }
     return $this->validators[$class_name];
 }
 /**
  * {@inheritdoc}
  */
 public function getInstance(Constraint $constraint)
 {
     $className = $constraint->validatedBy();
     if (!isset($this->validators[$className])) {
         $this->validators[$className] = 'validator.expression' === $className ? new ExpressionValidator($this->propertyAccessor) : new $className();
     }
     return $this->validators[$className];
 }
 /**
  * @param Constraint $constraint
  * @return \Symfony\Component\Validator\ConstraintValidatorInterface
  */
 public function getInstance(Constraint $constraint)
 {
     $class_name = $constraint->validatedBy();
     if (!isset($this->validators[$class_name])) {
         $this->validators[$class_name] = new $class_name();
     }
     return $this->validators[$class_name];
 }
Esempio n. 11
0
 /**
  * {@inheritdoc}
  */
 public function addConstraint(Constraint $constraint)
 {
     if (!in_array(Constraint::PROPERTY_CONSTRAINT, (array) $constraint->getTargets())) {
         throw new ConstraintDefinitionException(sprintf('The constraint %s cannot be put on properties or getters', get_class($constraint)));
     }
     parent::addConstraint($constraint);
     return $this;
 }
 /**
  * {@inheritdoc}
  */
 public function getInstance(Constraint $constraint)
 {
     $name = $constraint->validatedBy();
     if (isset($this->serviceNames[$name])) {
         return $this->container[$this->serviceNames[$name]];
     }
     return parent::getInstance($constraint);
 }
 function it_doesnt_support_multi_targets_constraint($guesser, $factory, ClassMetadata $metadata, ProductValueInterface $value, AttributeInterface $attribute, Constraint $multiTargets, Constraint $validNumber)
 {
     $factory->createMetadata(Argument::any())->willReturn($metadata);
     $value->getAttribute()->willReturn($attribute);
     $attribute->getBackendType()->willReturn('varchar');
     $guesser->guessConstraints($attribute)->willReturn([$multiTargets]);
     $multiTargets->getTargets()->willReturn([Constraint::PROPERTY_CONSTRAINT, Constraint::CLASS_CONSTRAINT]);
     $this->shouldThrow(new \LogicException('No support provided for constraint on many targets'))->duringGetMetadataFor($value);
 }
 /**
  * Returns the validator for the supplied constraint.
  *
  * @param  Constraint          $constraint A constraint
  * @return ConstraintValidator A validator for the supplied constraint
  */
 public function getInstance(Constraint $constraint)
 {
     $name = $constraint->validatedBy();
     if (isset($this->validators[$name])) {
         return $this->validators[$name];
     }
     $this->validators[$name] = $this->createValidator($name);
     return $this->validators[$name];
 }
 /**
  * {@inheritdoc}
  */
 public function validate($entity, Constraint $constraint)
 {
     if (!isset($entity)) {
         return;
     }
     if (!in_array($entity->bundle(), $constraint->getBundleOption())) {
         $this->context->addViolation($constraint->message, array('%bundle' => implode(', ', $constraint->getBundleOption())));
     }
 }
Esempio n. 16
0
 /**
  * {@inheritDoc}
  */
 public function validate($value, Constraint $constraint)
 {
     $callback = $constraint->getFilterCallback();
     $entity = $constraint->getMapper()->findBy($callback($value));
     if ($entity instanceof AbstractEntity) {
         return;
     }
     $this->context->addViolation($constraint->message, ['{{ field }}' => $constraint->field, '{{ value }}' => $value], $value);
 }
 /**
  * {@inheritDoc}
  */
 public function getInstance(Constraint $constraint)
 {
     $name = $constraint->validatedBy();
     if (!isset($this->validators[$name])) {
         $this->validators[$name] = new $name();
     } elseif (is_string($this->validators[$name])) {
         $this->validators[$name] = $this->serviceLocator->getService($this->validators[$name]);
     }
     return $this->validators[$name];
 }
 public function validate($commitEntity, Constraint $constraint)
 {
     $statusHash = $commitEntity->getStatusHash();
     $this->projectEnvironment = $this->projectEnvironmentStorage->getProjectEnviromment($commitEntity->getProject());
     $this->gitStatusCommand->overRideGitEnvironment($this->projectEnvironment);
     $currentStatusHash = $this->gitStatusCommand->getStatusHash();
     if ($currentStatusHash !== $statusHash) {
         $this->context->buildViolation($constraint->getMessage())->setParameter('{{statushash}}', $statusHash)->setParameter('{{currentstatushash}}', $currentStatusHash)->atPath('files')->addViolation();
     }
 }
 /**
  * Returns the validator for the supplied constraint.
  *
  * @param Constraint $constraint A constraint
  *
  * @return Symfony\Component\Validator\ConstraintValidator A validator for the supplied constraint
  */
 public function getInstance(Constraint $constraint)
 {
     $className = $constraint->validatedBy();
     if (!isset($this->validators[$className])) {
         $this->validators[$className] = new $className();
     } elseif (is_string($this->validators[$className])) {
         $this->validators[$className] = $this->container[$this->validators[$className]];
     }
     return $this->validators[$className];
 }
 /**
  * @param ClassMetadata      $metadata
  * @param Constraint         $constraint
  * @param AttributeInterface $attribute
  */
 protected function addConstraint(ClassMetadata $metadata, Constraint $constraint, AttributeInterface $attribute)
 {
     $target = $constraint->getTargets();
     if (is_array($target)) {
         throw new \LogicException('No support provided for constraint on many targets');
     } elseif (Constraint::PROPERTY_CONSTRAINT === $target) {
         $metadata->addPropertyConstraint($attribute->getBackendType(), $constraint);
     } elseif (Constraint::CLASS_CONSTRAINT === $target) {
         $metadata->addConstraint($constraint);
     }
 }
Esempio n. 21
0
 /**
  * {@inheritDoc}
  */
 public function addConstraint(Constraint $constraint)
 {
     if (!in_array(Constraint::PROPERTY_CONSTRAINT, (array) $constraint->targets())) {
         throw new ConstraintDefinitionException(sprintf('The constraint %s cannot be put on properties or getters', get_class($constraint)));
     }
     if ($constraint instanceof Valid) {
         $this->cascaded = true;
     } else {
         parent::addConstraint($constraint);
     }
     return $this;
 }
Esempio n. 22
0
 /**
  * Checks if the passed value is valid.
  *
  * @param mixed      $value      The value that should be validated
  * @param Constraint $constraint The constraint for the validation
  *
  * @api
  */
 public function validate($value, Constraint $constraint)
 {
     $groupName = $constraint->getGroupName();
     foreach ($value as $user) {
         $groups = $user->getGroups();
         foreach ($groups as $group) {
             if ($group->getName() != $groupName) {
                 $this->context->addViolation('message', array('%group%' => $groupName));
             }
         }
     }
 }
 /**
  * Checks if the passed value is valid.
  *
  * @api
  *
  * @param mixed $value The value that should be validated
  * @param \Symfony\Component\Validator\Constraint|\Spryker\Zed\Category\Communication\Constraint\CategoryNameExists $constraint The constraint for the validation
  *
  * @return void
  */
 public function validate($value, Constraint $constraint)
 {
     $idLocale = $constraint->getLocale()->getIdLocale();
     $idCategory = $constraint->getIdCategory();
     $categoryQueryContainer = $constraint->getQueryContainer();
     $categoryEntity = $categoryQueryContainer->queryCategory($value, $idLocale)->findOne();
     if ($categoryEntity !== null) {
         if ($idCategory === null || $idCategory !== $categoryEntity->getIdCategory()) {
             $this->addViolation($value, $constraint);
         }
     }
 }
 public function getInstance(Constraint $constraint)
 {
     $className = $constraint->validatedBy();
     if (!isset($this->validators[$className])) {
         if (class_exists($className)) {
             $this->validators[$className] = new $className();
         } else {
             $this->validators[$className] = $this->app[$className];
         }
     }
     return $this->validators[$className];
 }
 /**
  * Returns the validator for the supplied constraint.
  *
  * @param Constraint $constraint A constraint
  *       
  * @return ConstraintValidatorInterface A validator for the supplied constraint
  *        
  * @throws UnexpectedTypeException When the validator is not an instance of ConstraintValidatorInterface
  */
 public function getInstance(Constraint $constraint)
 {
     $name = $constraint->validatedBy();
     if (!isset($this->validators[$name])) {
         $this->validators[$name] = new $name();
     } elseif (is_string($this->validators[$name])) {
         $this->validators[$name] = $this->container->get($this->validators[$name]);
     }
     if (!$this->validators[$name] instanceof ConstraintValidatorInterface) {
         throw new UnexpectedTypeException($this->validators[$name], 'Symfony\\Component\\Validator\\ConstraintValidatorInterface');
     }
     return $this->validators[$name];
 }
 /**
  * Returns a contraint validator from the container service, setting it if it
  * doesn't exist yet
  *
  * Throws an exception if validator service is not instance of
  * ConstraintValidatorInterface.
  *
  * @param  Constraint $constraint
  * @return ConstraintValidatorInterface
  * @throws \LogicException
  */
 public function getInstance(Constraint $constraint)
 {
     $className = $constraint->validatedBy();
     $id = $this->getServiceIdFromClass($className);
     if (!$this->container->has($id)) {
         $this->container->set($id, new $className());
     }
     $validator = $this->container->get($id);
     if (!$validator instanceof ConstraintValidatorInterface) {
         throw new \LogicException('Service "' . $id . '" is not instance of ConstraintValidatorInterface');
     }
     return $validator;
 }
Esempio n. 27
0
 private function validateSize(Constraint $constraint, $size, $type, array $parameters)
 {
     if ($constraint->min == $constraint->max && $size != $constraint->max) {
         $this->context->addViolation($constraint->getExactMessage($type), array_merge(array('{{ limit }}' => $constraint->max), $parameters), null, (int) $constraint->max);
         return;
     }
     if (null !== $constraint->max && $size > $constraint->max) {
         $this->context->addViolation($constraint->getMaxMessage($type), array_merge(array('{{ limit }}' => $constraint->max), $parameters), null, (int) $constraint->max);
         return;
     }
     if (null !== $constraint->min && $size < $constraint->min) {
         $this->context->addViolation($constraint->getMinMessage($type), array_merge(array('{{ limit }}' => $constraint->min), $parameters), null, (int) $constraint->min);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     /* @var OwnOrAdminConstraintInterface $constraint */
     $account = $constraint->getAccount();
     if ($value == $account->id()) {
         // No violation if the user is the same as the provided one.
         return NULL;
     }
     if ($account->hasPermission($constraint->getPermission())) {
         // No violation if the current user has admin rights.
         return NULL;
     }
     $this->context->addViolation($constraint->message, ['@permission' => $constraint->getPermission()]);
 }
 public function validate($value, Constraint $constraint)
 {
     $today = new \DateTime();
     if ($value > $today) {
         $this->context->addViolation($constraint->message1);
     }
     if ($value <= $constraint->getColonie()->getDateColonie()) {
         $this->context->addViolation($constraint->message2);
     }
     if (!$constraint->getColonie()->getVisites()->isEmpty()) {
         if ($value <= $constraint->getColonie()->getVisites()->last()->getDate()) {
             $this->context->addViolation($constraint->message3);
         }
     }
     if (!$constraint->getColonie()->getRemerages()->isEmpty()) {
         if ($value <= $constraint->getColonie()->getRemerages()->last()->getDate()) {
             $this->context->addViolation($constraint->message4);
         }
     }
     if (!$constraint->getColonie()->getTranshumances()->isEmpty()) {
         if ($value <= $constraint->getColonie()->getTranshumances()->last()->getDate()) {
             $this->context->addViolation($constraint->message5);
         }
     }
 }
 /**
  * {@inheritDoc}
  */
 public function __construct($options = null)
 {
     if (!isset($options['value'])) {
         throw new ConstraintDefinitionException(sprintf('The %s constraint requires the "value" option to be set.', get_class($this)));
     }
     parent::__construct($options);
 }