PoDatabaseWriter.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. <?php
  2. namespace Drupal\locale;
  3. use Drupal\Component\Gettext\PoHeader;
  4. use Drupal\Component\Gettext\PoItem;
  5. use Drupal\Component\Gettext\PoReaderInterface;
  6. use Drupal\Component\Gettext\PoWriterInterface;
  7. /**
  8. * Gettext PO writer working with the locale module database.
  9. */
  10. class PoDatabaseWriter implements PoWriterInterface {
  11. /**
  12. * An associative array indicating what data should be overwritten, if any.
  13. *
  14. * Elements of the array:
  15. * - override_options
  16. * - not_customized: boolean indicating that not customized strings should
  17. * be overwritten.
  18. * - customized: boolean indicating that customized strings should be
  19. * overwritten.
  20. * - customized: the strings being imported should be saved as customized.
  21. * One of LOCALE_CUSTOMIZED or LOCALE_NOT_CUSTOMIZED.
  22. *
  23. * @var array
  24. */
  25. private $options;
  26. /**
  27. * Language code of the language being written to the database.
  28. *
  29. * @var string
  30. */
  31. private $langcode;
  32. /**
  33. * Header of the po file written to the database.
  34. *
  35. * @var \Drupal\Component\Gettext\PoHeader
  36. */
  37. private $header;
  38. /**
  39. * Associative array summarizing the number of changes done.
  40. *
  41. * Keys for the array:
  42. * - additions: number of source strings newly added
  43. * - updates: number of translations updated
  44. * - deletes: number of translations deleted
  45. * - skips: number of strings skipped due to disallowed HTML
  46. *
  47. * @var array
  48. */
  49. private $report;
  50. /**
  51. * Constructor, initialize reporting array.
  52. */
  53. public function __construct() {
  54. $this->setReport();
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function getLangcode() {
  60. return $this->langcode;
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function setLangcode($langcode) {
  66. $this->langcode = $langcode;
  67. }
  68. /**
  69. * Get the report of the write operations.
  70. */
  71. public function getReport() {
  72. return $this->report;
  73. }
  74. /**
  75. * Set the report array of write operations.
  76. *
  77. * @param array $report
  78. * Associative array with result information.
  79. */
  80. public function setReport($report = []) {
  81. $report += [
  82. 'additions' => 0,
  83. 'updates' => 0,
  84. 'deletes' => 0,
  85. 'skips' => 0,
  86. 'strings' => [],
  87. ];
  88. $this->report = $report;
  89. }
  90. /**
  91. * Get the options used by the writer.
  92. */
  93. public function getOptions() {
  94. return $this->options;
  95. }
  96. /**
  97. * Set the options for the current writer.
  98. */
  99. public function setOptions(array $options) {
  100. if (!isset($options['overwrite_options'])) {
  101. $options['overwrite_options'] = [];
  102. }
  103. $options['overwrite_options'] += [
  104. 'not_customized' => FALSE,
  105. 'customized' => FALSE,
  106. ];
  107. $options += [
  108. 'customized' => LOCALE_NOT_CUSTOMIZED,
  109. ];
  110. $this->options = $options;
  111. }
  112. /**
  113. * {@inheritdoc}
  114. */
  115. public function getHeader() {
  116. return $this->header;
  117. }
  118. /**
  119. * Implements Drupal\Component\Gettext\PoMetadataInterface::setHeader().
  120. *
  121. * Sets the header and configure Drupal accordingly.
  122. *
  123. * Before being able to process the given header we need to know in what
  124. * context this database write is done. For this the options must be set.
  125. *
  126. * A langcode is required to set the current header's PluralForm.
  127. *
  128. * @param \Drupal\Component\Gettext\PoHeader $header
  129. * Header metadata.
  130. *
  131. * @throws Exception
  132. */
  133. public function setHeader(PoHeader $header) {
  134. $this->header = $header;
  135. $locale_plurals = \Drupal::state()->get('locale.translation.plurals') ?: [];
  136. // Check for options.
  137. $options = $this->getOptions();
  138. if (empty($options)) {
  139. throw new \Exception('Options should be set before assigning a PoHeader.');
  140. }
  141. $overwrite_options = $options['overwrite_options'];
  142. // Check for langcode.
  143. $langcode = $this->langcode;
  144. if (empty($langcode)) {
  145. throw new \Exception('Langcode should be set before assigning a PoHeader.');
  146. }
  147. if (array_sum($overwrite_options) || empty($locale_plurals[$langcode]['plurals'])) {
  148. // Get and store the plural formula if available.
  149. $plural = $header->getPluralForms();
  150. if (isset($plural) && $p = $header->parsePluralForms($plural)) {
  151. list($nplurals, $formula) = $p;
  152. \Drupal::service('locale.plural.formula')->setPluralFormula($langcode, $nplurals, $formula);
  153. }
  154. }
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. public function writeItem(PoItem $item) {
  160. if ($item->isPlural()) {
  161. $item->setSource(implode(LOCALE_PLURAL_DELIMITER, $item->getSource()));
  162. $item->setTranslation(implode(LOCALE_PLURAL_DELIMITER, $item->getTranslation()));
  163. }
  164. $this->importString($item);
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function writeItems(PoReaderInterface $reader, $count = -1) {
  170. $forever = $count == -1;
  171. while (($count-- > 0 || $forever) && ($item = $reader->readItem())) {
  172. $this->writeItem($item);
  173. }
  174. }
  175. /**
  176. * Imports one string into the database.
  177. *
  178. * @param \Drupal\Component\Gettext\PoItem $item
  179. * The item being imported.
  180. *
  181. * @return int
  182. * The string ID of the existing string modified or the new string added.
  183. */
  184. private function importString(PoItem $item) {
  185. // Initialize overwrite options if not set.
  186. $this->options['overwrite_options'] += [
  187. 'not_customized' => FALSE,
  188. 'customized' => FALSE,
  189. ];
  190. $overwrite_options = $this->options['overwrite_options'];
  191. $customized = $this->options['customized'];
  192. $context = $item->getContext();
  193. $source = $item->getSource();
  194. $translation = $item->getTranslation();
  195. // Look up the source string and any existing translation.
  196. $strings = \Drupal::service('locale.storage')->getTranslations([
  197. 'language' => $this->langcode,
  198. 'source' => $source,
  199. 'context' => $context,
  200. ]);
  201. $string = reset($strings);
  202. if (!empty($translation)) {
  203. // Skip this string unless it passes a check for dangerous code.
  204. if (!locale_string_is_safe($translation)) {
  205. \Drupal::logger('locale')->error('Import of string "%string" was skipped because of disallowed or malformed HTML.', ['%string' => $translation]);
  206. $this->report['skips']++;
  207. return 0;
  208. }
  209. elseif ($string) {
  210. $string->setString($translation);
  211. if ($string->isNew()) {
  212. // No translation in this language.
  213. $string->setValues([
  214. 'language' => $this->langcode,
  215. 'customized' => $customized,
  216. ]);
  217. $string->save();
  218. $this->report['additions']++;
  219. }
  220. elseif ($overwrite_options[$string->customized ? 'customized' : 'not_customized']) {
  221. // Translation exists, only overwrite if instructed.
  222. $string->customized = $customized;
  223. $string->save();
  224. $this->report['updates']++;
  225. }
  226. $this->report['strings'][] = $string->getId();
  227. return $string->lid;
  228. }
  229. else {
  230. // No such source string in the database yet.
  231. $string = \Drupal::service('locale.storage')->createString(['source' => $source, 'context' => $context])
  232. ->save();
  233. \Drupal::service('locale.storage')->createTranslation([
  234. 'lid' => $string->getId(),
  235. 'language' => $this->langcode,
  236. 'translation' => $translation,
  237. 'customized' => $customized,
  238. ])->save();
  239. $this->report['additions']++;
  240. $this->report['strings'][] = $string->getId();
  241. return $string->lid;
  242. }
  243. }
  244. elseif ($string && !$string->isNew() && $overwrite_options[$string->customized ? 'customized' : 'not_customized']) {
  245. // Empty translation, remove existing if instructed.
  246. $string->delete();
  247. $this->report['deletes']++;
  248. $this->report['strings'][] = $string->lid;
  249. return $string->lid;
  250. }
  251. }
  252. }