LocaleSwitcher.php 1.7 KB

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