-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmbeddedHandler.php
More file actions
309 lines (258 loc) · 10.8 KB
/
EmbeddedHandler.php
File metadata and controls
309 lines (258 loc) · 10.8 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
<?php
declare(strict_types=1);
namespace Tmi\TranslationBundle\Translation\Handlers;
use Psr\Log\LoggerInterface;
use Tmi\TranslationBundle\Translation\Args\TranslationArgs;
use Tmi\TranslationBundle\Translation\TypeDefaultResolver;
use Tmi\TranslationBundle\Utils\AttributeHelper;
/**
* Handler for Doctrine embeddable objects.
*
* Uses per-property resolution where each embedded property resolves independently
* through a three-level cascade (entity-property -> embeddable-property -> embeddable-class).
*
* Resolution order (highest priority first):
* 1. Property-level attribute (on the embeddable's property itself)
* 2. Class-level attribute (on the embeddable class)
* 3. Default: use class default value
*/
final class EmbeddedHandler implements TranslationHandlerInterface
{
private LoggerInterface|null $logger = null;
public function __construct(
private readonly AttributeHelper $attributeHelper,
private readonly TypeDefaultResolver $typeDefaultResolver,
LoggerInterface|null $logger = null,
) {
$this->logger = $logger;
}
public function setLogger(LoggerInterface|null $logger): void
{
$this->logger = $logger;
}
public function supports(TranslationArgs $args): bool
{
return null !== $args->getProperty() && $this->attributeHelper->isEmbedded($args->getProperty());
}
/**
* Handle #[SharedAmongstTranslations] for embeddable.
*
* If the embeddable is marked shared (via parent property, class, or inner property)
* then return the same instance so siblings share it.
* If not shared, return a clone so each locale gets its own copy.
*
* @throws \ReflectionException
*/
public function handleSharedAmongstTranslations(TranslationArgs $args): mixed
{
$embeddable = $args->getDataToBeTranslated();
assert(\is_object($embeddable));
if ($this->isShared($args)) {
return $embeddable;
}
return clone $embeddable;
}
/**
* Handle #[EmptyOnTranslate] for embeddable.
*
* @throws \ReflectionException
*/
public function handleEmptyOnTranslate(TranslationArgs $args): mixed
{
$embeddable = $args->getDataToBeTranslated();
assert(\is_object($embeddable));
$parentProperty = $args->getProperty();
if (null !== $parentProperty && $this->attributeHelper->isEmptyOnTranslate($parentProperty)) {
return null;
}
$clone = clone $embeddable;
$reflection = new \ReflectionClass($clone);
$changed = false;
foreach ($reflection->getProperties() as $prop) {
if ($this->attributeHelper->isSharedAmongstTranslations($prop)) {
continue;
}
if ($this->attributeHelper->isEmptyOnTranslate($prop)) {
$this->clearProperty($clone, $prop);
$changed = true;
}
}
return $changed ? $clone : $embeddable;
}
/**
* Unified per-property resolution for embedded objects.
*
* Clones the embedded object and resolves each property through the three-level cascade:
* 1. Property-level attribute (most specific)
* 2. Class-level attribute (default for all properties)
* 3. No attribute: reset to class default value
*
* @throws \ReflectionException
*/
public function translate(TranslationArgs $args): mixed
{
$embeddable = $args->getDataToBeTranslated();
assert(\is_object($embeddable));
$reflection = new \ReflectionClass($embeddable);
// Validate the embeddable class (cached after first call)
$this->attributeHelper->validateEmbeddableClass($reflection, $this->logger);
// Detect class-level attributes
$classShared = $this->attributeHelper->classHasSharedAmongstTranslations($reflection);
$classEmpty = $this->attributeHelper->classHasEmptyOnTranslate($reflection);
if ($classShared) {
$this->logDebug('Class-level attribute detected: SharedAmongstTranslations', [
'class' => $reflection->getName(),
]);
}
if ($classEmpty) {
$this->logDebug('Class-level attribute detected: EmptyOnTranslate', [
'class' => $reflection->getName(),
]);
}
// Clone the embedded object for selective modification
$clone = clone $embeddable;
foreach ($reflection->getProperties() as $prop) {
// Resolve effective attribute via three-level cascade
$resolved = $this->resolvePropertyAttribute($prop, $classShared, $classEmpty);
// SharedAmongstTranslations always keeps cloned value regardless of copySource
if ('shared' === $resolved) {
continue;
}
// copy_source: false -- all non-shared properties get type-safe defaults
if (false === $args->getCopySource()) {
if ($this->attributeHelper->isEmptyOnTranslate($prop)) {
$this->logDebug('EmptyOnTranslate has no effect on embedded property when copy_source is false', [
'property' => $prop->getName(),
]);
}
$this->applyTypeDefault($clone, $prop);
continue;
}
if ('empty' === $resolved) {
// Clear the property value
$this->clearProperty($clone, $prop);
continue;
}
// resolved === 'default' -- use the class default value (not copied from original)
$this->resetToDefault($clone, $prop);
}
return $clone;
}
/**
* Resolves the effective attribute for a property using the three-level cascade.
*
* @return string 'shared', 'empty', or 'default'
*/
private function resolvePropertyAttribute(
\ReflectionProperty $prop,
bool $classShared,
bool $classEmpty,
): string {
$propShared = $this->attributeHelper->isSharedAmongstTranslations($prop);
$propEmpty = $this->attributeHelper->isEmptyOnTranslate($prop);
// Determine effective attribute
$classLevel = $classShared ? 'shared' : ($classEmpty ? 'empty' : 'none');
$propertyLevel = $propShared ? 'shared' : ($propEmpty ? 'empty' : 'none');
// Property overrides class (most specific wins)
if ('none' !== $propertyLevel) {
$resolved = $propertyLevel;
// Log override if class-level exists and differs
if ('none' !== $classLevel && $classLevel !== $propertyLevel) {
$this->logDebug('Property {property}: class={class_attr}, property={prop_attr} -> resolved: {resolved} (property override)', [
'property' => $prop->getName(),
'class_attr' => $classLevel,
'prop_attr' => $propertyLevel,
'resolved' => $resolved,
]);
} else {
$this->logDebug('Property {property}: class={class_attr}, property={prop_attr} -> resolved: {resolved}', [
'property' => $prop->getName(),
'class_attr' => $classLevel,
'prop_attr' => $propertyLevel,
'resolved' => $resolved,
]);
}
return $resolved;
}
// No property-level attribute: use class-level if present
if ('none' !== $classLevel) {
$this->logDebug('Property {property}: class={class_attr}, property=none -> resolved: {resolved}', [
'property' => $prop->getName(),
'class_attr' => $classLevel,
'resolved' => $classLevel,
]);
return $classLevel;
}
// No attribute at any level
$this->logDebug('Property {property}: class=none, property=none -> resolved: default', [
'property' => $prop->getName(),
]);
return 'default';
}
private function clearProperty(object $clone, \ReflectionProperty $prop): void
{
if (true !== $prop->getType()?->allowsNull()) {
// Non-nullable property: use type-safe default instead of null
$this->applyTypeDefault($clone, $prop);
return;
}
$setter = 'set'.ucfirst($prop->getName());
$reflection = new \ReflectionClass($clone);
if ($reflection->hasMethod($setter)) {
$reflection->getMethod($setter)->invoke($clone, null);
} else {
$prop->setValue($clone, null);
}
}
private function applyTypeDefault(object $clone, \ReflectionProperty $prop): void
{
try {
$default = $this->typeDefaultResolver->resolve($prop);
$prop->setValue($clone, $default);
} catch (\LogicException) {
// Non-nullable object/enum in embeddable: keep cloned value as safety fallback
$this->logDebug('Cannot resolve type-safe default for embedded property, keeping source value', [
'property' => $prop->getName(),
]);
}
}
private function resetToDefault(object $clone, \ReflectionProperty $prop): void
{
if ($prop->hasDefaultValue()) {
$prop->setValue($clone, $prop->getDefaultValue());
}
// If no default and not nullable, leave the cloned value as-is
}
/**
* Returns true when the embeddable should be shared across translations, i.e.:
* - the parent property is marked #[SharedAmongstTranslations], or
* - the embeddable class itself is marked #[SharedAmongstTranslations], or
* - any property inside the embeddable is marked #[SharedAmongstTranslations].
*
* @throws \ReflectionException
*/
private function isShared(TranslationArgs $args): bool
{
$embeddable = $args->getDataToBeTranslated();
assert(\is_object($embeddable));
// Parent property (on the entity)
$parentProperty = $args->getProperty();
if (null !== $parentProperty && $this->attributeHelper->isSharedAmongstTranslations($parentProperty)) {
return true;
}
// Class-level attribute on the embeddable
$reflection = new \ReflectionClass($embeddable);
if ($this->attributeHelper->classHasSharedAmongstTranslations($reflection)) {
return true;
}
// Any inner property marked shared
return array_any($reflection->getProperties(), $this->attributeHelper->isSharedAmongstTranslations(...));
}
/**
* @param array<string, mixed> $context
*/
private function logDebug(string $message, array $context = []): void
{
$this->logger?->debug('[TMI Translation][Embedded] '.$message, $context);
}
}