trans example


    public function testRenderStorefront(string $view, array $parameters = []): Response
    {
        return $this->renderStorefront($view$parameters);
    }

    /** * @param array<string, mixed> $parameters */
    public function testTrans(string $snippet, array $parameters = []): string
    {
        return $this->trans($snippet$parameters);
    }

    public function testCreateActionResponse(Request $request): Response
    {
        return $this->createActionResponse($request);
    }

    /** * @param array<string, mixed> $attributes * @param array<string, mixed> $routeParameters */
    
$this->handleChangeableAddresses($viewData$dataBag$context$customer);
            $this->handleAddressCreation($viewData$dataBag$context$customer);
            $this->handleAddressSelection($viewData$dataBag$context$customer);
            $this->handleCustomerVatIds($dataBag$context$customer);
        } catch (ConstraintViolationException $formViolations) {
            $params['formViolations'] = $formViolations;
            $params['postedData'] = $dataBag->get('address');
        } catch (\Exception) {
            $viewData->setSuccess(false);
            $viewData->setMessages([
                'type' => self::DANGER,
                'text' => $this->trans('error.message-default'),
            ]);
        }

        if ($request->get('redirectTo') || $request->get('forwardTo')) {
            return $this->createActionResponse($request);
        }
        $params = array_merge($params$viewData->getVars());

        $response = $this->renderStorefront(
            '@Storefront/storefront/component/address/address-editor-modal.html.twig',
            $params
        );
'passwordFormViolation' => $request->get('passwordFormViolation'),
            'emailFormViolation' => $request->get('emailFormViolation'),
        ]);
    }

    #[Route(path: '/account/profile', name: 'frontend.account.profile.save', defaults: ['_loginRequired' => true], methods: ['POST'])]     public function saveProfile(RequestDataBag $data, SalesChannelContext $context, CustomerEntity $customer): Response
    {
        try {
            $this->changeCustomerProfileRoute->change($data$context$customer);

            $this->addFlash(self::SUCCESS, $this->trans('account.profileUpdateSuccess'));
        } catch (ConstraintViolationException $formViolations) {
            return $this->forwardToRoute('frontend.account.profile.page', ['formViolations' => $formViolations]);
        } catch (\Exception $exception) {
            $this->logger->error($exception->getMessage()['e' => $exception]);
            $this->addFlash(self::DANGER, $this->trans('error.message-default'));
        }

        return $this->redirectToRoute('frontend.account.profile.page');
    }

    #[Route(path: '/account/profile/email', name: 'frontend.account.profile.email.save', defaults: ['_loginRequired' => true], methods: ['POST'])]
use TranslatorTrait;
        };
    }

    /** * @dataProvider getTransTests */
    public function testTrans($expected$id$parameters)
    {
        $translator = $this->getTranslator();

        $this->assertEquals($expected$translator->trans($id$parameters));
    }

    /** * @dataProvider getTransChoiceTests */
    public function testTransChoiceWithExplicitLocale($expected$id$number)
    {
        $translator = $this->getTranslator();

        $this->assertEquals($expected$translator->trans($id['%count%' => $number]));
    }

    
This template is used for translation message extraction tests <?php echo $view['translator']->trans('single-quoted key'); ?> <?php echo $view['translator']->trans('double-quoted key'); ?> <?php echo $view['translator']->trans(<<<EOF heredoc key EOF
); ?> <?php echo $view['translator']->trans(<<<'EOF' nowdoc key EOF
); ?> <?php echo $view['translator']->trans(
    "double-quoted key with whitespace and escaped \$\n\" sequences"
);
$this->cause = $cause;

        return $this;
    }

    public function addViolation(): void
    {
        $parameters = null === $this->plural ? $this->parameters : (['%count%' => $this->plural] + $this->parameters);
        if (false === $this->translationDomain) {
            $translatedMessage = strtr($this->message, $parameters);
        } else {
            $translatedMessage = $this->translator->trans(
                $this->message,
                $parameters,
                $this->translationDomain
            );
        }

        $this->violations->add(new ConstraintViolation(
            $translatedMessage,
            $this->message,
            $this->parameters,
            $this->root,
            
do {
                            $translationDomain = $form->getConfig()->getOption('translation_domain');
                            array_unshift(
                                $translationParameters,
                                $form->getConfig()->getOption('label_translation_parameters', [])
                            );
                        } while (null === $translationDomain && null !== $form = $form->getParent());

                        $translationParameters = array_merge([], ...$translationParameters);

                        $label = $this->translator->trans(
                            $label,
                            $translationParameters,
                            $translationDomain
                        );
                    }

                    $message = str_replace('{{ label }}', $label$message);
                    $messageTemplate = str_replace('{{ label }}', $label$messageTemplate);
                }
            }

            
if ($form->isRoot() && $form->getConfig()->getOption('compound') && !$postRequestSizeExceeded) {
            $data = $event->getData();

            $csrfValue = \is_string($data[$this->fieldName] ?? null) ? $data[$this->fieldName] : null;
            $csrfToken = new CsrfToken($this->tokenId, $csrfValue);

            if (null === $csrfValue || !$this->tokenManager->isTokenValid($csrfToken)) {
                $errorMessage = $this->errorMessage;

                if (null !== $this->translator) {
                    $errorMessage = $this->translator->trans($errorMessage[]$this->translationDomain);
                }

                $form->addError(new FormError($errorMessage$errorMessage[], null, $csrfToken));
            }

            if (\is_array($data)) {
                unset($data[$this->fieldName]);
                $event->setData($data);
            }
        }
    }
}
$violations = $file->validate();

    // Remove violations of inaccessible fields as they cannot stem from our     // changes.     $violations->filterByFieldAccess();

    // Validate the file based on the field definition configuration.     $errors = file_validate($file$validators);
    if (!empty($errors)) {
      $translator = new DrupalTranslator();
      foreach ($errors as $error) {
        $violation = new ConstraintViolation($translator->trans($error),
          (string) $error,
          [],
          EntityAdapter::createFromEntity($file),
          '',
          NULL
        );
        $violations->add($violation);
      }
    }

    return $violations;
  }
$messageTemplate = $options['invalid_message'] ?? 'The value {{ value }} is not valid.';
            $translator = $this->translator;

            $builder->addEventListener(FormEvents::POST_SUBMIT, static function DFormEvent $event) use (&$unknownValues$messageTemplate$translator) {
                // Throw exception if unknown values were submitted                 if (\count($unknownValues) > 0) {
                    $form = $event->getForm();

                    $clientDataAsString = \is_scalar($form->getViewData()) ? (string) $form->getViewData() : (\is_array($form->getViewData()) ? implode('", "', array_keys($unknownValues)) : \gettype($form->getViewData()));

                    if ($translator) {
                        $message = $translator->trans($messageTemplate['{{ value }}' => $clientDataAsString], 'validators');
                    } else {
                        $message = strtr($messageTemplate['{{ value }}' => $clientDataAsString]);
                    }

                    $form->addError(new FormError($message$messageTemplate['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.', $clientDataAsString))));
                }
            });

            // <select> tag with "multiple" option or list of checkbox inputs             $builder->addViewTransformer(new ChoicesToValuesTransformer($choiceList));
        } else {
            
use TranslatorTrait;
        };
    }

    /** * @dataProvider getTransTests */
    public function testTrans($expected$id$parameters)
    {
        $translator = $this->getTranslator();

        $this->assertEquals($expected$translator->trans($id$parameters));
    }

    /** * @dataProvider getTransChoiceTests */
    public function testTransChoiceWithExplicitLocale($expected$id$number)
    {
        $translator = $this->getTranslator();

        $this->assertEquals($expected$translator->trans($id['%count%' => $number]));
    }

    
    public function sendContactForm(RequestDataBag $data, SalesChannelContext $context): JsonResponse
    {
        $response = [];

        try {
            $message = $this->contactFormRoute
                ->load($data->toRequestDataBag()$context)
                ->getResult()
                ->getIndividualSuccessMessage();

            if (!$message) {
                $message = $this->trans('contact.success');
            }
            $response[] = [
                'type' => 'success',
                'alert' => $message,
            ];
        } catch (ConstraintViolationException $formViolations) {
            $violations = [];
            foreach ($formViolations->getViolations() as $violation) {
                $violations[] = $violation->getMessage();
            }
            $response[] = [
                
This template is used for translation message extraction tests <?php echo $view['translator']->trans('single-quoted key') ?> <?php echo $view['translator']->trans('double-quoted key') ?> <?php echo $view['translator']->trans(<<<'EOF' heredoc key EOF
) ?> <?php echo $view['translator']->trans(<<<'EOF' nowdoc key EOF
) ?> <?php echo $view['translator']->trans(
    "double-quoted key with whitespace and escaped \$\n\" sequences"
)
if ($mainRequest->hasSession() === false) {
            return;
        }

        $session = $mainRequest->getSession();

        if (!method_exists($session, 'getFlashBag')) {
            return;
        }

        $session->getFlashBag()->add('info', $this->translator->trans('checkout.cart-merged-hint'));
    }
}
// fake request         $request = new Request();

        $request->attributes->set(SalesChannelRequest::ATTRIBUTE_DOMAIN_SNIPPET_SET_ID, $this->getSnippetSetIdForLocale('en-GB'));
        $request->attributes->set(SalesChannelRequest::ATTRIBUTE_DOMAIN_LOCALE, 'en-GB');

        $this->getContainer()->get(RequestStack::class)->push($request);

        // get overwritten string         static::assertEquals(
            $snippets[0]['value'],
            $this->translator->trans('new.unit.test.key', [], null, 'en-GB')
        );
        static::assertEquals(
            $snippets[1]['value'],
            $this->translator->trans('new.unit.test.key', [], null, 'de-DE')
        );
        static::assertEquals(
            $snippets[0]['value'],
            $this->translator->trans('new.unit.test.key', [], null, 'en')
        );
        static::assertEquals(
            $snippets[1]['value'],
            
Home | Imprint | This part of the site doesn't use cookies.