Debian Codegraph @

lib/3rdParty/composer/symfony/translation/LocaleSwitcher.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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 <[email protected]>
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 // Silently ignore if the intl extension is not loaded
38 try {
39 if (class_exists(\Locale::class, false)) {
40 \Locale::setDefault($locale);
41 }
42 } catch (\Exception) {
43 }
44
45 $this->locale = $locale;
46 $this->requestContext?->setParameter('_locale', $locale);
47
48 foreach ($this->localeAwareServices as $service) {
49 $service->setLocale($locale);
50 }
51 }
52
53 public function getLocale(): string
54 {
55 return $this->locale;
56 }
57
58 /**
59 * Switch to a new locale, execute a callback, then switch back to the original.
60 *
61 * @template T
62 *
63 * @param callable(string $locale):T $callback
64 *
65 * @return T
66 */
67 public function runWithLocale(string $locale, callable $callback): mixed
68 {
69 $original = $this->getLocale();
70 $this->setLocale($locale);
71
72 try {
73 return $callback($locale);
74 } finally {
75 $this->setLocale($original);
76 }
77 }
78
79 public function reset(): void
80 {
81 $this->setLocale($this->defaultLocale);
82 }
83 }