PhpMessageSource.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. * PhpMessageSource represents a message source that stores translated messages in PHP scripts.
  11. *
  12. * PhpMessageSource uses PHP arrays to keep message translations.
  13. *
  14. * - Each PHP script contains one array which stores the message translations in one particular
  15. * language and for a single message category;
  16. * - Each PHP script is saved as a file named as `[[basePath]]/LanguageID/CategoryName.php`;
  17. * - Within each PHP script, the message translations are returned as an array like the following:
  18. *
  19. * ~~~
  20. * return [
  21. * 'original message 1' => 'translated message 1',
  22. * 'original message 2' => 'translated message 2',
  23. * ];
  24. * ~~~
  25. *
  26. * You may use [[fileMap]] to customize the association between category names and the file names.
  27. *
  28. * @author Qiang Xue <[email protected]>
  29. * @since 2.0
  30. */
  31. class PhpMessageSource extends MessageSource
  32. {
  33. /**
  34. * @var string the base path for all translated messages. Defaults to null, meaning
  35. * the "messages" subdirectory of the application directory (e.g. "protected/messages").
  36. */
  37. public $basePath = '@app/messages';
  38. /**
  39. * @var array mapping between message categories and the corresponding message file paths.
  40. * The file paths are relative to [[basePath]]. For example,
  41. *
  42. * ~~~
  43. * [
  44. * 'core' => 'core.php',
  45. * 'ext' => 'extensions.php',
  46. * ]
  47. * ~~~
  48. */
  49. public $fileMap;
  50. /**
  51. * Loads the message translation for the specified language and category.
  52. * @param string $category the message category
  53. * @param string $language the target language
  54. * @return array the loaded messages
  55. */
  56. protected function loadMessages($category, $language)
  57. {
  58. $messageFile = Yii::getAlias($this->basePath) . "/$language/";
  59. if (isset($this->fileMap[$category])) {
  60. $messageFile .= $this->fileMap[$category];
  61. } else {
  62. $messageFile .= str_replace('\\', '/', $category) . '.php';
  63. }
  64. if (is_file($messageFile)) {
  65. $messages = include($messageFile);
  66. if (!is_array($messages)) {
  67. $messages = [];
  68. }
  69. return $messages;
  70. } else {
  71. Yii::error("The message file for category '$category' does not exist: $messageFile", __METHOD__);
  72. return [];
  73. }
  74. }
  75. }