FallbackTrait.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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\Intl\Data\Generator;
  11. use Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReaderInterface;
  12. use Symfony\Component\Intl\Locale;
  13. /**
  14. * @author Roland Franssen <franssen.roland@gmail.com>
  15. *
  16. * @internal
  17. */
  18. trait FallbackTrait
  19. {
  20. private $fallbackCache = [];
  21. private $generatingFallback = false;
  22. /**
  23. * @see AbstractDataGenerator::generateDataForLocale()
  24. */
  25. abstract protected function generateDataForLocale(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): ?array;
  26. /**
  27. * @see AbstractDataGenerator::generateDataForRoot()
  28. */
  29. abstract protected function generateDataForRoot(BundleEntryReaderInterface $reader, string $tempDir): ?array;
  30. private function generateFallbackData(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): array
  31. {
  32. if (null === $fallback = Locale::getFallback($displayLocale)) {
  33. return [];
  34. }
  35. if (isset($this->fallbackCache[$fallback])) {
  36. return $this->fallbackCache[$fallback];
  37. }
  38. $prevGeneratingFallback = $this->generatingFallback;
  39. $this->generatingFallback = true;
  40. try {
  41. $data = 'root' === $fallback ? $this->generateDataForRoot($reader, $tempDir) : $this->generateDataForLocale($reader, $tempDir, $fallback);
  42. } finally {
  43. $this->generatingFallback = $prevGeneratingFallback;
  44. }
  45. return $this->fallbackCache[$fallback] = $data ?: [];
  46. }
  47. }