ConstraintViolation example

$violations = new ConstraintViolationList();
        $writeCommands = $event->getCommands();
        $lockedEntities = $this->containsLockedEntities($writeCommands);

        if (empty($lockedEntities)) {
            return;
        }

        $message = 'The %s entity is locked and can neither be modified nor deleted.';

        foreach ($lockedEntities as $entity => $_isLocked) {
            $violations->add(new ConstraintViolation(
                sprintf($message$entity),
                sprintf($message, '{{ entity }}'),
                ['{{ entity }}' => $entity],
                null,
                '/',
                null,
                null,
                self::VIOLATION_LOCKED
            ));
        }

        


        $message = 'This field is write-protected.';
        $allowedOrigins = '';
        if ($flag->getAllowedScopes()) {
            $message .= ' (Got: "%s" scope and "%s" is required)';
            $allowedOrigins = implode(' or ', $flag->getAllowedScopes());
        }

        $violationList = new ConstraintViolationList();
        $violationList->add(
            new ConstraintViolation(
                sprintf(
                    $message,
                    $parameters->getContext()->getContext()->getScope(),
                    $allowedOrigins
                ),
                $message,
                [
                    $parameters->getContext()->getContext()->getScope(),
                    $allowedOrigins,
                ],
                $data->getValue(),
                
/** * @param array<string, string> $parameters * @param array<mixed>|null $invalidValue */
    private function buildViolation(
        string $messageTemplate,
        array $parameters,
        ?string $propertyPath = null,
        ?array $invalidValue = null,
        ?string $code = null
    ): ConstraintViolationInterface {
        return new ConstraintViolation(
            str_replace(array_keys($parameters)array_values($parameters)$messageTemplate),
            $messageTemplate,
            $parameters,
            null,
            $propertyPath,
            $invalidValue,
            null,
            $code
        );
    }
}
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);
    }
}
public function getStatusCode(): int
    {
        return Response::HTTP_BAD_REQUEST;
    }

    private function mapErrorCodes(ConstraintViolationList $violations): void
    {
        /** @var ConstraintViolation $violation */
        foreach ($violations as $key => $violation) {
            if ($constraint = $violation->getConstraint()) {
                $violations->remove($key);
                $violations->add(new ConstraintViolation(
                    $violation->getMessage(),
                    $violation->getMessageTemplate(),
                    $violation->getParameters(),
                    $violation->getRoot(),
                    $violation->getPropertyPath(),
                    $violation->getInvalidValue(),
                    $violation->getPlural(),
                    'VIOLATION::' . $constraint->getErrorName($violation->getCode() ?? ''),
                    $constraint
                ));
            }
        }


    /** * @param array<int|string> $parameters */
    private function buildViolation(
        string $messageTemplate,
        array $parameters,
        ?string $propertyPath = null,
        ?string $code = null
    ): ConstraintViolationInterface {
        return new ConstraintViolation(
            str_replace(array_keys($parameters)array_values($parameters)$messageTemplate),
            $messageTemplate,
            $parameters,
            null,
            $propertyPath,
            null,
            null,
            $code
        );
    }

    
$expected = CartException::customerNotLoggedIn()::class;

        static::expectException($expected);
        static::expectExceptionMessage('Customer is not logged in');

        $checkoutConfirmPageLoader->load(new Request()$context);
    }

    public function testViolationsAreAddedAsCartErrorsWithSameAddress(): void
    {
        $violations = new ConstraintViolationList([
            new ConstraintViolation(
                'Test error',
                null,
                [],
                'root',
                null,
                'invalidValue'
            ),
        ]);

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

    private function buildViolation(string $message, mixed $invalidValue, string $propertyPath, string $code, int $index): ConstraintViolationInterface
    {
        $formattedPath = "/{$index}/{$propertyPath}";

        return new ConstraintViolation(
            $message,
            '',
            [
                'value' => $invalidValue,
            ],
            $invalidValue,
            $formattedPath,
            $invalidValue,
            null,
            $code
        );
    }
#[\Shopware\Core\Framework\Log\Package('core')] class MissingTranslationLanguageException extends WriteConstraintViolationException
{
    final public const VIOLATION_MISSING_TRANSLATION_LANGUAGE = 'MISSING-TRANSLATION-LANGUAGE';

    public function __construct(
        string $path,
        int $translationIndex
    ) {
        $template = 'Translation requires a language id.';
        $constraintViolationList = new ConstraintViolationList([
            new ConstraintViolation(
                $template,
                $template,
                [],
                null,
                "/{$translationIndex}",
                null,
                null,
                self::VIOLATION_MISSING_TRANSLATION_LANGUAGE
            ),
        ]);
        parent::__construct($constraintViolationList$path);
    }
return parent::encode($field$existence$data$parameters);
        }

        // In every other case force the user to use a state-transition         $messageTemplate = 'Changing the state-machine-state of this entity is not allowed for scope {{ scope }}. '
            . 'Either change the state-machine-state via a state-transition or use a different scope.';
        $messageParameters = [
            '{{ scope }}' => $scope,
        ];

        throw new WriteConstraintViolationException(new ConstraintViolationList([
            new ConstraintViolation(
                str_replace(array_keys($messageParameters)array_values($messageParameters)$messageTemplate),
                $messageTemplate,
                $messageParameters,
                null,
                '/' . $data->getKey(),
                $data->getValue()
            ),
        ])$parameters->getPath());
    }
}
public function testEncodeMethodWithIncorrectDataWillThrowException(): void
    {
        $data = new KeyValuePair('key', new CronIntervalField('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 === CronExpression::class);
            }))
            ->willReturn(new ConstraintViolationList([new ConstraintViolation('error', 'error', [], '', 'key', 'value')]));

        static::expectException(WriteConstraintViolationException::class);

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

    
#[\Shopware\Core\Framework\Log\Package('core')] class MissingSystemTranslationException extends WriteConstraintViolationException
{
    final public const VIOLATION_MISSING_SYSTEM_TRANSLATION = 'MISSING-SYSTEM-TRANSLATION';

    public function __construct(string $path = '')
    {
        $template = 'Translation required for system language {{ systemLanguage }}';
        $parameters = ['{{ systemLanguage }}' => Defaults::LANGUAGE_SYSTEM];
        $constraintViolationList = new ConstraintViolationList([
            new ConstraintViolation(
                str_replace(array_keys($parameters)array_values($parameters)$template),
                $template,
                $parameters,
                null,
                '',
                Defaults::LANGUAGE_SYSTEM,
                null,
                self::VIOLATION_MISSING_SYSTEM_TRANSLATION
            ),
        ]);
        parent::__construct($constraintViolationList$path);
    }
foreach ($this->data as $assertion) {
            $fieldName = $assertion['name'];
            $value = $assertion['value'];

            /** @var Constraint $constraint */
            foreach ($assertion['constraints'] as $constraint) {
                $violations = $this->validator->validate($value$constraint);

                /** @var ConstraintViolation $violation */
                foreach ($violations as $violation) {
                    $violationList->add(
                        new ConstraintViolation(
                            $violation->getMessage(),
                            $violation->getMessageTemplate(),
                            $violation->getParameters(),
                            $violation->getRoot(),
                            $fieldName,
                            $violation->getInvalidValue(),
                            $violation->getPlural(),
                            $violation->getCode(),
                            $violation->getConstraint(),
                            $violation->getCause()
                        )
                    );


            $pk = $command->getPrimaryKey();
            $id = mb_strtolower((string) Uuid::fromBytesToHex($pk['id']));
            if ($id !== Defaults::CURRENCY) {
                continue;
            }

            $msgTpl = 'The default currency {{ id }} cannot be deleted.';
            $parameters = ['{{ id }}' => $id];
            $msg = sprintf('The default currency %s cannot be deleted.', $id);
            $violation = new ConstraintViolation(
                $msg,
                $msgTpl,
                $parameters,
                null,
                '/' . $id,
                $id,
                null,
                self::VIOLATION_DELETE_DEFAULT_CURRENCY
            );

            $violations->add($violation);
        }
public function getName(): string
    {
        return self::CAPTCHA_NAME;
    }

    /** * {@inheritdoc} */
    public function getViolations(): ConstraintViolationList
    {
        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            '',
            '',
            [],
            '',
            '/' . self::CAPTCHA_REQUEST_PARAMETER,
            '',
            null,
            self::INVALID_CAPTCHA_CODE
        ));

        return $violations;
    }
Home | Imprint | This part of the site doesn't use cookies.