LocaleSwitcher.php 2.0 KB

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