Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | 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
    {
991 lars 37
        if (class_exists(\Locale::class)) {
38
            \Locale::setDefault($locale);
39
        }
40
        $this->locale = $locale;
148 lars 41
        $this->requestContext?->setParameter('_locale', $locale);
42
 
43
        foreach ($this->localeAwareServices as $service) {
44
            $service->setLocale($locale);
45
        }
46
    }
47
 
48
    public function getLocale(): string
49
    {
50
        return $this->locale;
51
    }
52
 
53
    /**
54
     * Switch to a new locale, execute a callback, then switch back to the original.
55
     *
56
     * @template T
57
     *
58
     * @param callable():T $callback
59
     *
60
     * @return T
61
     */
62
    public function runWithLocale(string $locale, callable $callback): mixed
63
    {
64
        $original = $this->getLocale();
65
        $this->setLocale($locale);
66
 
67
        try {
68
            return $callback();
69
        } finally {
70
            $this->setLocale($original);
71
        }
72
    }
73
 
74
    public function reset(): void
75
    {
76
        $this->setLocale($this->defaultLocale);
77
    }
78
}