setLocale example

/* The setOrder function of the Shopware_Components_Document change the currency of the shop. This would create a new Shop if we execute a flush(); Only create order documents when requested. */
            if ($documentType !== 0) {
                $this->createOrderDocuments($documentType$documentMode$order);
            }

            if ($previousLocale) {
                // This is necessary, since the "checkOrderStatus" method might change the locale due to translation issues                 // when sending an order status mail. Therefore, we reset it here to the chosen backend language.                 $this->get('snippets')->setLocale($previousLocale);
                $this->get('snippets')->resetShop();
            }

            $data['paymentStatus'] = $stateTranslator->translateState(StateTranslatorService::STATE_PAYMENT, $modelManager->toArray($order->getPaymentStatus()));
            $data['orderStatus'] = $stateTranslator->translateState(StateTranslatorService::STATE_ORDER, $modelManager->toArray($order->getOrderStatus()));

            try {
                // The method '$this->checkOrderStatus()' (even its name would not imply that) sends mails and can fail                 // with an exception. Catch this exception, so the batch process does not abort.                 $data['mail'] = $this->checkOrderStatus($order$statusBefore$clearedBefore$autoSend$documentType$addAttachments);
            } catch (Exception $e) {
                
        // so we always format the translations in the actual locale of the catalogue         $formatLocale = Locale::getFallback($catalogue->getLocale()) ?? $catalogue->getLocale();

        return $this->formatter->format($catalogue->get($id$domain)$formatLocale$parameters);
    }

    /** * {@inheritdoc} */
    public function setLocale(string $locale): void
    {
        $this->translator->setLocale($locale);
    }

    /** * {@inheritdoc} */
    public function getLocale(): string
    {
        return $this->translator->getLocale();
    }

    public function warmUp($cacheDir): void
    {

    private array $installerLanguages = ['de', 'en'];

    #[AsEventListener(RequestEvent::class, priority: 15)]     public function __invoke(RequestEvent $event): void
    {
        $request = $event->getRequest();

        $locale = $this->detectLanguage($request);
        $request->attributes->set('_locale', $locale);
        $request->setLocale($locale);
    }

    private function detectLanguage(Request $request): string
    {
        $session = $request->getSession();

        // language is changed         if ($request->query->has('language') && \in_array((string) $request->query->get('language')$this->installerLanguages, true)) {
            $session->set('language', (string) $request->query->get('language'));

            return (string) $request->query->get('language');
        }
$request->initialize([][]['foo' => 'bar']);
        $this->assertEquals('bar', $request->attributes->get('foo'), '->initialize() takes an array of attributes as its third argument');

        $request->initialize([][][][][]['HTTP_FOO' => 'bar']);
        $this->assertEquals('bar', $request->headers->get('FOO'), '->initialize() takes an array of HTTP headers as its sixth argument');
    }

    public function testGetLocale()
    {
        $request = new Request();
        $request->setLocale('pl');
        $locale = $request->getLocale();
        $this->assertEquals('pl', $locale);
    }

    public function testGetUser()
    {
        $request = Request::create('http://user:password@test.com');
        $user = $request->getUser();

        $this->assertEquals('user', $user);
    }

    
public function testRenderFallbackToInlineStrategyIfSsiNotSupported()
    {
        $strategy = new SsiFragmentRenderer(new Ssi()$this->getInlineStrategy(true));
        $strategy->render('/', Request::create('/'));
    }

    public function testRender()
    {
        $strategy = new SsiFragmentRenderer(new Ssi()$this->getInlineStrategy());

        $request = Request::create('/');
        $request->setLocale('fr');
        $request->headers->set('Surrogate-Capability', 'SSI/1.0');

        $this->assertEquals('<!--#include virtual="/" -->', $strategy->render('/', $request)->getContent());
        $this->assertEquals('<!--#include virtual="/" -->', $strategy->render('/', $request['comment' => 'This is a comment'])->getContent(), 'Strategy options should not impact the ssi include tag');
    }

    public function testRenderControllerReference()
    {
        $signer = new UriSigner('foo');
        $strategy = new SsiFragmentRenderer(new Ssi()$this->getInlineStrategy()$signer);

        


        static $setSession;

        $setSession ??= \Closure::bind(static function D$subRequest$request) { $subRequest->session = $request->session; }, null, Request::class);
        $setSession($subRequest$request);

        if ($request->get('_format')) {
            $subRequest->attributes->set('_format', $request->get('_format'));
        }
        if ($request->getDefaultLocale() !== $request->getLocale()) {
            $subRequest->setLocale($request->getLocale());
        }
        if ($request->attributes->has('_stateless')) {
            $subRequest->attributes->set('_stateless', $request->attributes->get('_stateless'));
        }

        return $subRequest;
    }

    public function getName(): string
    {
        return 'inline';
    }
return new Iterator();
    }

    /** * Responsible for loading the language string translations. * * @return Language */
    public static function language(?string $locale = null, bool $getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('language', $locale)->setLocale($locale);
        }

        if (AppServices::request() instanceof IncomingRequest) {
            $requestLocale = AppServices::request()->getLocale();
        } else {
            $requestLocale = Locale::getDefault();
        }

        // Use '?:' for empty string check         $locale = $locale ?: $requestLocale;

        
$validatorFactory = $this->validatorFactory ?? new ConstraintValidatorFactory();
        $translator = $this->translator;

        if (null === $translator) {
            $translator = new class() implements TranslatorInterface, LocaleAwareInterface {
                use TranslatorTrait;
            };
            // Force the locale to be 'en' when no translator is provided rather than relying on the Intl default locale             // This avoids depending on Intl or the stub implementation being available. It also ensures that Symfony             // validation messages are pluralized properly even when the default locale gets changed because they are in             // English.             $translator->setLocale('en');
        }

        $contextFactory = new ExecutionContextFactory($translator$this->translationDomain);

        return new RecursiveValidator($contextFactory$metadataFactory$validatorFactory$this->initializers);
    }

    private function createAnnotationReader(): Reader
    {
        if (!class_exists(AnnotationReader::class)) {
            throw new LogicException('Enabling annotation based constraint mapping requires the packages doctrine/annotations and symfony/cache to be installed.');
        }
public function registerShop(Shop $shop): void
    {
        $this->registerResources($shop);
        $this->resetTemplate($shop);
    }

    public function registerResources(Shop $shop): void
    {
        $this->container->set('shop', $shop);

        $locale = $this->container->get(Zend_Locale::class);
        $locale->setLocale($shop->getLocale()->toString());

        $currency = $this->container->get(Zend_Currency::class);
        $currency->setLocale($locale);
        $currency->setFormat($shop->getCurrency()->toArray());

        $config = $this->container->get(Shopware_Components_Config::class);
        $config->setShop($shop);

        $snippets = $this->container->get(Shopware_Components_Snippet_Manager::class);
        $snippets->setShop($shop);

        
$modelManager = Shopware()->Models();
        $orderLocale = null;

        if ($modelManager !== null) {
            $orderLocale = $modelManager->find(
                ShopLocale::class,
                $this->_order['language']
            );
        }

        if ($orderLocale !== null) {
            $snippetManager->setLocale($orderLocale);
        }

        $shippingName = $snippetManager->getNamespace('documents/index')->get('ShippingCosts', 'Shipping costs', true);

        if ($this->_order['invoice_shipping_tax_rate'] === null && $this->_shipping !== null) {
            $approximateTaxRate = 0.0;
            if ((float) $this->_order['invoice_shipping_net'] !== 0.0) {
                // p.e. = 24.99 / 20.83 * 100 - 100 = 19.971195391 (approx. 20% VAT)                 $approximateTaxRate = $this->_order['invoice_shipping'] / $this->_order['invoice_shipping_net'] * 100 - 100;
            }

            
'/_fragment?_path=foo%3Dfoo%26_format%3Djson%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', ['foo' => 'foo', '_format' => 'json'][])],
            ['/_fragment?bar=bar&_path=foo%3Dfoo%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', ['foo' => 'foo']['bar' => 'bar'])],
            ['/_fragment?foo=foo&_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', []['foo' => 'foo'])],
            ['/_fragment?_path=foo%255B0%255D%3Dfoo%26foo%255B1%255D%3Dbar%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', ['foo' => ['foo', 'bar']][])],
        ];
    }

    public function testGenerateFragmentUriWithARequest()
    {
        $request = Request::create('/');
        $request->attributes->set('_format', 'json');
        $request->setLocale('fr');
        $controller = new ControllerReference('controller', [][]);

        $this->assertEquals('/_fragment?_path=_format%3Djson%26_locale%3Dfr%26_controller%3Dcontroller', $this->callGenerateFragmentUriMethod($controller$request));
    }

    /** * @dataProvider getGenerateFragmentUriDataWithNonScalar */
    public function testGenerateFragmentUriWithNonScalar($controller)
    {
        $this->expectException(\LogicException::class);
        
$validatorFactory = $this->validatorFactory ?? new ConstraintValidatorFactory();
        $translator = $this->translator;

        if (null === $translator) {
            $translator = new class() implements TranslatorInterface, LocaleAwareInterface {
                use TranslatorTrait;
            };
            // Force the locale to be 'en' when no translator is provided rather than relying on the Intl default locale             // This avoids depending on Intl or the stub implementation being available. It also ensures that Symfony             // validation messages are pluralized properly even when the default locale gets changed because they are in             // English.             $translator->setLocale('en');
        }

        $contextFactory = new ExecutionContextFactory($translator$this->translationDomain);

        return new RecursiveValidator($contextFactory$metadataFactory$validatorFactory$this->initializers);
    }

    private function createAnnotationReader(): Reader
    {
        if (!class_exists(AnnotationReader::class)) {
            throw new LogicException('Enabling annotation based constraint mapping requires the packages doctrine/annotations and symfony/cache to be installed.');
        }
return [
            RequestEvent::class => ['setInstallerLocale', 15],
        ];
    }

    public function setInstallerLocale(RequestEvent $event): void
    {
        $request = $event->getRequest();

        $locale = $this->detectLanguage($request);
        $request->attributes->set('_locale', $locale);
        $request->setLocale($locale);
    }

    private function detectLanguage(Request $request): string
    {
        $session = $request->getSession();

        // language is changed         if ($request->query->has('language') && \in_array((string) $request->query->get('language')$this->installerLanguages, true)) {
            $session->set('language', (string) $request->query->get('language'));

            return (string) $request->query->get('language');
        }
/** * @param iterable<mixed, LocaleAwareInterface> $localeAwareServices */
    public function __construct(iterable $localeAwareServices, RequestStack $requestStack)
    {
        $this->localeAwareServices = $localeAwareServices;
        $this->requestStack = $requestStack;
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $this->setLocale($event->getRequest()->getLocale()$event->getRequest()->getDefaultLocale());
    }

    public function onKernelFinishRequest(FinishRequestEvent $event): void
    {
        if (null === $parentRequest = $this->requestStack->getParentRequest()) {
            foreach ($this->localeAwareServices as $service) {
                $service->setLocale($event->getRequest()->getDefaultLocale());
            }

            return;
        }

        
if ($request->attributes->has(SecurityRequestAttributes::ACCESS_DENIED_ERROR)) {
            $newRequest->attributes->set(SecurityRequestAttributes::ACCESS_DENIED_ERROR, $request->attributes->get(SecurityRequestAttributes::ACCESS_DENIED_ERROR));
        }
        if ($request->attributes->has(SecurityRequestAttributes::LAST_USERNAME)) {
            $newRequest->attributes->set(SecurityRequestAttributes::LAST_USERNAME, $request->attributes->get(SecurityRequestAttributes::LAST_USERNAME));
        }

        if ($request->get('_format')) {
            $newRequest->attributes->set('_format', $request->get('_format'));
        }
        if ($request->getDefaultLocale() !== $request->getLocale()) {
            $newRequest->setLocale($request->getLocale());
        }

        return $newRequest;
    }

    /** * Checks that a given path matches the Request. * * @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo)) * * @return bool true if the path is the same as the one from the Request, false otherwise */
Home | Imprint | This part of the site doesn't use cookies.