PoDatabaseWriter.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. * - overwrite_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. * @param array $options
  100. * An associative array containing:
  101. * - overwrite_options: An array of options. Each option contains:
  102. * - not_customized: Boolean indicating that not customized strings should
  103. * be overwritten.
  104. * - customized: Boolean indicating that customized strings should be
  105. * overwritten.
  106. * - customized: The strings being imported should be saved as customized.
  107. * One of LOCALE_CUSTOMIZED or LOCALE_NOT_CUSTOMIZED.
  108. */
  109. public function setOptions(array $options) {
  110. if (!isset($options['overwrite_options'])) {
  111. $options['overwrite_options'] = [];
  112. }
  113. $options['overwrite_options'] += [
  114. 'not_customized' => FALSE,
  115. 'customized' => FALSE,
  116. ];
  117. $options += [
  118. 'customized' => LOCALE_NOT_CUSTOMIZED,
  119. ];
  120. $this->options = $options;
  121. }
  122. /**
  123. * {@inheritdoc}
  124. */
  125. public function getHeader() {
  126. return $this->header;
  127. }
  128. /**
  129. * Implements Drupal\Component\Gettext\PoMetadataInterface::setHeader().
  130. *
  131. * Sets the header and configure Drupal accordingly.
  132. *
  133. * Before being able to process the given header we need to know in what
  134. * context this database write is done. For this the options must be set.
  135. *
  136. * A langcode is required to set the current header's PluralForm.
  137. *
  138. * @param \Drupal\Component\Gettext\PoHeader $header
  139. * Header metadata.
  140. *
  141. * @throws Exception
  142. */
  143. public function setHeader(PoHeader $header) {
  144. $this->header = $header;
  145. $locale_plurals = \Drupal::state()->get('locale.translation.plurals') ?: [];
  146. // Check for options.
  147. $options = $this->getOptions();
  148. if (empty($options)) {
  149. throw new \Exception('Options should be set before assigning a PoHeader.');
  150. }
  151. $overwrite_options = $options['overwrite_options'];
  152. // Check for langcode.
  153. $langcode = $this->langcode;
  154. if (empty($langcode)) {
  155. throw new \Exception('Langcode should be set before assigning a PoHeader.');
  156. }
  157. if (array_sum($overwrite_options) || empty($locale_plurals[$langcode]['plurals'])) {
  158. // Get and store the plural formula if available.
  159. $plural = $header->getPluralForms();
  160. if (isset($plural) && $p = $header->parsePluralForms($plural)) {
  161. list($nplurals, $formula) = $p;
  162. \Drupal::service('locale.plural.formula')->setPluralFormula($langcode, $nplurals, $formula);
  163. }
  164. }
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function writeItem(PoItem $item) {
  170. if ($item->isPlural()) {
  171. $item->setSource(implode(PoItem::DELIMITER, $item->getSource()));
  172. $item->setTranslation(implode(PoItem::DELIMITER, $item->getTranslation()));
  173. }
  174. $this->importString($item);
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. public function writeItems(PoReaderInterface $reader, $count = -1) {
  180. $forever = $count == -1;
  181. while (($count-- > 0 || $forever) && ($item = $reader->readItem())) {
  182. $this->writeItem($item);
  183. }
  184. }
  185. /**
  186. * Imports one string into the database.
  187. *
  188. * @param \Drupal\Component\Gettext\PoItem $item
  189. * The item being imported.
  190. *
  191. * @return int
  192. * The string ID of the existing string modified or the new string added.
  193. */
  194. private function importString(PoItem $item) {
  195. // Initialize overwrite options if not set.
  196. $this->options['overwrite_options'] += [
  197. 'not_customized' => FALSE,
  198. 'customized' => FALSE,
  199. ];
  200. $overwrite_options = $this->options['overwrite_options'];
  201. $customized = $this->options['customized'];
  202. $context = $item->getContext();
  203. $source = $item->getSource();
  204. $translation = $item->getTranslation();
  205. // Look up the source string and any existing translation.
  206. $strings = \Drupal::service('locale.storage')->getTranslations([
  207. 'language' => $this->langcode,
  208. 'source' => $source,
  209. 'context' => $context,
  210. ]);
  211. $string = reset($strings);
  212. if (!empty($translation)) {
  213. // Skip this string unless it passes a check for dangerous code.
  214. if (!locale_string_is_safe($translation)) {
  215. \Drupal::logger('locale')->error('Import of string "%string" was skipped because of disallowed or malformed HTML.', ['%string' => $translation]);
  216. $this->report['skips']++;
  217. return 0;
  218. }
  219. elseif ($string) {
  220. $string->setString($translation);
  221. if ($string->isNew()) {
  222. // No translation in this language.
  223. $string->setValues([
  224. 'language' => $this->langcode,
  225. 'customized' => $customized,
  226. ]);
  227. $string->save();
  228. $this->report['additions']++;
  229. }
  230. elseif ($overwrite_options[$string->customized ? 'customized' : 'not_customized']) {
  231. // Translation exists, only overwrite if instructed.
  232. $string->customized = $customized;
  233. $string->save();
  234. $this->report['updates']++;
  235. }
  236. $this->report['strings'][] = $string->getId();
  237. return $string->lid;
  238. }
  239. else {
  240. // No such source string in the database yet.
  241. $string = \Drupal::service('locale.storage')->createString(['source' => $source, 'context' => $context])
  242. ->save();
  243. \Drupal::service('locale.storage')->createTranslation([
  244. 'lid' => $string->getId(),
  245. 'language' => $this->langcode,
  246. 'translation' => $translation,
  247. 'customized' => $customized,
  248. ])->save();
  249. $this->report['additions']++;
  250. $this->report['strings'][] = $string->getId();
  251. return $string->lid;
  252. }
  253. }
  254. elseif ($string && !$string->isNew() && $overwrite_options[$string->customized ? 'customized' : 'not_customized']) {
  255. // Empty translation, remove existing if instructed.
  256. $string->delete();
  257. $this->report['deletes']++;
  258. $this->report['strings'][] = $string->lid;
  259. return $string->lid;
  260. }
  261. }
  262. }