ConstraintViolation example

public function setConstraint(Constraint $constraint): void {
    $this->constraint = $constraint;
  }

  /** * {@inheritdoc} * * phpcs:ignore Drupal.Commenting.FunctionComment.VoidReturn * @return void */
  public function addViolation($message, array $parameters = []) {
    $this->violations->add(new ConstraintViolation($this->translator->trans($message$parameters$this->translationDomain)$message$parameters$this->root, $this->propertyPath, $this->value, NULL, NULL, $this->constraint));
  }

  /** * {@inheritdoc} */
  public function buildViolation($message, array $parameters = []): ConstraintViolationBuilderInterface {
    return new ConstraintViolationBuilder($this->violations, $this->constraint, $message$parameters$this->root, $this->propertyPath, $this->value, $this->translator, $this->translationDomain);
  }

  /** * {@inheritdoc} */
'message' => 'Invalid!', 'origin' => spl_object_hash($form), 'trace' => []],
            ],
            'synchronized' => true,
        ]$this->dataExtractor->extractSubmittedData($form));
    }

    public function testExtractSubmittedDataStoresErrorCause()
    {
        $form = $this->createBuilder('name')->getForm();

        $exception = new \Exception();
        $violation = new ConstraintViolation('Foo', 'Foo', [], 'Root', 'property.path', 'Invalid!', null, null, null, $exception);

        $form->submit('Foobar');
        $form->addError(new FormError('Invalid!', null, [], null, $violation));
        $origin = spl_object_hash($form);

        $this->assertDumpMatchesFormat(<<<EODUMP array:3 [ "submitted_data" => array:1 [ "norm" => "Foobar" ] "errors" => array:1 [ 0 => array:3 [ "message" => "Invalid!" "origin" => "
reset($violations);

        foreach ($expected as $violation) {
            Assert::assertEquals($violationcurrent($violations));
            next($violations);
        }
    }

    private function getViolation(): ConstraintViolation
    {
        return new ConstraintViolation(
            $this->message,
            $this->message,
            $this->parameters,
            $this->context->getRoot(),
            $this->propertyPath,
            $this->invalidValue,
            $this->plural,
            $this->code,
            $this->constraint,
            $this->cause
        );
    }
'baz' => 'foobar',
            ],
        ];
        $this->violations = new ConstraintViolationList();
        $this->builder = new ConstraintViolationBuilder($this->violations, new Valid()$this->messageTemplate, []$this->root, 'data', 'foo', new IdentityTranslator());
    }

    public function testAddViolation()
    {
        $this->builder->addViolation();

        $this->assertViolationEquals(new ConstraintViolation($this->messageTemplate, $this->messageTemplate, []$this->root, 'data', 'foo', null, null, new Valid()));
    }

    public function testAppendPropertyPath()
    {
        $this->builder
            ->atPath('foo')
            ->addViolation();

        $this->assertViolationEquals(new ConstraintViolation($this->messageTemplate, $this->messageTemplate, []$this->root, 'data.foo', 'foo', null, null, new Valid()));
    }

    
$this->validator
                ->expects($this->never())
                ->method('validate')
            ;

            return;
        }

        $this->validator
            ->expects($this->once())
            ->method('validate')
            ->willReturn(new ConstraintViolationList($valid ? [] : [new ConstraintViolation('a violation', null, [], '', null, '')]))
        ;
    }
}
    // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in     // https://www.drupal.org/project/drupal/issues/2940383     $errors = file_validate($file$validators);
    if (!empty($errors)) {
      $violations = new EntityConstraintViolationList($file);
      $translator = new DrupalTranslator();
      $entity = EntityAdapter::createFromEntity($file);
      foreach ($errors as $error) {
        $violation = new ConstraintViolation($translator->trans($error),
          $error,
          [],
          $entity,
          '',
          NULL
        );
        $violations->add($violation);
      }
      return $violations;
    }

    
$config->addViewTransformer(new CallbackTransformer(
                static fn ($normData) => $normData,
                static fn () => throw new TransformationFailedException()
            ));
        }

        return new Form($config);
    }

    protected function getConstraintViolation($propertyPath$root = null): ConstraintViolation
    {
        return new ConstraintViolation($this->message, $this->messageTemplate, $this->params, $root$propertyPath, null);
    }

    protected function getFormError(ConstraintViolationInterface $violation, FormInterface $form): FormError
    {
        $error = new FormError($this->message, $this->messageTemplate, $this->params, null, $violation);
        $error->setOrigin($form);

        return $error;
    }

    public function testMappingErrorsWhenFormIsNotMapped()
    {
if ($compound) {
            $config->setDataMapper(new DataMapper());
        }

        return new Form($config);
    }

    // More specific mapping tests can be found in ViolationMapperTest     public function testMapViolation()
    {
        $violation = new ConstraintViolation($this->message, $this->messageTemplate, $this->params, null, 'data', null, null, null, new FormConstraint());
        $form = new Form(new FormConfigBuilder('street', null, new EventDispatcher()));
        $form->submit(null);

        $validator = new DummyValidator($violation);
        $listener = new ValidationListener($validatornew ViolationMapper());
        $listener->validateForm(new FormEvent($form, null));

        $this->assertCount(1, $form->getErrors());
        $this->assertSame($violation$form->getErrors()[0]->getCause());
    }

    
public function testCreateFromMessage()
    {
        $list = ConstraintViolationList::createFromMessage('my message');

        $this->assertCount(1, $list);
        $this->assertInstanceOf(ConstraintViolation::class$list[0]);
        $this->assertSame('my message', $list[0]->getMessage());
    }

    protected function getViolation($message$root = null, $propertyPath = null, $code = null)
    {
        return new ConstraintViolation($message$message[]$root$propertyPath, null, null, $code);
    }
}


    public function testSupportsNormalization()
    {
        $this->assertTrue($this->normalizer->supportsNormalization(new ConstraintViolationList()));
        $this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
    }

    public function testNormalize()
    {
        $list = new ConstraintViolationList([
            new ConstraintViolation('a', 'b', ['value' => 'foo'], 'c', 'd', 'e', null, 'f'),
            new ConstraintViolation('1', '2', [], '3', '4', '5', null, '6'),
        ]);

        $expected = [
            'type' => 'https://symfony.com/errors/validation',
            'title' => 'Validation Failed',
            'detail' => 'd: a 4: 1',
            'violations' => [
                    [
                        'propertyPath' => 'd',
                        

    public function __construct(iterable $violations = [])
    {
        foreach ($violations as $violation) {
            $this->add($violation);
        }
    }

    public static function createFromMessage(string $message): self
    {
        $self = new self();
        $self->add(new ConstraintViolation($message, '', [], null, '', null));

        return $self;
    }

    public function __toString(): string
    {
        $string = '';

        foreach ($this->violations as $violation) {
            $string .= $violation."\n";
        }

        
namespace Symfony\Component\Validator\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Tests\Fixtures\CustomArrayObject;
use Symfony\Component\Validator\Tests\Fixtures\ToString;

class ConstraintViolationTest extends TestCase
{
    public function testToStringHandlesArrays()
    {
        $violation = new ConstraintViolation(
            'Array',
            '{{ value }}',
            ['{{ value }}' => [1, 2, 3]],
            'Root',
            'property.path',
            null
        );

        $expected = <<<'EOF' Root.property.path: Array
try {
                    $payload = $this->$payloadMapper($request$type$argument);
                } catch (PartialDenormalizationException $e) {
                    $trans = $this->translator ? $this->translator->trans(...) : fn ($m$p) => strtr($m$p);
                    foreach ($e->getErrors() as $error) {
                        $parameters = ['{{ type }}' => implode('|', $error->getExpectedTypes())];
                        if ($error->canUseMessageForUser()) {
                            $parameters['hint'] = $error->getMessage();
                        }
                        $template = 'This value should be of type {{ type }}.';
                        $message = $trans($template$parameters, 'validators');
                        $violations->add(new ConstraintViolation($message$template$parameters, null, $error->getPath(), null));
                    }
                    $payload = $e->getData();
                }

                if (null !== $payload) {
                    $violations->addAll($this->validator->validate($payload, null, $argument->validationGroups ?? null));
                }

                if (\count($violations)) {
                    throw new HttpException($validationFailedCodeimplode("\n", array_map(static fn ($e) => $e->getMessage()iterator_to_array($violations)))new ValidationFailedException($payload$violations));
                }
            }
public function testStopsAtFirstConstraintWithViolations()
    {
        $constraints = [
            new Type('string'),
            new Regex(['pattern' => '[a-z]']),
            new NotEqualTo('Foo'),
        ];

        $value = 'Foo';

        $this->expectValidateValue(0, $value[$constraints[0]]);
        $this->expectFailingValueValidation(1, $value[$constraints[1]], null, new ConstraintViolation('regex error', null, [], null, '', null, null, 'regex'));

        $this->validator->validate($valuenew Sequentially($constraints));

        $this->assertCount(1, $this->context->getViolations());
    }

    public function testNestedConstraintsAreNotExecutedWhenGroupDoesNotMatch()
    {
        $validator = Validation::createValidator();

        $violations = $validator->validate(50, new Sequentially([
            
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(),
              reset($remaining_fields),
              $violation->getInvalidValue(),
              $violation->getPlural(),
              $violation->getCode(),
              $violation->getConstraint(),
              $violation->getCause()
            );
            
Home | Imprint | This part of the site doesn't use cookies.