getViolations example

/** @var WriteConstraintViolationException|null $exception */
        $exception = null;

        try {
            $this->serializer->encode($this->field, $this->existence, $kvPair$this->parameters)->current();
        } catch (\Throwable $e) {
            $exception = $e;
        }

        static::assertInstanceOf(WriteConstraintViolationException::class$exception, 'This value should not be blank.');
        static::assertEquals('/email', $exception->getViolations()->get(0)->getPropertyPath());
    }
}
/** * {@inheritdoc} */
  protected function buildErrorObjects(HttpException $exception) {
    /** @var \Drupal\jsonapi\Exception\UnprocessableHttpEntityException $exception */
    $errors = parent::buildErrorObjects($exception);
    $error = $errors[0];
    unset($error['links']);

    $errors = [];
    $violations = $exception->getViolations();
    $entity_violations = $violations->getEntityViolations();
    foreach ($entity_violations as $violation) {
      /** @var \Symfony\Component\Validator\ConstraintViolation $violation */
      $error['detail'] = 'Entity is not valid: '
        . $violation->getMessage();
      $error['source']['pointer'] = '/data';
      $errors[] = $error;
    }

    $entity = $violations->getEntity();
    foreach ($violations->getFieldNames() as $field_name) {
      

        }

        $this->context->setNode($previousValue$previousObject$previousMetadata$previousPath);
        $this->context->setGroup($previousGroup);

        return $this;
    }

    public function getViolations(): ConstraintViolationListInterface
    {
        return $this->context->getViolations();
    }

    /** * Normalizes the given group or list of groups to an array. * * @param string|GroupSequence|array<string|GroupSequence> $groups The groups to normalize * * @return array<string|GroupSequence> */
    protected function normalizeGroups(string|GroupSequence|array $groups): array
    {
        
$validation = new DataValidationDefinition('customer.create');

        $validation
            ->add('vatIds', $constraint);

        $validator = $this->getContainer()->get(DataValidator::class);

        try {
            $validator->validate(['vatIds' => $vatIds]$validation);
        } catch (\Throwable $exception) {
            static::assertInstanceOf(ConstraintViolationException::class$exception);
            $violations = $exception->getViolations();
            $violation = $violations->get(1);

            static::assertNotEmpty($violation);
            static::assertEquals($constraint->message, $violation->getMessageTemplate());
        }
    }
}

    public function validate(mixed $value, Constraint $constraint)
    {
        if (!$constraint instanceof Sequentially) {
            throw new UnexpectedTypeException($constraint, Sequentially::class);
        }

        $context = $this->context;

        $validator = $context->getValidator()->inContext($context);

        $originalCount = $validator->getViolations()->count();

        foreach ($constraint->constraints as $c) {
            if ($originalCount !== $validator->validate($value$c)->getViolations()->count()) {
                break;
            }
        }
    }
}


    private function validateConsistence(string $basePath, array $fieldValidations, array $payload): ConstraintViolationList
    {
        $list = new ConstraintViolationList();
        foreach ($fieldValidations as $fieldName => $validations) {
            $currentPath = sprintf('%s/%s', $basePath$fieldName);
            $list->addAll(
                $this->validator->startContext()
                    ->atPath($currentPath)
                    ->validate($payload[$fieldName] ?? null, $validations)
                    ->getViolations()
            );
        }

        foreach ($payload as $fieldName => $_value) {
            $currentPath = sprintf('%s/%s', $basePath$fieldName);

            if (!\array_key_exists($fieldName$fieldValidations)) {
                $list->add(
                    $this->buildViolation(
                        'The property "{{ fieldName }}" is not allowed.',
                        ['{{ fieldName }}' => $fieldName],
                        
public function validate(mixed $value, Constraint $constraint)
    {
        if (!$constraint instanceof AtLeastOneOf) {
            throw new UnexpectedTypeException($constraint, AtLeastOneOf::class);
        }

        $validator = $this->context->getValidator();

        // Build a first violation to have the base message of the constraint translated         $baseMessageContext = clone $this->context;
        $baseMessageContext->buildViolation($constraint->message)->addViolation();
        $baseViolations = $baseMessageContext->getViolations();
        $messages = [(string) $baseViolations->get(\count($baseViolations) - 1)->getMessage()];

        foreach ($constraint->constraints as $key => $item) {
            if (!\in_array($this->context->getGroup()$item->groups, true)) {
                continue;
            }

            $executionContext = clone $this->context;
            $executionContext->setNode($value$this->context->getObject()$this->context->getMetadata()$this->context->getPropertyPath());
            $violations = $validator->inContext($executionContext)->validate($value$item$this->context->getGroup())->getViolations();

            
$result = new ContactFormRouteResponseStruct();
        $result->assign([
            'individualSuccessMessage' => $mailConfigs['message'] ?? '',
        ]);

        return new ContactFormRouteResponse($result);
    }

    private function validateContactForm(DataBag $data, SalesChannelContext $context): void
    {
        $definition = $this->contactFormValidationFactory->create($context);
        $violations = $this->validator->getViolations($data->all()$definition);

        if ($violations->count() > 0) {
            throw new ConstraintViolationException($violations$data->all());
        }
    }

    /** * @return array<string, string|array<int, string>> */
    private function getSlotConfig(string $slotId, string $navigationId, SalesChannelContext $context, ?string $entityName = null): array
    {
        
$criteria->addFilter(new EqualsFilter('productId', $data->get('productId')));

            $definition->add('customerId', new EntityNotExists([
                'entity' => 'product_review',
                'context' => $context,
                'criteria' => $criteria,
            ]));
        }

        $this->validator->validate($data->all()$definition);

        $violations = $this->validator->getViolations($data->all()$definition);

        if (!$violations->count()) {
            return;
        }

        throw new ConstraintViolationException($violations$data->all());
    }

    /** * @throws ReviewNotActiveExeption */
    
if ($type === 'writeException') {
            $this->expectException(WriteConstraintViolationException::class);

            try {
                $serializer->encode(
                    $this->getStringField($name$flags),
                    EntityExistence::createEmpty(),
                    $data,
                    $this->getWriteParameterBagMock()
                )->current();
            } catch (WriteConstraintViolationException $e) {
                static::assertSame('/' . $name$e->getViolations()->get(0)->getPropertyPath());
                /* Unexpected language has to be fixed NEXT-9419 */
                // static::assertSame($expected, $e->getViolations()->get(0)->getMessage());
                throw $e;
            }
        }

        if ($type === 'assertion') {
            static::assertSame(
                $expected,
                $serializer->encode(
                    
'template' => $template,
                            'parameters' => [
                                '{{ type }}' => implode('|', $e->getExpectedTypes() ?? ['?']),
                            ],
                        ] + ($debug || $e->canUseMessageForUser() ? ['hint' => $e->getMessage()] : []),
                        $exception->getErrors()
                    ),
                ];
                $data['detail'] = implode("\n", array_map(fn ($e) => $e['propertyPath'].': '.$e['title']$data['violations']));
            } elseif ($exception instanceof ValidationFailedException
                && $this->serializer instanceof NormalizerInterface
                && $this->serializer->supportsNormalization($exception->getViolations()$format$context)
            ) {
                $data = $this->serializer->normalize($exception->getViolations()$format$context);
            }
        }

        $data = [
            self::TYPE => $data[self::TYPE] ?? $context[self::TYPE] ?? 'https://tools.ietf.org/html/rfc2616#section-10',
            self::TITLE => $data[self::TITLE] ?? $context[self::TITLE] ?? 'An error occurred',
            self::STATUS => $context[self::STATUS] ?? $object->getStatusCode(),
            'detail' => $data['detail'] ?? ($debug ? $object->getMessage() : $object->getStatusText()),
        ] + $data;
        
unset($paymentMethod[0]['name']);

        try {
            $this->paymentRepository->create($paymentMethod$defaultContext);

            static::fail('The name should always be required!');
        } catch (WriteException $e) {
            /** @var WriteConstraintViolationException $constraintViolation */
            $constraintViolation = $e->getExceptions()[0];
            static::assertInstanceOf(WriteConstraintViolationException::class$constraintViolation);
            static::assertEquals('/name', $constraintViolation->getViolations()->get(0)->getPropertyPath());
        }
    }

    /** * @return array<int, array<string, mixed>> */
    private function createPaymentMethodDummyArray(): array
    {
        return [
            [
                'id' => $this->paymentMethodId,
                
'',
                new WriteCommandQueue()
            );

            $x = $handler->encode($field$existence$kvPair$parameters);
            $array = iterator_to_array($x);
        } catch (WriteConstraintViolationException $exception) {
        }

        static::assertIsNotArray($array);
        static::assertInstanceOf(WriteConstraintViolationException::class$exception);
        static::assertNotNull($exception->getViolations()->findByCodes(NotBlank::IS_BLANK_ERROR));
    }

    public function testValueIsRequiredOnUpdate(): void
    {
        $field = new PasswordField('password', 'password');
        $field->addFlags(new ApiAware()new Required());

        $existence = new EntityExistence($this->getContainer()->get(UserDefinition::class)->getEntityName()[], true, false, false, []);
        $kvPair = new KeyValuePair('password', null, true);

        $exception = null;
        
$newShippingAddress->setLastName('');
        $customer->setActiveShippingAddress($newShippingAddress);

        $cartErrors = $this->getPageLoader()->load($request$context)->getCart()->getErrors();
        static::assertCount(2, $cartErrors);
        $errors = $cartErrors->getElements();
        static::assertArrayHasKey('billing-address-invalid', $errors);
        static::assertArrayHasKey('shipping-address-invalid', $errors);

        /** @var AddressValidationError $billingAddressViolation */
        $billingAddressViolation = $errors['billing-address-invalid'];
        $violation = $billingAddressViolation->getViolations()->get(0);
        static::assertSame('/firstName', $violation->getPropertyPath());

        /** @var AddressValidationError $shippingAddressViolation */
        $shippingAddressViolation = $errors['shipping-address-invalid'];
        $violation = $shippingAddressViolation->getViolations()->get(0);
        static::assertSame('/lastName', $violation->getPropertyPath());
    }

    protected function getPageLoader(): CheckoutConfirmPageLoader
    {
        return $this->getContainer()->get(CheckoutConfirmPageLoader::class);
    }
$this->expectFailingValueValidation(
            0,
            7,
            $constraints,
            null,
            new ConstraintViolation('error_range', '', [], '', '', 7, null, 'range')
        );

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

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

    /** * @dataProvider provideCompileIsValid */
    public function testCompileIsValid(string $expression, array $names, string $expected)
    {
        $expressionLanguage = new ExpressionLanguage();
        $expressionLanguage->registerProvider(new ExpressionLanguageProvider());

        $result = $expressionLanguage->compile($expression$names);

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