ConstraintViolationException example



        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
    {
        $mailConfigs = [];
        $mailConfigs['receivers'] = [];
        $mailConfigs['message'] = '';

        

    private function validateOrderData(
        ParameterBag $data,
        SalesChannelContext $context,
        bool $hasVirtualGoods
    ): void {
        $definition = $this->getOrderCreateValidationDefinition(new DataBag($data->all())$context$hasVirtualGoods);
        $violations = $this->dataValidator->getViolations($data->all()$definition);

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

    private function getOrderCreateValidationDefinition(
        DataBag $data,
        SalesChannelContext $context,
        bool $hasVirtualGoods
    ): DataValidationDefinition {
        $validation = $this->orderValidationFactory->create($context);

        if ($hasVirtualGoods) {
            
$compareValue = $data[$equalityValidation->propertyPath] ?? null;
        if ($data[$field] === $compareValue) {
            return;
        }

        $message = str_replace('{{ compared_value }}', $compareValue ?? '', (string) $equalityValidation->message);

        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation($message$equalityValidation->message, [], '', $field$data[$field]));

        throw new ConstraintViolationException($violations$data);
    }

    private function deleteRecoveryForCustomer(CustomerRecoveryEntity $existingRecovery, Context $context): void
    {
        $recoveryData = [
            'id' => $existingRecovery->getId(),
        ];

        $this->customerRecoveryRepository->delete([$recoveryData]$context);
    }

    

        }

        $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 */
    private function checkReviewsActive(SalesChannelContext $context): void
    {
        $showReview = $this->config->get('core.listing.showReview', $context->getSalesChannel()->getId());

        if (!$showReview) {
            throw new ReviewNotActiveExeption();
        }
$compareValue = $data[$equalityValidation->propertyPath] ?? null;
        if ($data[$field] === $compareValue) {
            return;
        }

        $message = str_replace('{{ compared_value }}', $compareValue(string) $equalityValidation->message);

        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation($message$equalityValidation->message, [], '', $field$data[$field]));

        throw new ConstraintViolationException($violations$data);
    }
}
$context = Generator::createSalesChannelContext();
        $request = new Request();
        $dataBag = new RequestDataBag();
        $dataBag->set('address', new DataBag(['id' => Uuid::randomHex()]));

        $customer = new CustomerEntity();
        $customer->setId(Uuid::randomHex());

        $this->abstractUpsertAddressRoute
            ->expects(static::once())
            ->method('upsert')
            ->willThrowException(new ConstraintViolationException(new ConstraintViolationList()[]));

        $response = $this->controller->addressBook($request$dataBag$context$customer);
        static::assertEquals(Response::HTTP_OK, $response->getStatusCode());

        $renderParams = $this->controller->renderStorefrontParameters;

        static::assertArrayHasKey('messages', $renderParams);
        static::assertCount(0, $renderParams['messages']);
        static::assertArrayHasKey('page', $renderParams);
        static::assertArrayHasKey('formViolations', $renderParams);
        static::assertArrayHasKey('postedData', $renderParams);
    }
$compareValue = $data[$equalityValidation->propertyPath] ?? null;
        if ($data[$field] === $compareValue) {
            return;
        }

        $message = str_replace('{{ compared_value }}', $compareValue(string) $equalityValidation->message);

        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation($message$equalityValidation->message, [], '', $field$data[$field]));

        throw new ConstraintViolationException($violations$data);
    }
}


        $this->validator->expects(static::once())
            ->method('validate')
            ->willReturnCallback(function Darray $data, DataValidationDefinition $definition): void {
                $properties = $definition->getProperties();
                static::assertArrayHasKey('doubleOptInRegistration', $properties);
                static::assertContainsOnlyInstancesOf(IsTrue::class$properties['doubleOptInRegistration']);

                static::assertFalse($data['doubleOptInRegistration']);

                throw new ConstraintViolationException(new ConstraintViolationList()$data);
            });

        static::expectException(ConstraintViolationException::class);
        $this->route->confirm($this->mockRequestDataBag()$this->context);
    }

    public function testConfirmActivatedCustomer(): void
    {
        Feature::skipTestIfActive('v6.6.0.0', $this);

        $customer = $this->mockCustomer();
        

    }

    public function testSaveReviewViolation(): void
    {
        $ids = new IdsCollection();

        $this->systemConfigServiceMock->method('get')->with('core.listing.showReview')->willReturn(true);

        $requestBag = new RequestDataBag(['test' => 'test']);

        $violations = new ConstraintViolationException(new ConstraintViolationList()[]);

        $this->productReviewSaveRouteMock->method('save')->willThrowException($violations);

        $response = $this->controller->saveReview(
            $ids->get('productId'),
            new RequestDataBag(['test' => 'test']),
            $this->createMock(SalesChannelContext::class)
        );

        static::assertEquals(Response::HTTP_OK, $response->getStatusCode());
        static::assertEquals('frontend.product.reviews', $this->controller->forwardToRoute);
        
$violations->add(new ConstraintViolation(
            str_replace(array_keys($params)array_values($params)$message),
            $message,
            $params,
            null,
            null,
            $email,
            null,
            '79d30fe0-febf-421e-ac9b-1bfd5c9007f7'
        ));

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

    #[Route(path: '/api/_admin/sanitize-html', name: 'api.admin.sanitize-html', methods: ['POST'])]     public function sanitizeHtml(Request $request, Context $context): JsonResponse
    {
        if (!$request->request->has('html')) {
            throw RoutingException::missingRequestParameter('html');
        }

        $html = (string) $request->request->get('html');
        $field = (string) $request->request->get('field');

        
$compareValue = $data[$equalityValidation->propertyPath] ?? null;
        if ($data[$field] === $compareValue) {
            return;
        }

        $message = str_replace('{{ compared_value }}', $compareValue ?? '', (string) $equalityValidation->message);

        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation($message$equalityValidation->message, [], '', $field$data[$field]));

        throw new ConstraintViolationException($violations$data);
    }

    private function getCustomerByEmail(string $email, SalesChannelContext $context): CustomerEntity
    {
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('customer.active', 1));
        $criteria->addFilter(new EqualsFilter('customer.email', $email));
        $criteria->addFilter(new EqualsFilter('customer.guest', 0));

        $criteria->addFilter(new MultiFilter(MultiFilter::CONNECTION_OR, [
            new EqualsFilter('customer.boundSalesChannelId', null),
            
$this->expectException(RoutingException::class);
        $this->expectExceptionMessage('Parameter "languageId" is missing.');

        $controller->switchLanguage(new Request()$this->createMock(SalesChannelContext::class));
    }

    public function testSwitchLangNotFound(): void
    {
        $contextSwitchRoute = $this->createMock(ContextSwitchRoute::class);
        $contextSwitchRoute->expects(static::once())->method('switchContext')->willThrowException(
            new ConstraintViolationException(new ConstraintViolationList()[])
        );
        $controller = new ContextController(
            $contextSwitchRoute,
            $this->createMock(RequestStack::class),
            $this->createMock(RouterInterface::class)
        );

        $notExistingLang = Uuid::randomHex();

        $this->expectException(RoutingException::class);
        $this->expectExceptionMessage('The language "' . $notExistingLang . '" was not found');

        
$constraints = (new ConstraintBuilder())
            ->isNotBlank()
            ->isEmail()
            ->getConstraints();

        $violations = new ConstraintViolationList();
        foreach ($addresses as $address) {
            $violations->addAll($this->validator->validate($address$constraints));
        }

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

    /** * @param string[] $addresses * * @return string[] */
    private function formatMailAddresses(array $addresses): array
    {
        $formattedAddresses = [];
        
throw RoutingException::missingRequestParameter('formId');
        }

        if ($this->basicCaptcha->isValid($request[])) {
            $fakeSession = $request->get(BasicCaptcha::CAPTCHA_REQUEST_PARAMETER);
            $request->getSession()->set($formId . BasicCaptcha::BASIC_CAPTCHA_SESSION, $fakeSession);

            return new JsonResponse(['session' => $fakeSession]);
        }

        $violations = $this->basicCaptcha->getViolations();
        $formViolations = new ConstraintViolationException($violations[]);
        $response[] = [
            'type' => 'danger',
            'error' => 'invalid_captcha',
            'input' => $this->renderView('@Storefront/storefront/component/captcha/basicCaptchaFields.html.twig', [
                'formId' => $request->get('formId'),
                'formViolations' => $formViolations,
            ]),
        ];

        return new JsonResponse($response);
    }
}
return $violations;
    }

    public function validate(array $data, DataValidationDefinition $definition, string $path = ''): void
    {
        $violations = $this->getViolations($data$definition$path);
        if ($violations->count() === 0) {
            return;
        }

        throw new ConstraintViolationException($violations$data);
    }

    private function validateProperties(array $data, DataValidationDefinition $definition, string $path): ConstraintViolationList
    {
        $constraintViolations = new ConstraintViolationList();

        foreach ($definition->getProperties() as $propertyName => $constraints) {
            $value = $data[$propertyName] ?? null;
            $violations = $this->validator->validate($value$constraints);

            /** @var ConstraintViolation $violation */
            
Home | Imprint | This part of the site doesn't use cookies.