GettextMessageSource.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\i18n;
  8. use Yii;
  9. /**
  10. * GettextMessageSource represents a message source that is based on GNU Gettext.
  11. *
  12. * Each GettextMessageSource instance represents the message tranlations
  13. * for a single domain. And each message category represents a message context
  14. * in Gettext. Translated messages are stored as either a MO or PO file,
  15. * depending on the [[useMoFile]] property value.
  16. *
  17. * All translations are saved under the [[basePath]] directory.
  18. *
  19. * Translations in one language are kept as MO or PO files under an individual
  20. * subdirectory whose name is the language ID. The file name is specified via
  21. * [[catalog]] property, which defaults to 'messages'.
  22. *
  23. * @author Qiang Xue <[email protected]>
  24. * @since 2.0
  25. */
  26. class GettextMessageSource extends MessageSource
  27. {
  28. const MO_FILE_EXT = '.mo';
  29. const PO_FILE_EXT = '.po';
  30. /**
  31. * @var string
  32. */
  33. public $basePath = '@app/messages';
  34. /**
  35. * @var string
  36. */
  37. public $catalog = 'messages';
  38. /**
  39. * @var boolean
  40. */
  41. public $useMoFile = true;
  42. /**
  43. * @var boolean
  44. */
  45. public $useBigEndian = false;
  46. /**
  47. * Loads the message translation for the specified language and category.
  48. * Child classes should override this method to return the message translations of
  49. * the specified language and category.
  50. * @param string $category the message category
  51. * @param string $language the target language
  52. * @return array the loaded messages. The keys are original messages, and the values
  53. * are translated messages.
  54. */
  55. protected function loadMessages($category, $language)
  56. {
  57. $messageFile = Yii::getAlias($this->basePath) . '/' . $language . '/' . $this->catalog;
  58. if ($this->useMoFile) {
  59. $messageFile .= static::MO_FILE_EXT;
  60. } else {
  61. $messageFile .= static::PO_FILE_EXT;
  62. }
  63. if (is_file($messageFile)) {
  64. if ($this->useMoFile) {
  65. $gettextFile = new GettextMoFile(['useBigEndian' => $this->useBigEndian]);
  66. } else {
  67. $gettextFile = new GettextPoFile();
  68. }
  69. $messages = $gettextFile->load($messageFile, $category);
  70. if (!is_array($messages)) {
  71. $messages = [];
  72. }
  73. return $messages;
  74. } else {
  75. Yii::error("The message file for category '$category' does not exist: $messageFile", __METHOD__);
  76. return [];
  77. }
  78. }
  79. }