-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslatableEntityHandler.php
More file actions
79 lines (63 loc) · 2.43 KB
/
TranslatableEntityHandler.php
File metadata and controls
79 lines (63 loc) · 2.43 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
<?php
declare(strict_types=1);
namespace Tmi\TranslationBundle\Translation\Handlers;
use Doctrine\ORM\EntityManagerInterface;
use Tmi\TranslationBundle\Doctrine\Model\TranslatableInterface;
use Tmi\TranslationBundle\Translation\Args\TranslationArgs;
use Tmi\TranslationBundle\Utils\AttributeHelper;
final readonly class TranslatableEntityHandler implements TranslationHandlerInterface
{
public function __construct(
private EntityManagerInterface $entityManager,
private DoctrineObjectHandler $doctrineObjectHandler,
private AttributeHelper $attributeHelper,
) {
}
public function supports(TranslationArgs $args): bool
{
return $args->getDataToBeTranslated() instanceof TranslatableInterface;
}
/**
* @throws \ReflectionException
*/
public function handleSharedAmongstTranslations(TranslationArgs $args): TranslatableInterface
{
return $this->translate($args);
}
public function handleEmptyOnTranslate(TranslationArgs $args): null
{
return null;
}
/**
* @throws \ReflectionException
*/
public function translate(TranslationArgs $args): TranslatableInterface
{
$data = $args->getDataToBeTranslated();
\assert($data instanceof TranslatableInterface);
// Search in database if the content exists, otherwise translate it.
$existingTranslation = $this->entityManager->getRepository($data::class)->findOneBy([
'locale' => $args->getTargetLocale(),
'tuuid' => (string) $data->getTuuid(),
]);
if ($existingTranslation instanceof TranslatableInterface) {
return $existingTranslation;
}
$clone = clone $data;
$subArgs = new TranslationArgs($clone, $clone->getLocale(), $args->getTargetLocale());
$subArgs->setCopySource($args->getCopySource());
$this->doctrineObjectHandler->translateProperties($subArgs);
$this->resetGeneratedIds($clone);
$clone->setLocale($args->getTargetLocale());
return $clone;
}
private function resetGeneratedIds(TranslatableInterface $clone): void
{
$reflection = new \ReflectionClass($clone);
foreach ($reflection->getProperties() as $property) {
if ($this->attributeHelper->isId($property) && $this->attributeHelper->isGeneratedValue($property)) {
$property->setValue($clone, null);
}
}
}
}