Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
 
12
namespace Symfony\Component\Translation;
13
 
14
use Symfony\Component\Routing\RequestContext;
15
use Symfony\Contracts\Translation\LocaleAwareInterface;
16
 
17
/**
18
 * @author Kevin Bond <kevinbond@gmail.com>
19
 */
20
class LocaleSwitcher implements LocaleAwareInterface
21
{
22
    private string $defaultLocale;
23
 
24
    /**
25
     * @param LocaleAwareInterface[] $localeAwareServices
26
     */
27
    public function __construct(
28
        private string $locale,
29
        private iterable $localeAwareServices,
30
        private ?RequestContext $requestContext = null,
31
    ) {
32
        $this->defaultLocale = $locale;
33
    }
34
 
35
    public function setLocale(string $locale): void
36
    {
37
        \Locale::setDefault($this->locale = $locale);
38
        $this->requestContext?->setParameter('_locale', $locale);
39
 
40
        foreach ($this->localeAwareServices as $service) {
41
            $service->setLocale($locale);
42
        }
43
    }
44
 
45
    public function getLocale(): string
46
    {
47
        return $this->locale;
48
    }
49
 
50
    /**
51
     * Switch to a new locale, execute a callback, then switch back to the original.
52
     *
53
     * @template T
54
     *
55
     * @param callable():T $callback
56
     *
57
     * @return T
58
     */
59
    public function runWithLocale(string $locale, callable $callback): mixed
60
    {
61
        $original = $this->getLocale();
62
        $this->setLocale($locale);
63
 
64
        try {
65
            return $callback();
66
        } finally {
67
            $this->setLocale($original);
68
        }
69
    }
70
 
71
    public function reset(): void
72
    {
73
        $this->setLocale($this->defaultLocale);
74
    }
75
}