-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntityTranslator.php
More file actions
387 lines (320 loc) · 14.6 KB
/
EntityTranslator.php
File metadata and controls
387 lines (320 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
<?php
declare(strict_types=1);
namespace Tmi\TranslationBundle\Translation;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Tmi\TranslationBundle\Doctrine\Model\TranslatableInterface;
use Tmi\TranslationBundle\Event\TranslateEvent;
use Tmi\TranslationBundle\Translation\Args\TranslationArgs;
use Tmi\TranslationBundle\Translation\Cache\TranslationCacheInterface;
use Tmi\TranslationBundle\Translation\Handlers\TranslationHandlerInterface;
use Tmi\TranslationBundle\Utils\AttributeHelper;
final class EntityTranslator implements EntityTranslatorInterface
{
/** @var array<TranslationHandlerInterface> */
private array $handlers = [];
private LoggerInterface|null $logger = null;
/**
* @param array<string> $locales
*/
public function __construct(
#[Autowire(param: 'tmi_translation.default_locale')]
private readonly string $defaultLocale,
private readonly array $locales,
private readonly bool $copySource,
private readonly EventDispatcherInterface $eventDispatcher,
private readonly AttributeHelper $attributeHelper,
private readonly TypeDefaultResolver $typeDefaultResolver,
private readonly EntityManagerInterface $entityManager,
private readonly TranslationCacheInterface $cache,
LoggerInterface|null $logger = null,
) {
$this->logger = $logger;
}
public function setLogger(LoggerInterface|null $logger): void
{
$this->logger = $logger;
}
public function translate(TranslatableInterface $entity, string $locale): TranslatableInterface
{
$this->logInfo('Starting translation of {class}', [
'class' => $entity::class,
'source_locale' => $entity->getLocale(),
'target_locale' => $locale,
]);
$result = $this->processTranslation(new TranslationArgs($entity, $entity->getLocale(), $locale));
\assert($result instanceof TranslatableInterface);
return $result;
}
public function translateAndPersist(TranslatableInterface $entity, string $locale): TranslatableInterface
{
$result = $this->translate($entity, $locale);
$this->entityManager->persist($result);
return $result;
}
public function getOrTranslate(TranslatableInterface $entity, string $locale): TranslatableInterface
{
$result = $this->translate($entity, $locale);
if (!$this->entityManager->contains($result)) {
$this->entityManager->persist($result);
}
return $result;
}
/**
* Process translation for a given entity or property.
*
* This method handles:
* - Top-level entity translation
* - Properties with #[SharedAmongstTranslations] or #[EmptyOnTranslate]
* - Embedded properties that may contain shared or empty attributes internally
*
* @param TranslationArgs $args contains the entity or property to translate, source/target locales, and parent entity
*
* @return mixed Translated entity, embedded, or property value according to attribute rules
*/
public function processTranslation(TranslationArgs $args): mixed
{
$entity = $args->getDataToBeTranslated();
$locale = $args->getTargetLocale() ?? $this->defaultLocale;
// Validate that the requested locale is allowed
if (!in_array($locale, $this->locales, true)) {
throw new \LogicException(sprintf('Locale "%s" is not allowed. Allowed locales: %s', $locale, implode(', ', $this->locales)));
}
// Handle top-level entities that implement TranslatableInterface
if ($entity instanceof TranslatableInterface) {
$tuuidValue = $entity->getTuuid()->getValue();
// Return cached translation immediately if available
if ($this->cache->has($tuuidValue, $locale)) {
return $this->cache->get($tuuidValue, $locale);
}
// Detect cycles to avoid infinite recursion
if ($this->cache->isInProgress($tuuidValue, $locale)) {
return $entity;
}
// Resolve copySource per entity (entity-level override or global config)
if (null === $args->getCopySource()) {
$args->setCopySource($this->resolveCopySource($entity));
}
// Mark as in-progress with auto-cleanup guarantee
$this->cache->markInProgress($tuuidValue, $locale);
try {
$this->warmupTranslations([$entity], $locale);
if ($this->cache->has($tuuidValue, $locale)) {
$this->cache->unmarkInProgress($tuuidValue, $locale);
return $this->cache->get($tuuidValue, $locale);
}
} catch (\Throwable $e) {
$this->cache->unmarkInProgress($tuuidValue, $locale);
throw $e;
}
}
// Iterate through all registered translation handlers
foreach ($this->handlers as $handler) {
if (!$handler->supports($args)) {
continue;
}
// Handle attribute logic if a specific property is set in TranslationArgs
$property = $args->getProperty();
$this->logDebug('Handler selected for processing', [
'handler' => $handler::class,
'property' => $property?->name,
'data_type' => is_object($entity) ? $entity::class : gettype($entity),
]);
// Dispatch PRE_TRANSLATE event for top-level entities
if ($entity instanceof TranslatableInterface) {
$this->eventDispatcher->dispatch(
new TranslateEvent($entity, $locale),
TranslateEvent::PRE_TRANSLATE,
);
}
if ($property instanceof \ReflectionProperty) {
// Validate property attributes for conflicts
$this->attributeHelper->validateProperty($property, $this->logger);
// 1. Determine if the top-level property is Shared (always copies from source)
if ($this->attributeHelper->isSharedAmongstTranslations($property)) {
$this->logDebug('Attribute detected: SharedAmongstTranslations', [
'property' => $property->name,
'class' => $property->class,
'action' => 'sharing value across translations',
]);
return $handler->handleSharedAmongstTranslations($args);
}
// 2. Handle copy_source: false -- type-safe defaults for all non-shared fields
if (false === $args->getCopySource()) {
// Embedded properties: delegate to handler for per-property resolution
if ($this->attributeHelper->isEmbedded($property)) {
if ($this->attributeHelper->isEmptyOnTranslate($property)) {
$this->logDebug('EmptyOnTranslate has no effect when copy_source is false', [
'property' => $property->name,
'class' => $property->class,
]);
}
return $handler->translate($args);
}
// Log redundancy hint if EmptyOnTranslate is present
if ($this->attributeHelper->isEmptyOnTranslate($property)) {
$this->logDebug('EmptyOnTranslate has no effect when copy_source is false', [
'property' => $property->name,
'class' => $property->class,
]);
}
// Non-nullable object safety fallback: copy from source
$type = $property->getType();
if ($type instanceof \ReflectionNamedType && !$type->isBuiltin() && !$type->allowsNull()) {
$this->logDebug(\sprintf(
'Property %s::$%s is non-nullable object -- copying from source despite copy_source: false',
$property->class,
$property->name,
), []);
return $handler->translate($args);
}
// Resolve type-safe default
$default = $this->typeDefaultResolver->resolve($property);
$this->logDebug('Type-safe default for copy_source: false', [
'property' => $property->name,
'class' => $property->class,
]);
return $default;
}
// 3. Handle EmptyOnTranslate (copy_source: true path)
if ($this->attributeHelper->isEmptyOnTranslate($property)) {
if (!$this->attributeHelper->isNullable($property)) {
// Type-safe default instead of throwing
$default = $this->typeDefaultResolver->resolve($property);
$this->logDebug('Type-safe default for non-nullable EmptyOnTranslate property', [
'property' => $property->name,
'class' => $property->class,
'default' => $default,
]);
return $default;
}
$this->logDebug('Attribute detected: EmptyOnTranslate', [
'property' => $property->name,
'class' => $property->class,
'action' => 'clearing value for translation',
]);
return $handler->handleEmptyOnTranslate($args);
}
// Handle embeddable with unified per-property resolution
if ($this->attributeHelper->isEmbedded($property)) {
$this->logDebug('Processing embedded property with per-property resolution', [
'property' => $property->name,
'class' => $property->class,
]);
return $handler->translate($args);
}
}
$translated = $handler->translate($args);
if ($entity instanceof TranslatableInterface && $translated instanceof TranslatableInterface) {
$this->eventDispatcher->dispatch(
new TranslateEvent($entity, $locale, $translated),
TranslateEvent::POST_TRANSLATE,
);
$this->cache->set($translated->getTuuid()->getValue(), $translated->getLocale() ?? $locale, $translated);
$this->cache->unmarkInProgress($entity->getTuuid()->getValue(), $locale);
$this->logDebug('Translation complete', [
'class' => $translated::class,
'target_locale' => $translated->getLocale(),
]);
}
return $translated;
}
return $entity;
}
public function addTranslationHandler(TranslationHandlerInterface $handler, int|null $priority = null): void
{
if (null === $priority) {
$this->handlers[] = $handler;
} else {
$this->handlers[$priority] = $handler;
}
}
// --- EntityTranslatorInterface Hooks ---
public function afterLoad(TranslatableInterface $entity): void
{
$this->translate($entity, $entity->getLocale() ?? $this->defaultLocale);
}
public function beforePersist(TranslatableInterface $entity): void
{
$this->translate($entity, $entity->getLocale() ?? $this->defaultLocale);
}
public function beforeUpdate(TranslatableInterface $entity): void
{
$this->translate($entity, $entity->getLocale() ?? $this->defaultLocale);
}
public function beforeRemove(TranslatableInterface $entity): void
{
$this->translate($entity, $entity->getLocale() ?? $this->defaultLocale);
}
/**
* @param array<string, mixed> $context
*/
private function logDebug(string $message, array $context = []): void
{
if (null === $this->logger) {
return;
}
$this->logger->debug('[TMI Translation] '.$message, $context);
}
/**
* @param array<string, mixed> $context
*/
private function logInfo(string $message, array $context = []): void
{
if (null === $this->logger) {
return;
}
$this->logger->info('[TMI Translation] '.$message, $context);
}
/**
* Resolves copySource for an entity: per-entity attribute overrides global config.
*/
private function resolveCopySource(object $entity): bool
{
$attribute = $this->attributeHelper->getTranslatableAttribute(new \ReflectionClass($entity));
if (null !== $attribute && null !== $attribute->copySource) {
return $attribute->copySource;
}
return $this->copySource;
}
/**
* Batch-load translations for given entities and target locale.
*
* @param array<mixed> $entities
*/
private function warmupTranslations(array $entities, string $locale): void
{
/** @var array<class-string, list<string>> $byClass */
$byClass = [];
foreach ($entities as $entity) {
if (!$entity instanceof TranslatableInterface) {
continue;
}
$tuuid = $entity->getTuuid()->getValue();
if ($this->cache->has($tuuid, $locale)) {
continue;
}
$byClass[$entity::class][] = $tuuid;
}
foreach ($byClass as $class => $tuuids) {
$qb = $this->entityManager->createQueryBuilder()
->select('t')
->from($class, 't')
->where('t.tuuid IN (:tuuids)')
->andWhere('t.locale = :locale')
->setParameter('tuuids', $tuuids)
->setParameter('locale', $locale);
/** @var array<TranslatableInterface>|null $translations */
$translations = $qb->getQuery()->getResult();
foreach ($translations ?? [] as $translation) {
$this->cache->set(
$translation->getTuuid()->getValue(),
$translation->getLocale() ?? $locale,
$translation,
);
}
}
}
}