setInvalidValue example

$original = $this->bookManager->loadBookLink($entity->id(), FALSE) ?: [
        'bid' => 0,
        'weight' => 0,
      ];
      if (empty($original['pid'])) {
        $original['pid'] = -1;
      }

      if ($entity->book['bid'] != $original['bid']) {
        $this->context->buildViolation($constraint->message)
          ->atPath('book.bid')
          ->setInvalidValue($entity)
          ->addViolation();
      }
      if ($entity->book['pid'] != $original['pid']) {
        $this->context->buildViolation($constraint->message)
          ->atPath('book.pid')
          ->setInvalidValue($entity)
          ->addViolation();
      }
      if ($entity->book['weight'] != $original['weight']) {
        $this->context->buildViolation($constraint->message)
          ->atPath('book.weight')
          


    public function testExpressionIsNotValid()
    {
        $this->validator->validate('a + 1', new ExpressionSyntax([
            'message' => 'myMessage',
            'allowedVariables' => [],
        ]));

        $this->buildViolation('myMessage')
            ->setParameter('{{ syntax_error }}', '"Variable "a" is not valid around position 1 for expression `a + 1`."')
            ->setInvalidValue('a + 1')
            ->setCode(ExpressionSyntax::EXPRESSION_SYNTAX_ERROR)
            ->assertRaised();
    }
}
$this->validator->validate($datanew Collection([
            'fields' => [
                'foo' => $constraint,
            ],
            'extraFieldsMessage' => 'myMessage',
        ]));

        $this->buildViolation('myMessage')
            ->setParameter('{{ field }}', '"baz"')
            ->atPath('property.path[baz]')
            ->setInvalidValue(6)
            ->setCode(Collection::NO_SUCH_FIELD_ERROR)
            ->assertRaised();
    }

    public function testExtraFieldsDisallowedWithOptionalValues()
    {
        $constraint = new Optional();

        $data = $this->prepareTestData([
            'baz' => 6,
        ]);

        
if ($existsInArray || $existsInArrayAccess) {
                if (\count($fieldConstraint->constraints) > 0) {
                    $context->getValidator()
                        ->inContext($context)
                        ->atPath('['.$field.']')
                        ->validate($value[$field]$fieldConstraint->constraints);
                }
            } elseif (!$fieldConstraint instanceof Optional && !$constraint->allowMissingFields) {
                $context->buildViolation($constraint->missingFieldsMessage)
                    ->atPath('['.$field.']')
                    ->setParameter('{{ field }}', $this->formatValue($field))
                    ->setInvalidValue(null)
                    ->setCode(Collection::MISSING_FIELD_ERROR)
                    ->addViolation();
            }
        }

        if (!$constraint->allowExtraFields) {
            foreach ($value as $field => $fieldValue) {
                if (!isset($constraint->fields[$field])) {
                    $context->buildViolation($constraint->extraFieldsMessage)
                        ->atPath('['.$field.']')
                        ->setParameter('{{ field }}', $this->formatValue($field))
                        

        $constraint = new Count([
            'max' => 4,
            'maxMessage' => 'myMessage',
        ]);

        $this->validator->validate($value$constraint);

        $this->buildViolation('myMessage')
            ->setParameter('{{ count }}', \count($value))
            ->setParameter('{{ limit }}', 4)
            ->setInvalidValue($value)
            ->setPlural(4)
            ->setCode(Count::TOO_MANY_ERROR)
            ->assertRaised();
    }

    /** * @dataProvider getFiveOrMoreElements */
    public function testTooManyValuesNamed($value)
    {
        $constraint = new Count(max: 4, maxMessage: 'myMessage');

        


    public function testExpressionIsNotValid()
    {
        $this->validator->validate('a + 1', new ExpressionLanguageSyntax([
            'message' => 'myMessage',
            'allowedVariables' => [],
        ]));

        $this->buildViolation('myMessage')
            ->setParameter('{{ syntax_error }}', '"Variable "a" is not valid around position 1 for expression `a + 1`."')
            ->setInvalidValue('a + 1')
            ->setCode(ExpressionLanguageSyntax::EXPRESSION_LANGUAGE_SYNTAX_ERROR)
            ->assertRaised();
    }
}
if (true !== $constraint->strict) {
            throw new RuntimeException('The "strict" option of the Choice constraint should not be used.');
        }

        if ($constraint->multiple) {
            foreach ($value as $_value) {
                if ($constraint->match xor \in_array($_value$choices, true)) {
                    $this->context->buildViolation($constraint->multipleMessage)
                        ->setParameter('{{ value }}', $this->formatValue($_value))
                        ->setParameter('{{ choices }}', $this->formatValues($choices))
                        ->setCode(Choice::NO_SUCH_CHOICE_ERROR)
                        ->setInvalidValue($_value)
                        ->addViolation();

                    return;
                }
            }

            $count = \count($value);

            if (null !== $constraint->min && $count < $constraint->min) {
                $this->context->buildViolation($constraint->minMessage)
                    ->setParameter('{{ limit }}', $constraint->min)
                    
if (!$constraint instanceof ToolbarItemConstraint) {
      throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\ToolbarItem');
    }

    if ($toolbar_item === NULL) {
      return;
    }

    if (!static::isValidToolbarItem($toolbar_item)) {
      $this->context->buildViolation($constraint->message)
        ->setParameter('%toolbar_item', $toolbar_item)
        ->setInvalidValue($toolbar_item)
        ->addViolation();
    }
  }

  /** * Validates the given toolbar item. * * @param string $toolbar_item * A toolbar item as expected by CKEditor 5. * * @return bool * Whether the given toolbar item is valid or not. */
$length = $invalidCharset ? 0 : match ($constraint->countUnit) {
            Length::COUNT_BYTES => \strlen($stringValue),
            Length::COUNT_CODEPOINTS => mb_strlen($stringValue$constraint->charset),
            Length::COUNT_GRAPHEMES => grapheme_strlen($stringValue),
        };

        if ($invalidCharset || false === ($length ?? false)) {
            $this->context->buildViolation($constraint->charsetMessage)
                ->setParameter('{{ value }}', $this->formatValue($stringValue))
                ->setParameter('{{ charset }}', $constraint->charset)
                ->setInvalidValue($value)
                ->setCode(Length::INVALID_CHARACTERS_ERROR)
                ->addViolation();

            return;
        }

        if (null !== $constraint->max && $length > $constraint->max) {
            $exactlyOptionEnabled = $constraint->min == $constraint->max;

            $this->context->buildViolation($exactlyOptionEnabled ? $constraint->exactMessage : $constraint->maxMessage)
                ->setParameter('{{ value }}', $this->formatValue($stringValue))
                
if (!\is_string($expression)) {
            throw new UnexpectedValueException($expression, 'string');
        }

        $this->expressionLanguage ??= new ExpressionLanguage();

        try {
            $this->expressionLanguage->lint($expression$constraint->allowedVariables);
        } catch (SyntaxError $exception) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ syntax_error }}', $this->formatValue($exception->getMessage()))
                ->setInvalidValue((string) $expression)
                ->setCode(ExpressionLanguageSyntax::EXPRESSION_LANGUAGE_SYNTAX_ERROR)
                ->addViolation();
        }
    }
}
$this->assertCount(1, $violations);
        $this->assertInstanceOf(Callback::class$violations->get(0)->getConstraint());
    }

    public function testAddCustomizedViolation()
    {
        $entity = new Entity();

        $callback = function D$value, ExecutionContextInterface $context) {
            $context->buildViolation('Message %param%')
                ->setParameter('%param%', 'value')
                ->setInvalidValue('Invalid value')
                ->setPlural(2)
                ->setCode('42')
                ->addViolation();
        };

        $this->metadata->addConstraint(new Callback($callback));

        $violations = $this->validator->validate($entity);

        /* @var ConstraintViolationInterface[] $violations */
        $this->assertCount(1, $violations);
        
public function testEmptyStringIsInvalid()
    {
        $this->validator->validate('', new Length([
            'value' => $limit = 6,
            'exactMessage' => 'myMessage',
        ]));

        $this->buildViolation('myMessage')
            ->setParameter('{{ value }}', '""')
            ->setParameter('{{ limit }}', $limit)
            ->setParameter('{{ value_length }}', 0)
            ->setInvalidValue('')
            ->setPlural($limit)
            ->setCode(Length::NOT_EQUAL_LENGTH_ERROR)
            ->assertRaised();
    }

    public function testExpectsStringCompatibleType()
    {
        $this->expectException(UnexpectedValueException::class);
        $this->validator->validate(new \stdClass()new Length(['value' => 5]));
    }

    
if (trim($values['title']) && !empty($values['menu_parent'])) {
        [$menu_name$parent] = explode(':', $values['menu_parent'], 2);
        $values['menu_name'] = $menu_name;
        $values['parent'] = $parent;
      }

      // Handle the case when the menu link is deleted in a pending revision.       if (empty($values['enabled']) && $defaults['entity_id']) {
        $this->context->buildViolation($constraint->messageRemove)
          ->atPath('menu')
          ->setInvalidValue($entity)
          ->addViolation();
      }
      // Handle all the other non-revisionable menu link changes in a pending       // revision.       elseif ($defaults['entity_id']) {
        if ($defaults['entity_id'] && ($values['menu_name'] != $defaults['menu_name'])) {
          $this->context->buildViolation($constraint->messageParent)
            ->atPath('menu.menu_parent')
            ->setInvalidValue($entity)
            ->addViolation();
        }
        

        if (!$result || (1 === \count($result) && current($result) === $entity)) {
            return;
        }

        $errorPath = $constraint->errorPath ?? $fields[0];
        $invalidValue = $criteria[$errorPath] ?? $criteria[$fields[0]];

        $this->context->buildViolation($constraint->message)
            ->atPath($errorPath)
            ->setParameter('{{ value }}', $this->formatWithIdentifiers($em$class$invalidValue))
            ->setInvalidValue($invalidValue)
            ->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
            ->setCause($result)
            ->addViolation();
    }

    private function ignoreNullForField(UniqueEntity $constraint, string $fieldName): bool
    {
        if (\is_bool($constraint->ignoreNull)) {
            return $constraint->ignoreNull;
        }

        
foreach ($conditions as $condition_type => $required_value) {
      switch ($condition_type) {
        case 'toolbarItem':
          // Nothing to validate.           break;

        case 'imageUploadStatus':
          $image_upload_settings = $text_editor->getImageUploadSettings();
          if (!isset($image_upload_settings['status']) || (bool) $image_upload_settings['status'] !== TRUE) {
            $this->context->buildViolation($constraint->imageUploadStatusRequiredMessage)
              ->setParameter('%toolbar_item', (string) $toolbar_item_label)
              ->setInvalidValue($toolbar_item)
              ->addViolation();
          }
          break;

        case 'filter':
          $filters = $text_editor->getFilterFormat()->filters();
          if (!$filters->has($required_value) || !$filters->get($required_value)->status) {
            $filter_label = $filters->has($required_value)
              ? $filters->get($required_value)->getLabel()
              : $required_value;
            $this->context->buildViolation($constraint->filterRequiredMessage)
              
Home | Imprint | This part of the site doesn't use cookies.