LocaleSwitcher.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. if (class_exists(\Locale::class)) {
  32. \Locale::setDefault($locale);
  33. }
  34. $this->locale = $locale;
  35. $this->requestContext?->setParameter('_locale', $locale);
  36. foreach ($this->localeAwareServices as $service) {
  37. $service->setLocale($locale);
  38. }
  39. }
  40. public function getLocale(): string
  41. {
  42. return $this->locale;
  43. }
  44. /**
  45. * Switch to a new locale, execute a callback, then switch back to the original.
  46. *
  47. * @template T
  48. *
  49. * @param callable():T $callback
  50. *
  51. * @return T
  52. */
  53. public function runWithLocale(string $locale, callable $callback): mixed
  54. {
  55. $original = $this->getLocale();
  56. $this->setLocale($locale);
  57. try {
  58. return $callback();
  59. } finally {
  60. $this->setLocale($original);
  61. }
  62. }
  63. public function reset(): void
  64. {
  65. $this->setLocale($this->defaultLocale);
  66. }
  67. }