-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTranslatableClassMetadata.php
More file actions
333 lines (273 loc) · 13.6 KB
/
TranslatableClassMetadata.php
File metadata and controls
333 lines (273 loc) · 13.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
<?php
/*
* (c) webfactory GmbH <info@webfactory.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webfactory\Bundle\PolyglotBundle\Doctrine;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\Persistence\Mapping\RuntimeReflectionService;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use ReflectionClass;
use ReflectionProperty;
use RuntimeException;
use Webfactory\Bundle\PolyglotBundle\Attribute;
use Webfactory\Bundle\PolyglotBundle\Locale\DefaultLocaleProvider;
use Webfactory\Bundle\PolyglotBundle\Translatable;
/**
* For an entity class that contains #[Translatable] attributes, this class holds metadata
* like which fields in the class are #[Translatable]s, which field holds the collection
* of translations etc. There need only be one instance of this class for every
* entity class with translations.
*/
final class TranslatableClassMetadata
{
/**
* Ein Mapping von Feldnamen in der Hauptklasse auf die Felder in der
* Übersetzungs-Klasse, in denen die jeweilige Übersetzung liegt.
*
* @var array<string, ReflectionProperty>
*/
private array $translationFieldMapping = [];
/**
* Die Eigenschaften der Haupt-Klasse, die übersetzbar sind; indiziert nach Feldnamen.
*
* @var array<string, ReflectionProperty>
*/
private array $translatedProperties = [];
/**
* Die Eigenschaft der Haupt-Klasse, die die Collection der Übersetzungen hält.
*/
private ?ReflectionProperty $translationsCollectionProperty = null;
/**
* Die Eigenschaft der Übersetzungs-Klasse, die als many-to-one auf die Haupt-Klasse verweist.
*/
private ?ReflectionProperty $translationMappingProperty = null;
/**
* Die Eigenschaft in der Übersetzungs-Klasse, die die Sprache einer Übersetzungsinstanz enhtält.
*/
private ?ReflectionProperty $translationLocaleProperty = null;
/**
* Die Übersetzungs-Klasse.
*/
private ?ReflectionClass $translationClass = null;
/**
* Die Locale der Werte in der Haupt-Klasse.
*/
private ?string $primaryLocale = null;
private ?LoggerInterface $logger = null;
/**
* @param class-string $class The FQCN for the entity class whose translatable fields are described by this
* TranslatableClassMetadata instance. If the class has base entity classes (or mapped
* superclasses), a separate instance of TranslatableClassMetadata will be used for
* their fields.
*/
private function __construct(
private readonly string $class,
) {
}
public static function parseFromClass(string $class, ClassMetadataFactory $classMetadataFactory): ?self
{
/** @var ClassMetadata $cm */
$cm = $classMetadataFactory->getMetadataFor($class);
$tm = new static($class);
$tm->findPrimaryLocale($cm);
$tm->findTranslationsCollection($cm, $classMetadataFactory);
$tm->findTranslatedProperties($cm, $classMetadataFactory);
if ($tm->isClassWithoutTranslations()) {
return null;
}
$tm->assertAttributesAreComplete($class);
return $tm;
}
public function setLogger(?LoggerInterface $logger = null): void
{
$this->logger = $logger;
}
public function sleep(): SerializedTranslatableClassMetadata
{
$sleep = new SerializedTranslatableClassMetadata();
$sleep->class = $this->class;
$sleep->primaryLocale = $this->primaryLocale;
$sleep->translationClass = $this->translationClass->name;
foreach ($this->translationFieldMapping as $fieldname => $property) {
$sleep->translationFieldMapping[$fieldname] = [$property->class, $property->name];
}
foreach ($this->translatedProperties as $fieldname => $property) {
$sleep->translatedProperties[$fieldname] = [$property->class, $property->name];
}
$sleep->translationLocaleProperty = [$this->translationLocaleProperty->class, $this->translationLocaleProperty->name];
$sleep->translationsCollectionProperty = [$this->translationsCollectionProperty->class, $this->translationsCollectionProperty->name];
$sleep->translationMappingProperty = [$this->translationMappingProperty->class, $this->translationMappingProperty->name];
return $sleep;
}
public static function wakeup(SerializedTranslatableClassMetadata $data, RuntimeReflectionService $reflectionService): self
{
$self = new self($data->class);
$self->primaryLocale = $data->primaryLocale;
$self->translationClass = $reflectionService->getClass($data->translationClass);
foreach ($data->translationFieldMapping as $fieldname => $property) {
$self->translationFieldMapping[$fieldname] = $reflectionService->getAccessibleProperty(...$property);
}
foreach ($data->translatedProperties as $fieldname => $property) {
$self->translatedProperties[$fieldname] = $reflectionService->getAccessibleProperty(...$property);
}
$self->translationsCollectionProperty = $reflectionService->getAccessibleProperty(...$data->translationsCollectionProperty);
$self->translationMappingProperty = $reflectionService->getAccessibleProperty(...$data->translationMappingProperty);
$self->translationLocaleProperty = $reflectionService->getAccessibleProperty(...$data->translationLocaleProperty);
return $self;
}
private function isClassWithoutTranslations(): bool
{
return null === $this->translationClass
&& null === $this->translationLocaleProperty
&& null === $this->translationMappingProperty
&& 0 === \count($this->translatedProperties);
}
private function assertAttributesAreComplete(string $class): void
{
if (null === $this->translationClass) {
throw new RuntimeException(\sprintf('Unable to find the translations for %s. There should be a one-to-may collection holding the translation entities, and it should be marked with %s.', $class, Attribute\TranslationCollection::class));
}
if (null === $this->translationLocaleProperty) {
throw new RuntimeException('The #[Polyglot\Locale] attribute at the language property of the translation class is missing or incorrect');
}
if (null === $this->translationMappingProperty) {
throw new RuntimeException('The property referenced in the mappedBy-property of the #[ORM\OneToMany(..., mappedBy: "...")] is missing or incorrect');
}
if (0 === \count($this->translatedProperties)) {
throw new RuntimeException('No translatable properties attributed with #[Polyglot\Translatable] (at the property level) or #[Polyglot\TranslatedProperty] (at the class level) were found');
}
if (null === $this->primaryLocale) {
throw new RuntimeException(\sprintf('Class %s uses translations, so it needs to provide the primary locale with the %s attribute at the class level. This can either be at the class itself, or in one of its parent classes.', $class, Attribute\Locale::class));
}
}
private function findTranslatedProperties(ClassMetadata $cm, ClassMetadataFactory $classMetadataFactory): void
{
if (!$this->translationClass) {
return;
}
$reflectionService = $classMetadataFactory->getReflectionService();
$translationClassMetadata = $classMetadataFactory->getMetadataFor($this->translationClass->getName());
$reflectionClass = $cm->getReflectionClass();
/*
Collect all (propertyName => translationFieldname) candidates from both sources.
Using propertyName as key ensures deduplication when both sources declare the same property.
*/
$candidates = []; // propertyName => translationFieldname|null
/* Property-level #[Translatable] attributes */
foreach ($reflectionClass->getProperties() as $reflectionProperty) {
$attributes = $reflectionProperty->getAttributes(Attribute\Translatable::class);
if (!$attributes || $this->isDeclaredByParentEntity($reflectionProperty, $cm)) {
continue;
}
$candidates[$reflectionProperty->name] = $attributes[0]->newInstance()->getTranslationFieldname();
}
/* Class-level #[TranslatedProperty] attributes */
foreach ($reflectionClass->getAttributes(Attribute\TranslatedProperty::class) as $classAttribute) {
$attribute = $classAttribute->newInstance();
$propertyName = $attribute->getPropertyName();
if (!$reflectionClass->hasProperty($propertyName)) {
throw new InvalidArgumentException(\sprintf('Property "%s" not found in class "%s" (declared via #[TranslatedProperty]).', $propertyName, $cm->name));
}
if ($this->isDeclaredByParentEntity($reflectionClass->getProperty($propertyName), $cm)) {
continue;
}
$candidates[$propertyName] = $attribute->getTranslationFieldname();
}
/* Register all collected candidates */
foreach ($candidates as $propertyName => $translationFieldname) {
$this->translatedProperties[$propertyName] = $reflectionService->getAccessibleProperty($cm->name, $propertyName);
$this->translationFieldMapping[$propertyName] = $reflectionService->getAccessibleProperty($translationClassMetadata->name, $translationFieldname ?: $propertyName);
}
}
private function findTranslationsCollection(ClassMetadata $cm, ClassMetadataFactory $classMetadataFactory): void
{
foreach ($cm->associationMappings as $fieldName => $mapping) {
if (isset($mapping['declared'])) {
// The association is inherited from a parent class
continue;
}
$reflectionProperty = $cm->getReflectionProperty($fieldName);
if ($reflectionProperty->getAttributes(Attribute\TranslationCollection::class)) {
$this->translationsCollectionProperty = $reflectionProperty;
$translationEntityMetadata = $classMetadataFactory->getMetadataFor($mapping['targetEntity']);
$this->translationClass = $translationEntityMetadata->getReflectionClass();
$this->translationMappingProperty = $translationEntityMetadata->getReflectionProperty($mapping['mappedBy']);
$this->parseTranslationsEntity($translationEntityMetadata);
return;
}
}
}
private function findPrimaryLocale(ClassMetadata $cm): void
{
foreach (array_merge([$cm->name], $cm->parentClasses) as $class) {
$reflectionClass = new ReflectionClass($class);
foreach ($reflectionClass->getAttributes(Attribute\Locale::class) as $attribute) {
$this->primaryLocale = $attribute->newInstance()->getPrimary();
return;
}
}
}
/*
Returns true if the property is declared in a parent class that is already covered
by our parent entity's metadata, so we need not include it again.
*/
private function isDeclaredByParentEntity(ReflectionProperty $property, ClassMetadata $cm): bool
{
$declaringClass = $property->getDeclaringClass()->name;
return $declaringClass !== $cm->name && $cm->parentClasses && is_a($cm->parentClasses[0], $declaringClass, true);
}
private function parseTranslationsEntity(ClassMetadata $cm): void
{
foreach ($cm->fieldMappings as $fieldName => $mapping) {
$reflectionProperty = $cm->getReflectionProperty($fieldName);
if ($reflectionProperty->getAttributes(Attribute\Locale::class)) {
$this->translationLocaleProperty = $reflectionProperty;
return;
}
}
}
/**
* For a given entity, find all @Translatable fields that contain new (not yet persisted)
* Translatable objects and replace those with PersistentTranslatable.
*/
public function injectNewPersistentTranslatables(object $entity, EntityManager $entityManager, DefaultLocaleProvider $defaultLocaleProvider): void
{
foreach ($this->translatedProperties as $fieldName => $property) {
$persistentTranslatable = new PersistentTranslatable(
$entityManager->getUnitOfWork(),
$this->class,
$entity,
$this->primaryLocale,
$defaultLocaleProvider,
$this->translationFieldMapping[$fieldName],
$this->translationsCollectionProperty,
$this->translationClass,
$this->translationLocaleProperty,
$this->translationMappingProperty,
$property,
$this->logger
);
$persistentTranslatable->inject();
}
}
/**
* @return list<PersistentTranslatable>
*/
public function ejectPersistentTranslatables(object $entity): array
{
$ejectedTranslatables = [];
foreach ($this->translatedProperties as $property) {
$persistentTranslatable = $property->getValue($entity);
\assert($persistentTranslatable instanceof PersistentTranslatable);
$persistentTranslatable->eject();
$ejectedTranslatables[] = $persistentTranslatable;
}
return $ejectedTranslatables;
}
}