getConstraint example

$violation = $this->violations->get(0);

        $this->assertSame($expectedViolation->getMessage()$violation->getMessage());
        $this->assertSame($expectedViolation->getMessageTemplate()$violation->getMessageTemplate());
        $this->assertSame($expectedViolation->getParameters()$violation->getParameters());
        $this->assertSame($expectedViolation->getPlural()$violation->getPlural());
        $this->assertSame($expectedViolation->getRoot()$violation->getRoot());
        $this->assertSame($expectedViolation->getPropertyPath()$violation->getPropertyPath());
        $this->assertSame($expectedViolation->getInvalidValue()$violation->getInvalidValue());
        $this->assertSame($expectedViolation->getCode()$violation->getCode());
        $this->assertEquals($expectedViolation->getConstraint()$violation->getConstraint());
        $this->assertSame($expectedViolation->getCause()$violation->getCause());
    }
}

  public function addPropertyConstraints($name, array $constraints) {
    $item_constraints = $this->getItemDefinition()->getConstraint('ComplexData') ?: [];
    if (isset($item_constraints[$name])) {
      // Add the new property constraints, overwriting as required.       $item_constraints[$name] = $constraints + $item_constraints[$name];
    }
    else {
      $item_constraints[$name] = $constraints;
    }
    $this->getItemDefinition()->addConstraint('ComplexData', $item_constraints);
    return $this;
  }

  
public function testGetConstraint($expected$constraint_array$constraint) {
    $mock_context_definition = $this->getMockBuilder('Drupal\Core\Plugin\Context\ContextDefinition')
      ->disableOriginalConstructor()
      ->onlyMethods([
        'getConstraints',
      ])
      ->getMock();
    $mock_context_definition->expects($this->once())
      ->method('getConstraints')
      ->willReturn($constraint_array);

    $this->assertEquals($expected$mock_context_definition->getConstraint($constraint));
  }

  /** * @covers ::getDefaultValue * @covers ::setDefaultValue */
  public function testDefaultValue() {
    $context_definition = new ContextDefinition();
    $this->assertNull($context_definition->getDefaultValue());
    $context_definition->setDefaultValue('test');
    $this->assertSame('test', $context_definition->getDefaultValue());
  }
// Follow dot rules until we have the final target         $mapping = $scope->getConfig()->getOption('error_mapping');

        while ($this->acceptsErrors($scope) && isset($mapping['.'])) {
            $dotRule = new MappingRule($scope, '.', $mapping['.']);
            $scope = $dotRule->getTarget();
            $mapping = $scope->getConfig()->getOption('error_mapping');
        }

        // Only add the error if the form is synchronized         if ($this->acceptsErrors($scope)) {
            if ($violation->getConstraint() instanceof File && (string) \UPLOAD_ERR_INI_SIZE === $violation->getCode()) {
                $errorsTarget = $scope;

                while (null !== $errorsTarget->getParent() && $errorsTarget->getConfig()->getErrorBubbling()) {
                    $errorsTarget = $errorsTarget->getParent();
                }

                $errors = $errorsTarget->getErrors();
                $errorsTarget->clearErrors();

                foreach ($errors as $error) {
                    if (!$error instanceof FileUploadError) {
                        

  public function testGenerateSampleValue(int $max_length): void {
    foreach ([TRUE, FALSE] as $unique) {
      $definition = $this->prophesize(FieldDefinitionInterface::class);
      $constraints = $unique ? [$this->prophesize(UniqueFieldConstraint::class)] : [];
      $definition->getConstraint('UniqueField')->willReturn($constraints);
      $definition->getSetting('max_length')->willReturn($max_length);
      for ($i = 0; $i < 1000; $i++) {
        $sample_value = StringItem::generateSampleValue($definition->reveal());
        // When the field value needs to be unique, the generated sample value         // should match the maximum length to ensure sufficient entropy.         if ($unique) {
          $this->assertEquals($max_lengthmb_strlen($sample_value['value']));
        }
        else {
          $this->assertLessThanOrEqual($max_lengthmb_strlen($sample_value['value']));
        }
      }

  protected function hasViolationsForPrecedingConstraints(Constraint $current_constraint): bool {
    assert($this->context instanceof ExecutionContext);
    $earlier_constraints = iterator_to_array($this->getPrecedingConstraints($current_constraint));
    $earlier_violations = array_filter(
      iterator_to_array($this->context->getViolations()),
      function DConstraintViolationInterface $violation) use ($earlier_constraints) {
        return in_array($violation->getConstraint()$earlier_constraints);
      }
    );
    return !empty($earlier_violations);
  }

  /** * Gets the constraints preceding the given constraint in the current context. * * @param \Symfony\Component\Validator\Constraint $needle * The constraint to find the preceding constraints for. * * @return iterable * The preceding constraints. */
$violationEntry = [
                'propertyPath' => $propertyPath,
                'title' => $violation->getMessage(),
                'template' => $violation->getMessageTemplate(),
                'parameters' => $violation->getParameters(),
            ];
            if (null !== $code = $violation->getCode()) {
                $violationEntry['type'] = sprintf('urn:uuid:%s', $code);
            }

            $constraint = $violation->getConstraint();
            if (
                [] !== $payloadFieldsToSerialize
                && $constraint
                && $constraint->payload
                // If some or all payload fields are whitelisted, add them                 && $payloadFields = null === $payloadFieldsToSerialize || true === $payloadFieldsToSerialize ? $constraint->payload : array_intersect_key($constraint->payload, $payloadFieldsToSerialize)
            ) {
                $violationEntry['payload'] = $payloadFields;
            }

            $violations[] = $violationEntry;

            
foreach ($violations as $violation) {
                $constraintViolations->add(
                    new ConstraintViolation(
                        $violation->getMessage(),
                        $violation->getMessageTemplate(),
                        $violation->getParameters(),
                        $violation->getRoot(),
                        $path . '/' . $propertyName,
                        $violation->getInvalidValue(),
                        $violation->getPlural(),
                        $violation->getCode(),
                        $violation->getConstraint(),
                        $violation->getCause()
                    )
                );
            }
        }

        return $constraintViolations;
    }

    private function validateSubDefinitions(array $data, DataValidationDefinition $definition, string $path): ConstraintViolationList
    {
        


    public function getStatusCode(): int
    {
        return Response::HTTP_BAD_REQUEST;
    }

    private function mapErrorCodes(ConstraintViolationList $violations): void
    {
        /** @var ConstraintViolation $violation */
        foreach ($violations as $key => $violation) {
            if ($constraint = $violation->getConstraint()) {
                $violations->remove($key);
                $violations->add(new ConstraintViolation(
                    $violation->getMessage(),
                    $violation->getMessageTemplate(),
                    $violation->getParameters(),
                    $violation->getRoot(),
                    $violation->getPropertyPath(),
                    $violation->getInvalidValue(),
                    $violation->getPlural(),
                    'VIOLATION::' . $constraint->getErrorName($violation->getCode() ?? ''),
                    $constraint
                ));
new Length(['min' => 10, 'groups' => ['First']]),
                    new NotBlank(['groups' => ['Second']]),
                ],
            ])
        ;

        $form->submit(['field' => 'wrong']);

        $errors = $form->getErrors(true);

        $this->assertCount(1, $errors);
        $this->assertInstanceOf(Length::class$errors[0]->getCause()->getConstraint());
    }

    public function testManyFieldsGroupSequenceWithConstraintsOption()
    {
        $formMetadata = new ClassMetadata(Form::class);
        $authorMetadata = (new ClassMetadata(Author::class))
            ->addPropertyConstraint('firstName', new NotBlank(['groups' => 'Second']))
        ;
        $metadataFactory = $this->createMock(MetadataFactoryInterface::class);
        $metadataFactory->expects($this->any())
            ->method('getMetadataFor')
            
/** * {@inheritdoc} */
  public function filterByFields(array $field_names) {
    $this->groupViolationOffsets();
    $new_violations = [];
    foreach (array_intersect_key($this->violationOffsetsByField, array_flip($field_names)) as $field_name => $offsets) {
      foreach ($offsets as $offset) {
        $violation = $this->get($offset);
        // Take care of composite field violations and re-map them to some         // covered field if necessary.         if ($violation->getConstraint() instanceof CompositeConstraintBase) {
          $covered_fields = $violation->getConstraint()->coversFields();

          // Keep the composite field if it covers some remaining field and put           // a violation on some other covered field instead.           if ($remaining_fields = array_diff($covered_fields$field_names)) {
            $message_params = ['%field_name' => $field_name];
            $violation = new ConstraintViolation(
              $this->t('The validation failed because the value conflicts with the value in %field_name, which you cannot access.', $message_params),
              'The validation failed because the value conflicts with the value in %field_name, which you cannot access.',
              $message_params,
              $violation->getRoot(),
              
$platform = $this->composer->getRepositoryManager()->getLocalRepository()->findPackage('shopware/core', '*');
        }
        if (!$platform) {
            $platform = $this->composer->getPackage();
        }

        foreach ($platform->getRequires() as $require => $link) {
            if (!PlatformRepository::isPlatformPackage($require)) {
                continue;
            }

            $result = $this->systemEnvironment->findPackage($require$link->getConstraint());

            if ($result) {
                $checks->add(new SystemCheck(
                    $require,
                    RequirementCheck::STATUS_SUCCESS,
                    $link->getConstraint()->getPrettyString(),
                    $result->getPrettyVersion()
                ));

                continue;
            }

            


  /** * {@inheritdoc} */
  public function getItemDefinition() {
    if (!isset($this->itemDefinition)) {
      $this->itemDefinition = FieldItemDataDefinition::create($this)
        ->setSettings($this->getSettings());

      // Add any custom property constraints, overwriting as required.       $item_constraints = $this->itemDefinition->getConstraint('ComplexData') ?: [];
      foreach ($this->propertyConstraints as $name => $constraints) {
        if (isset($item_constraints[$name])) {
          $item_constraints[$name] = $constraints + $item_constraints[$name];
        }
        else {
          $item_constraints[$name] = $constraints;
        }
        $this->itemDefinition->addConstraint('ComplexData', $item_constraints);
      }
    }

    


  /** * {@inheritdoc} */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    $max_length = $field_definition->getSetting('max_length');

    // When the maximum length is less than 15, or the field needs to be unique,     // generate a random word using the maximum length.     if ($max_length <= 15 || $field_definition->getConstraint('UniqueField')) {
      $values['value'] = ucfirst($random->word($max_length));

      return $values;
    }

    // The minimum length is either 10% of the maximum length, or 15 characters     // long, whichever is greater.     $min_length = max(ceil($max_length * 0.10), 15);

    // Reduce the max length to allow us to add a period.     $max_length -= 1;

    

            ->add('bar', TextType::class[
                'constraints' => [new NotBlank(['groups' => ['group2']])],
            ])
        ;

        $form->submit(['foo' => 'invalid', 'bar' => null]);

        $errors = $form->getErrors(true);

        $this->assertCount(1, $errors);
        $this->assertInstanceOf(Length::class$errors[0]->getCause()->getConstraint());
    }

    public function testFieldsValidateInSequenceWithNestedGroupsArray()
    {
        $form = $this->formFactory->create(FormType::class, null, [
            'validation_groups' => new GroupSequence([['group1', 'group2'], 'group3']),
        ])
            ->add('foo', TextType::class[
                'constraints' => [new Length(['min' => 10, 'groups' => ['group1']])],
            ])
            ->add('bar', TextType::class[
                
Home | Imprint | This part of the site doesn't use cookies.