Passed
Pull Request — main (#9)
by Dante
01:33
created

TranslateObjectsCommand::objectsIterator()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 30
rs 9.584
cc 4
nc 4
nop 3
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * BEdita, API-first content management framework
6
 * Copyright 2024 Atlas Srl, Chialab Srl
7
 *
8
 * This file is part of BEdita: you can redistribute it and/or modify
9
 * it under the terms of the GNU Lesser General Public License as published
10
 * by the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
14
 */
15
namespace BEdita\ImportTools\Command;
16
17
use BEdita\Core\Utility\LoggedUser;
18
use Cake\Command\Command;
19
use Cake\Console\Arguments;
20
use Cake\Console\ConsoleIo;
21
use Cake\Console\ConsoleOptionParser;
22
use Cake\Core\Configure;
23
use Cake\Core\InstanceConfigTrait;
24
use Cake\Database\Expression\QueryExpression;
25
use Cake\Utility\Hash;
26
27
/**
28
 * TranslateObjects command.
29
 * Translate objects from a language to another using a translator engine.
30
 * The translator engine is defined in the configuration.
31
 * The configuration must contain the translator engine class and options
32
 * I.e.:
33
 * 'Translators' => [
34
 *   'deepl' => [
35
 *      'name' => 'DeepL',
36
 *      'class' => '\BEdita\I18n\Deepl\Core\Translator',
37
 *      'options' => [
38
 *        'auth_key' => '************',
39
 *      ],
40
 *   ],
41
 * ],
42
 */
43
class TranslateObjectsCommand extends Command
44
{
45
    use InstanceConfigTrait;
46
47
    protected $_defaultConfig = [
48
        'langsMap' => [
49
            'en' => 'en-US',
50
            'it' => 'it-IT',
51
            'de' => 'de-DE',
52
            'es' => 'es-ES',
53
            'fr' => 'fr-FR',
54
            'pt' => 'pt-PT',
55
        ],
56
        'status' => 'draft',
57
        'dryRun' => false,
58
    ];
59
    protected $ok;
60
    protected $error;
61
    protected $io;
62
    protected $dryRun;
63
    protected $defaultStatus;
64
    protected $translatableFields = [];
65
    protected $translator;
66
    protected $langsMap;
67
68
    /**
69
     * @inheritDoc
70
     */
71
    public function __construct()
72
    {
73
        parent::__construct();
74
        $cfg = (array)Configure::read('TranslateObjects');
75
        $cfg = array_merge($this->_defaultConfig, $cfg);
76
        $this->defaultStatus = (string)Hash::get($cfg, 'status');
77
        $this->dryRun = (int)Hash::get($cfg, 'dryRun');
78
        $this->langsMap = (array)Hash::get($cfg, 'langsMap');
79
    }
80
81
    /**
82
     * @inheritDoc
83
     */
84
    public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
85
    {
86
        $langs = array_keys($this->langsMap);
87
        $parser = parent::buildOptionParser($parser);
88
        $parser->addOption('from', [
89
            'short' => 'f',
90
            'help' => 'Language to translate from',
91
            'required' => true,
92
            'choices' => $langs,
93
        ]);
94
        $parser->addOption('to', [
95
            'short' => 't',
96
            'help' => 'Language to translate to',
97
            'required' => true,
98
            'choices' => $langs,
99
        ]);
100
        $parser->addOption('engine', [
101
            'short' => 'e',
102
            'help' => 'Translator engine',
103
            'default' => 'deepl',
104
            'required' => true,
105
            'choices' => ['aws', 'deepl', 'google', 'microsoft'],
106
        ]);
107
        $parser->addOption('status', [
108
            'short' => 's',
109
            'help' => 'Status for new translations',
110
            'choices' => ['draft', 'on', 'off'],
111
            'default' => 'draft',
112
        ]);
113
        $parser->addOption('dry-run', [
114
            'short' => 'd',
115
            'help' => 'Dry run',
116
            'boolean' => true,
117
            'default' => false,
118
        ]);
119
120
        return $parser;
121
    }
122
123
    /**
124
     * @inheritDoc
125
     */
126
    public function execute(Arguments $args, ConsoleIo $io)
127
    {
128
        $this->io = $io;
129
        $this->dryRun = $args->getOption('dry-run');
130
131
        // parameter engine
132
        $engine = $args->getOption('engine') ?? 'deepl';
133
134
        // setup translator engine
135
        $cfg = Configure::read(sprintf('Translators.%s', $engine));
136
        if (empty($cfg)) {
137
            $this->io->abort(sprintf('Translator %s not found', $engine));
138
        }
139
        $class = (string)Hash::get($cfg, 'class');
140
        $options = (array)Hash::get($cfg, 'options');
141
        $this->translator = new $class();
142
        $this->translator->setup($options);
143
144
        // parameters: lang from, lang to
145
        $from = $args->getOption('from');
146
        $to = $args->getOption('to');
147
        $this->io->out(sprintf('Translating objects from %s to %s [dry-run %s]', $from, $to, $this->dryRun ? 'yes' : 'no'));
148
        $to = $this->langsMap[$to];
149
        if ($this->io->ask('Do you want to continue [Y/n]?', 'n') !== 'Y') {
150
            $this->io->abort('Bye');
151
        }
152
        $this->ok = $this->error = 0;
153
        $this->defaultStatus = $args->getOption('status');
154
        $this->processObjects($from, $to);
155
        $this->io->out(sprintf('Processed %d objects (%d errors)', $this->ok + $this->error, $this->error));
156
        $this->io->out('Done');
157
    }
158
159
    /**
160
     * Process objects to translate.
161
     *
162
     * @param string $from The language to translate from
163
     * @param string $to The language to translate to
164
     * @return void
165
     */
166
    private function processObjects(string $from, string $to)
167
    {
168
        $conditions = [];
169
        foreach ($this->objectsIterator($conditions, $from, $to) as $object) {
170
            try {
171
                $this->io->verbose(sprintf('Translating object %s', $object->id));
172
                if (!$this->dryRun) {
173
                    $this->translate($object, $from, $to);
174
                }
175
                $this->io->verbose(sprintf('Translated object %s', $object->id));
176
                $this->ok++;
177
            } catch (\Exception $e) {
178
                $this->io->error(sprintf('Error translating object %s: %s', $object->id, $e->getMessage()));
179
                $this->error++;
180
            }
181
        }
182
    }
183
184
    /**
185
     * Get objects as iterable.
186
     *
187
     * @param array $conditions The conditions to filter objects.
188
     * @param string $lang The language to use to find objects.
189
     * @param string $to The language to translate objects to.
190
     * @return iterable
191
     */
192
    private function objectsIterator(array $conditions, string $lang, string $to): iterable
193
    {
194
        $table = $this->fetchTable('objects');
195
        $conditions = array_merge(
196
            $conditions,
197
            [
198
                $table->aliasField('deleted') => 0,
199
                $table->aliasField('lang') => $lang,
200
            ]
201
        );
202
        $query = $table->find('all')
203
            ->where($conditions)
204
            ->notMatching('Translations', function ($q) use ($to) {
205
                return $q->where(['Translations.lang' => $to]);
206
            })
207
            ->orderAsc($table->aliasField('id'))
208
            ->limit(500);
209
        $lastId = 0;
210
        while (true) {
211
            $q = clone $query;
212
            $q = $q->where(fn (QueryExpression $exp): QueryExpression => $exp->gt($table->aliasField('id'), $lastId));
213
            $results = $q->all();
214
            if ($results->isEmpty()) {
215
                break;
216
            }
217
218
            foreach ($results as $entity) {
219
                $lastId = $entity->id;
220
221
                yield $entity;
222
            }
223
        }
224
    }
225
226
    /**
227
     * Translate object translatable fields and store translation in translations table.
228
     *
229
     * @param \BEdita\Core\Model\Entity\ObjectEntity $object The object to translate
230
     * @param string $from The language to translate from
231
     * @param string $to The language to translate to
232
     * @return void
233
     */
234
    protected function translate($object, $from, $to): void
235
    {
236
        $translatableFields = $this->translatableFields($object->type);
237
        if (empty($translatableFields)) {
238
            return;
239
        }
240
        $translatedFields = [];
241
        foreach ($translatableFields as $field) {
242
            if (empty($object->get($field))) {
243
                continue;
244
            }
245
            $translatedFields[$field] = $this->singleTranslation($object->get($field), $from, $to);
246
        }
247
        $translation = [
248
            'object_id' => $object->id,
249
            'lang' => array_flip($this->langsMap)[$to],
250
            'translated_fields' => json_encode($translatedFields),
251
            'status' => $this->defaultStatus,
252
        ];
253
        $table = $this->fetchTable('Translations');
254
        $entity = $table->newEntity($translation);
255
        $entity->set('translated_fields', json_decode($translation['translated_fields'], true));
256
        $entity->set('status', $this->defaultStatus);
257
        LoggedUser::setUserAdmin();
258
        $table->saveOrFail($entity);
259
    }
260
261
    /**
262
     * Get translatable fields by object type.
263
     *
264
     * @param string $type The object type
265
     * @return array
266
     */
267
    protected function translatableFields(string $type): array
268
    {
269
        if (array_key_exists($type, $this->translatableFields)) {
270
            return $this->translatableFields[$type];
271
        }
272
        /** @var \BEdita\Core\Model\Entity\ObjectType $objectType */
273
        $objectType = $this->fetchTable('ObjectTypes')->find()->where(['name' => $type])->firstOrFail();
274
        $schema = $objectType->get('schema');
275
        $this->translatableFields[$type] = (array)Hash::get($schema, 'translatable');
276
277
        return $this->translatableFields[$type];
278
    }
279
280
    /**
281
     * Translate a single text.
282
     *
283
     * @param mixed $text The text to translate
284
     * @param string $from The language to translate from
285
     * @param string $to The language to translate to
286
     * @return string
287
     */
288
    protected function singleTranslation($text, string $from, string $to): string
289
    {
290
        $response = $this->translator->translate([$text], $from, $to);
291
        $response = json_decode($response, true);
292
293
        return (string)Hash::get($response, 'translation.0');
294
    }
295
}
296