ConstraintViolationList example

private readonly array $inputData
    ) {
        $this->mapErrorCodes($violations);

        $this->violations = $violations;

        parent::__construct('Caught {{ count }} violation errors.', ['count' => $violations->count()]);
    }

    public function getRootViolations(): ConstraintViolationList
    {
        $violations = new ConstraintViolationList();
        foreach ($this->violations as $violation) {
            if ($violation->getPropertyPath() === '') {
                $violations->add($violation);
            }
        }

        return $violations;
    }

    public function getViolations(?string $propertyPath = null): ConstraintViolationList
    {
        

    }

    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);
        
return [
            PreWriteValidationEvent::class => 'preValidate',
        ];
    }

    public function preValidate(PreWriteValidationEvent $event): void
    {
        if ($event->getContext()->getVersionId() !== Defaults::LIVE_VERSION) {
            return;
        }

        $violations = new ConstraintViolationList();
        $violations->addAll($this->getDeletedSystemTranslationViolations($event->getCommands()));

        if ($violations->count()) {
            $event->getExceptions()->add(new WriteConstraintViolationException($violations));
        }
    }

    /** * @param list<WriteCommand> $writeCommands */
    private function getDeletedSystemTranslationViolations(array $writeCommands): ConstraintViolationList
    {


    public function checkWrite(PreWriteValidationEvent $event): void
    {
        $context = $event->getContext();

        if ($context->getSource() instanceof SystemSource || $context->getScope() === Context::SYSTEM_SCOPE) {
            return;
        }

        $integrationId = $this->getIntegrationId($context);
        $violationList = new ConstraintViolationList();

        foreach ($event->getCommands() as $command) {
            if (
                !($command->getDefinition() instanceof CustomFieldSetDefinition)
                || $command instanceof InsertCommand
            ) {
                continue;
            }

            $appIntegrationId = $this->fetchIntegrationIdOfAssociatedApp($command);
            if (!$appIntegrationId) {
                
/** * This function validates our incoming delta-values for promotions * and its aggregation. It does only check for business relevant rules and logic. * All primitive "required" constraints are done inside the definition of the entity. * * @throws WriteConstraintViolationException */
    public function preValidate(PreWriteValidationEvent $event): void
    {
        $this->collect($event->getCommands());

        $violationList = new ConstraintViolationList();
        $writeCommands = $event->getCommands();

        foreach ($writeCommands as $index => $command) {
            if (!$command instanceof InsertCommand && !$command instanceof UpdateCommand) {
                continue;
            }

            switch ($command->getDefinition()::class) {
                case PromotionDefinition::class:
                    /** @var string $promotionId */
                    $promotionId = $command->getPrimaryKey()['id'];

                    
$customer->setId(Uuid::randomHex());
        $customer->setFirstName('Max');
        $customer->setLastName('Mustermann');
        $customer->setEmail('foo@example.com');
        $salesChannel = new SalesChannelEntity();
        $salesChannel->setId('test');

        $salesChannelContext->expects(static::once())->method('getCustomer')->willReturn($customer);
        $salesChannelContext->expects(static::exactly(4))->method('getSalesChannel')->willReturn($salesChannel);
        $salesChannelContext->expects(static::exactly(4))->method('getContext')->willReturn($context);

        $this->validator->expects(static::once())->method('getViolations')->willReturn(new ConstraintViolationList());

        $this->repository
            ->expects(static::once())
            ->method('upsert')
            ->with([
                [
                    'productId' => $productId,
                    'customerId' => $customer->getId(),
                    'salesChannelId' => $salesChannel->getId(),
                    'languageId' => $context->getLanguageId(),
                    'externalUser' => $customer->getFirstName(),
                    
$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');

        


    public static function getSubscribedEvents(): array
    {
        return [
            PostWriteValidationEvent::class => 'postValidate',
        ];
    }

    public function postValidate(PostWriteValidationEvent $event): void
    {
        $violationList = new ConstraintViolationList();
        foreach ($event->getCommands() as $command) {
            if (!($command instanceof InsertCommand || $command instanceof UpdateCommand)) {
                continue;
            }

            if ($command->getDefinition()->getClass() !== CategoryDefinition::class) {
                continue;
            }

            if (!isset($command->getPayload()['type'])) {
                continue;
            }
if (!$equalityValidation instanceof EqualTo) {
            return;
        }

        $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));

        
$this->validateUpdateCommands($updateQueue$writeException$event->getContext());
        }
    }

    private function validateCondition(
        ?RuleConditionEntity $condition,
        WriteCommand $command,
        WriteException $writeException,
        Context $context
    ): void {
        $payload = $command->getPayload();
        $violationList = new ConstraintViolationList();

        $type = $this->getConditionType($condition$payload);
        if ($type === null) {
            return;
        }

        try {
            $ruleInstance = $this->ruleConditionRegistry->getRuleInstance($type);
        } catch (InvalidConditionException) {
            $violation = $this->buildViolation(
                'This {{ value }} is not a valid condition type.',
                [
public function testEncodeMethodWithIncorrectDataTypeObjectWillThrowInvalidIntervalFieldDataTypeException(): void
    {
        $data = new KeyValuePair('key', new DateIntervalField('name', 'name'), false);

        $this->validator
            ->expects(static::exactly(2))
            ->method('validate')
            ->with($data->getValue()static::callback(static function D$constraint): bool {
                return $constraint instanceof NotNull || ($constraint instanceof Type && $constraint->type === \DateInterval::class);
            }))
            ->willReturn(new ConstraintViolationList([new ConstraintViolation('error', 'error', [], '', 'key', 'value')]));

        static::expectException(WriteConstraintViolationException::class);

        $this->dateIntervalFieldSerializer->encode(
            (new DateIntervalField('name', 'name'))->setFlags(new Required()),
            $this->createStub(EntityExistence::class),
            $data,
            $this->createMock(WriteParameterBag::class)
        )->current();
    }

    
public function preValidate(PreWriteValidationEvent $event): void
    {
        $allowTypes = [
            ShippingMethodEntity::TAX_TYPE_FIXED,
            ShippingMethodEntity::TAX_TYPE_AUTO,
            ShippingMethodEntity::TAX_TYPE_HIGHEST,
        ];

        $writeCommands = $event->getCommands();

        foreach ($writeCommands as $command) {
            $violations = new ConstraintViolationList();

            if (!$command instanceof InsertCommand && !$command instanceof UpdateCommand) {
                continue;
            }

            if ($command->getDefinition()->getClass() !== ShippingMethodDefinition::class) {
                continue;
            }

            $shippingMethod = $this->findShippingMethod($command->getPrimaryKey()['id']);

            
if (!$equalityValidation instanceof EqualTo) {
            return;
        }

        $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);
    }
}
return $constraints;
    }

    private function ensureDefaultPrice(WriteParameterBag $parameters, array $prices): void
    {
        foreach ($prices as $price) {
            if ($price['currencyId'] === Defaults::CURRENCY) {
                return;
            }
        }

        $violationList = new ConstraintViolationList();
        $violationList->add(
            new ConstraintViolation(
                'No price for default currency defined',
                'No price for default currency defined',
                [],
                '',
                '/price',
                $prices
            )
        );

        


    public function testOrderConstraintViolation(): void
    {
        $request = new Request();
        $request->setSession($this->createMock(Session::class));

        $context = $this->createMock(SalesChannelContext::class);
        $context->method('getCustomer')->willReturn(new CustomerEntity());

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

        $response = $this->controller->order(new RequestDataBag()$context$request);

        static::assertEquals(new Response('forward to frontend.checkout.confirm.page')$response);
    }

    public function testOrderCartException(): void
    {
        $request = new Request();
        $request->setSession($this->createMock(Session::class));

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