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