DataBundle.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Locale\Bundle;
  7. class DataBundle
  8. {
  9. /**
  10. * @var string
  11. */
  12. protected $path = 'ICUDATA';
  13. /**
  14. * @var \ResourceBundle[][]
  15. */
  16. protected static $bundles = [];
  17. /**
  18. * Get resource bundle for the locale
  19. *
  20. * @param string $locale
  21. * @return \ResourceBundle
  22. */
  23. public function get($locale)
  24. {
  25. $locale = $this->cleanLocale($locale);
  26. $class = get_class($this);
  27. if (!isset(static::$bundles[$class][$locale])) {
  28. $bundle = $this->createResourceBundle($locale, $this->path);
  29. if (!$bundle && $this->path != 'ICUDATA') {
  30. $bundle = $this->createResourceBundle($locale, 'ICUDATA');
  31. }
  32. static::$bundles[$class][$locale] = $bundle;
  33. }
  34. return static::$bundles[$class][$locale];
  35. }
  36. /**
  37. * @param string $locale
  38. * @param string $path
  39. * @return null|\ResourceBundle
  40. */
  41. protected function createResourceBundle($locale, $path)
  42. {
  43. try {
  44. $bundle = new \ResourceBundle($locale, $path);
  45. } catch (\Exception $e) {
  46. // HHVM compatibility: constructor throws on invalid resource
  47. $bundle = null;
  48. }
  49. return $bundle;
  50. }
  51. /**
  52. * Clean locale leaving only language and script
  53. *
  54. * @param string $locale
  55. * @return string
  56. */
  57. protected function cleanLocale($locale)
  58. {
  59. $localeParts = \Locale::parseLocale($locale);
  60. $cleanLocaleParts = [];
  61. if (isset($localeParts['language'])) {
  62. $cleanLocaleParts['language'] = $localeParts['language'];
  63. }
  64. if (isset($localeParts['script'])) {
  65. $cleanLocaleParts['script'] = $localeParts['script'];
  66. }
  67. return \Locale::composeLocale($cleanLocaleParts);
  68. }
  69. }