ConstraintViolationList example

'detail' => 'Invalid value',
            'violations' => [
                [
                    'propertyPath' => '',
                    'title' => 'Invalid value',
                    'template' => '',
                    'parameters' => [],
                ],
            ],
        ];

        $exception = new ValidationFailedException('Validation Failed', new ConstraintViolationList([new ConstraintViolation('Invalid value', '', [], '', null, null)]));
        $exception = new HttpException(422, 'Validation Failed', $exception);
        $this->assertSame($expected$this->normalizer->normalize(FlattenException::createFromThrowable($exception), null, ['exception' => $exception]));
    }
}
$validationFailedCode = Response::HTTP_UNPROCESSABLE_ENTITY;
            } else {
                continue;
            }
            $request = $event->getRequest();

            if (!$type = $argument->metadata->getType()) {
                throw new \LogicException(sprintf('Could not resolve the "$%s" controller argument: argument should be typed.', $argument->metadata->getName()));
            }

            if ($this->validator) {
                $violations = new ConstraintViolationList();
                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');
                        
// Assert that the returned data type is an instance of EntityAdapter.     $this->assertInstanceOf($expected$entity->getTypedData());
  }

  /** * @covers ::validate */
  public function testValidate() {
    $validator = $this->createMock(ValidatorInterface::class);
    /** @var \Symfony\Component\Validator\ConstraintViolationList $empty_violation_list */
    $empty_violation_list = new ConstraintViolationList();
    $non_empty_violation_list = clone $empty_violation_list;
    $violation = $this->createMock('\Symfony\Component\Validator\ConstraintViolationInterface');
    $non_empty_violation_list->add($violation);
    $validator->expects($this->exactly(2))
      ->method('validate')
      ->with($this->entity->getTypedData())
      ->willReturnOnConsecutiveCalls($empty_violation_list$non_empty_violation_list);
    $this->typedDataManager->expects($this->exactly(2))
      ->method('getValidator')
      ->willReturn($validator);
    $this->assertCount(0, $this->entity->validate());
    

    elseif (!empty($definition['context_definitions'][$name])) {
      return $definition['context_definitions'][$name];
    }
    throw new ContextException(sprintf("The %s context is not a valid context.", $name));
  }

  /** * {@inheritdoc} */
  public function validateContexts() {
    $violations = new ConstraintViolationList();

    // @todo Implement the Symfony Validator component to let the validator     // traverse and set property paths accordingly.     // See https://www.drupal.org/project/drupal/issues/3153847.     foreach ($this->getContexts() as $context) {
      $violations->addAll($context->validate());
    }
    return $violations;
  }

  /** * {@inheritdoc} */
use Symfony\Component\Validator\Validator\ValidatorInterface;

class ValidatorDataCollectorTest extends TestCase
{
    public function testCollectsValidatorCalls()
    {
        $originalValidator = $this->createMock(ValidatorInterface::class);
        $validator = new TraceableValidator($originalValidator);

        $collector = new ValidatorDataCollector($validator);

        $violations = new ConstraintViolationList([
            $this->createMock(ConstraintViolation::class),
            $this->createMock(ConstraintViolation::class),
        ]);
        $originalValidator->method('validate')->willReturn($violations);

        $validator->validate(new \stdClass());

        $collector->lateCollect();

        $calls = $collector->getCalls();

        
if (!interface_exists(ValidatorInterface::class)) {
            throw new \Exception('In order to use the "ValidatorExtensionTrait", the symfony/validator component must be installed.');
        }

        if (!$this instanceof TypeTestCase) {
            throw new \Exception(sprintf('The trait "ValidatorExtensionTrait" can only be added to a class that extends "%s".', TypeTestCase::class));
        }

        $this->validator = $this->createMock(ValidatorInterface::class);
        $metadata = $this->getMockBuilder(ClassMetadata::class)->setConstructorArgs([''])->onlyMethods(['addPropertyConstraint'])->getMock();
        $this->validator->expects($this->any())->method('getMetadataFor')->will($this->returnValue($metadata));
        $this->validator->expects($this->any())->method('validate')->will($this->returnValue(new ConstraintViolationList()));

        return new ValidatorExtension($this->validator, false);
    }
}
class ConstraintViolationListNormalizerTest extends TestCase
{
    private ConstraintViolationListNormalizer $normalizer;

    protected function setUp(): void
    {
        $this->normalizer = new ConstraintViolationListNormalizer();
    }

    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 = [
            

  public function __construct(ValidatorInterface $validator$root, TranslatorInterface $translator$translationDomain = NULL) {
    $this->validator = $validator;
    $this->root = $root;
    $this->translator = $translator;
    $this->translationDomain = $translationDomain;
    $this->violations = new ConstraintViolationList();
  }

  /** * {@inheritdoc} */
  public function setNode($value$object, MetadataInterface $metadata = NULL, $propertyPath): void {
    $this->value = $value;
    $this->data = $object;
    $this->metadata = $metadata;
    $this->propertyPath = (string) $propertyPath;
  }

  
$this->defaultTimezone = null;
        }
    }

    protected function createContext()
    {
        $translator = $this->createMock(TranslatorInterface::class);
        $translator->expects($this->any())->method('trans')->willReturnArgument(0);
        $validator = $this->createMock(ValidatorInterface::class);
        $validator->expects($this->any())
            ->method('validate')
            ->willReturnCallback(fn () => $this->expectedViolations[$this->call++] ?? new ConstraintViolationList());

        $context = new ExecutionContext($validator$this->root, $translator);
        $context->setGroup($this->group);
        $context->setNode($this->value, $this->object, $this->metadata, $this->propertyPath);
        $context->setConstraint($this->constraint);

        $contextualValidatorMockBuilder = $this->getMockBuilder(AssertingContextualValidator::class)
            ->setConstructorArgs([$context]);
        $contextualValidatorMethods = [
            'atPath',
            'validate',
            
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;

class ConstraintViolationListTest extends TestCase
{
    protected ConstraintViolationList $list;

    protected function setUp(): void
    {
        $this->list = new ConstraintViolationList();
    }

    public function testInit()
    {
        $this->assertCount(0, $this->list);
    }

    public function testInitWithViolations()
    {
        $violation = $this->getViolation('Error');
        $this->list = new ConstraintViolationList([$violation]);

        

  protected function movePropertyPathViolationsRelativeToField($field_name, ConstraintViolationListInterface $violations) {
    $new_violations = new ConstraintViolationList();
    foreach ($violations as $violation) {
      // All the logic below is necessary to change the property path of the       // violations to be relative to the item list, so like title.0.value gets       // changed to 0.value. Sadly constraints in Symfony don't have setters so       // we have to create new objects.       /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
      // Create a new violation object with just a different property path.       $violation_path = $violation->getPropertyPath();
      $path_parts = explode('.', $violation_path);
      if ($path_parts[0] === $field_name) {
        unset($path_parts[0]);
      }
public function testValidationNotPassed()
    {
        $content = '{"price": 50, "title": ["not a string"]}';
        $payload = new RequestPayload(50);
        $serializer = new Serializer([new ObjectNormalizer()]['json' => new JsonEncoder()]);

        $validator = $this->createMock(ValidatorInterface::class);
        $validator->expects($this->once())
            ->method('validate')
            ->with($payload)
            ->willReturn(new ConstraintViolationList([new ConstraintViolation('Test', null, [], '', null, '')]));

        $resolver = new RequestPayloadValueResolver($serializer$validator);

        $argument = new ArgumentMetadata('invalid', RequestPayload::class, false, false, null, false, [
            MapRequestPayload::class => new MapRequestPayload(),
        ]);
        $request = Request::create('/', 'POST', server: ['CONTENT_TYPE' => 'application/json'], content: $content);

        $kernel = $this->createMock(HttpKernelInterface::class);
        $arguments = $resolver->resolve($request$argument);
        $event = new ControllerArgumentsEvent($kernelfunction D) {}$arguments$request, HttpKernelInterface::MAIN_REQUEST);

        
null,
            [
                'validation_groups' => 'group',
            ]
        );
        $builder->add('firstName', FormTypeTest::TESTED_TYPE);
        $form = $builder->getForm();

        $this->validator->expects($this->once())
            ->method('validate')
            ->with($this->equalTo($form))
            ->willReturn(new ConstraintViolationList());

        // specific data is irrelevant         $form->submit([]);
    }

    public function testValidConstraint()
    {
        $form = $this->createForm(['constraints' => $valid = new Valid()]);

        $this->assertSame([$valid]$form->getConfig()->getOption('constraints'));
    }

    
public function getMetadataFor($value): MetadataInterface
    {
    }

    public function hasMetadataFor($value): bool
    {
    }

    public function validate($value$constraints = null, $groups = null): ConstraintViolationListInterface
    {
        return new ConstraintViolationList([$this->violation]);
    }

    public function validateProperty($object$propertyName$groups = null): ConstraintViolationListInterface
    {
    }

    public function validatePropertyValue($objectOrClass$propertyName$value$groups = null): ConstraintViolationListInterface
    {
    }

    public function startContext(): ContextualValidatorInterface
    {
private \SplObjectStorage $cachedObjectsRefs;

    /** * @internal Called by {@link ExecutionContextFactory}. Should not be used in user code. */
    public function __construct(ValidatorInterface $validator, mixed $root, TranslatorInterface $translator, string $translationDomain = null)
    {
        $this->validator = $validator;
        $this->root = $root;
        $this->translator = $translator;
        $this->translationDomain = $translationDomain;
        $this->violations = new ConstraintViolationList();
        $this->cachedObjectsRefs = new \SplObjectStorage();
    }

    public function setNode(mixed $value, ?object $object, MetadataInterface $metadata = null, string $propertyPath): void
    {
        $this->value = $value;
        $this->object = $object;
        $this->metadata = $metadata;
        $this->propertyPath = $propertyPath;
    }

    
Home | Imprint | This part of the site doesn't use cookies.