-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathTranslationRepository.php
More file actions
288 lines (258 loc) · 10.8 KB
/
Copy pathTranslationRepository.php
File metadata and controls
288 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
<?php
/*
* This file is part of the Doctrine Behavioral Extensions package.
* (c) Gediminas Morkevicius <gediminas.morkevicius@gmail.com> http://www.gediminasm.org
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Gedmo\Translatable\Entity\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query;
use Gedmo\Exception\InvalidArgumentException;
use Gedmo\Exception\RuntimeException;
use Gedmo\Exception\UnexpectedValueException;
use Gedmo\Tool\Wrapper\EntityWrapper;
use Gedmo\Translatable\Entity\MappedSuperclass\AbstractPersonalTranslation;
use Gedmo\Translatable\Mapping\Event\Adapter\ORM as TranslatableAdapterORM;
use Gedmo\Translatable\TranslatableListener;
/**
* The TranslationRepository has some useful functions
* to interact with translations.
*
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
*
* @phpstan-extends EntityRepository<object>
*/
class TranslationRepository extends EntityRepository
{
/**
* Current TranslatableListener instance used
* in EntityManager
*/
private ?TranslatableListener $listener = null;
public function __construct(EntityManagerInterface $em, ClassMetadata $class)
{
if ($class->getReflectionClass()->isSubclassOf(AbstractPersonalTranslation::class)) {
throw new UnexpectedValueException('This repository is useless for personal translations');
}
parent::__construct($em, $class);
}
/**
* Makes additional translation of $entity $field into $locale
* using $value
*
* @param object $entity
* @param string $field
* @param string $locale
* @param mixed $value
*
* @throws InvalidArgumentException
*
* @return static
*/
public function translate($entity, $field, $locale, $value)
{
$meta = $this->getEntityManager()->getClassMetadata(get_class($entity));
$listener = $this->getTranslatableListener();
$config = $listener->getConfiguration($this->getEntityManager(), $meta->getName());
if (!isset($config['fields']) || !in_array($field, $config['fields'], true)) {
throw new InvalidArgumentException("Entity: {$meta->getName()} does not translate field - {$field}");
}
$needsPersist = true;
if ($locale === $listener->getTranslatableLocale($entity, $meta, $this->getEntityManager())) {
$meta->setFieldValue($entity, $field, $value);
$this->getEntityManager()->persist($entity);
} else {
if (isset($config['translationClass'])) {
$class = $config['translationClass'];
} else {
$ea = new TranslatableAdapterORM();
$class = $listener->getTranslationClass($ea, $config['useObjectClass']);
}
$foreignKey = $meta->getFieldValue($entity, $meta->getSingleIdentifierFieldName());
$objectClass = $config['useObjectClass'];
$transMeta = $this->getEntityManager()->getClassMetadata($class);
$trans = $this->findOneBy([
'locale' => $locale,
'objectClass' => $objectClass,
'field' => $field,
'foreignKey' => $foreignKey,
]);
if (!$trans) {
$trans = $transMeta->newInstance();
$transMeta->setFieldValue($trans, 'foreignKey', $foreignKey);
$transMeta->setFieldValue($trans, 'objectClass', $objectClass);
$transMeta->setFieldValue($trans, 'field', $field);
$transMeta->setFieldValue($trans, 'locale', $locale);
}
if ($listener->getDefaultLocale() != $listener->getTranslatableLocale($entity, $meta, $this->getEntityManager())
&& $locale === $listener->getDefaultLocale()) {
$listener->setTranslationInDefaultLocale(spl_object_id($entity), $field, $trans);
$needsPersist = $listener->getPersistDefaultLocaleTranslation();
}
$transformed = $this->getEntityManager()->getConnection()->convertToDatabaseValue($value, $meta->getTypeOfField($field));
$transMeta->setFieldValue($trans, 'content', $transformed);
if ($needsPersist) {
if ($this->getEntityManager()->getUnitOfWork()->isInIdentityMap($entity)) {
$this->getEntityManager()->persist($trans);
} else {
$oid = spl_object_id($entity);
$listener->addPendingTranslationInsert($oid, $trans);
}
}
}
return $this;
}
/**
* Loads all translations with all translatable
* fields from the given entity
*
* @param object $entity Must implement Translatable
*
* @return array<string, array<string, string>> list of translations in locale groups
*/
public function findTranslations($entity)
{
$result = [];
$wrapped = new EntityWrapper($entity, $this->getEntityManager());
if ($wrapped->hasValidIdentifier()) {
$entityId = $wrapped->getIdentifier();
$config = $this
->getTranslatableListener()
->getConfiguration($this->getEntityManager(), $wrapped->getMetadata()->getName());
if (!$config) {
return $result;
}
$entityClass = $config['useObjectClass'];
$translationMeta = $this->getClassMetadata(); // table inheritance support
$translationClass = $config['translationClass'] ?? $translationMeta->rootEntityName;
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('trans.content, trans.field, trans.locale')
->from($translationClass, 'trans')
->where('trans.foreignKey = :entityId', 'trans.objectClass = :entityClass')
->orderBy('trans.locale')
->setParameter('entityId', $entityId)
->setParameter('entityClass', $entityClass);
foreach ($qb->getQuery()->toIterable([], Query::HYDRATE_ARRAY) as $row) {
$result[$row['locale']][$row['field']] = $row['content'];
}
}
return $result;
}
/**
* Find the entity $class by the translated field.
* Result is the first occurrence of translated field.
* Query can be slow, since there are no indexes on such
* columns
*
* @param string $field
* @param string $value
* @param string $class
*
* @phpstan-param class-string $class
*
* @return object instance of $class or null if not found
*/
public function findObjectByTranslatedField($field, $value, $class)
{
$entity = null;
$meta = $this->getEntityManager()->getClassMetadata($class);
$translationMeta = $this->getClassMetadata(); // table inheritance support
if ($meta->hasField($field)) {
$dql = "SELECT trans.foreignKey FROM {$translationMeta->rootEntityName} trans";
$dql .= ' WHERE trans.objectClass = :class';
$dql .= ' AND trans.field = :field';
$dql .= ' AND trans.content = :value';
$q = $this->getEntityManager()->createQuery($dql);
$q->setParameters([
'class' => $class,
'field' => $field,
'value' => $value,
]);
$q->setMaxResults(1);
$id = $q->getSingleScalarResult();
if (null !== $id) {
$entity = $this->getEntityManager()->find($class, $id);
}
}
return $entity;
}
/**
* Loads all translations with all translatable
* fields by a given entity primary key
*
* @param mixed $id primary key value of an entity
*
* @return array<string, array<string, string>>
*/
public function findTranslationsByObjectId($id)
{
$result = [];
if ($id) {
$translationMeta = $this->getClassMetadata(); // table inheritance support
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('trans.content, trans.field, trans.locale')
->from($translationMeta->rootEntityName, 'trans')
->where('trans.foreignKey = :entityId')
->orderBy('trans.locale')
->setParameter('entityId', $id);
$q = $qb->getQuery();
foreach ($q->toIterable([], Query::HYDRATE_ARRAY) as $row) {
$result[$row['locale']][$row['field']] = $row['content'];
}
}
return $result;
}
public function removeTranslations($entity, $field = null, $locale = null)
{
$wrapped = new EntityWrapper($entity, $this->getEntityManager());
if ($wrapped->hasValidIdentifier()) {
$entityId = $wrapped->getIdentifier();
$config = $this
->getTranslatableListener()
->getConfiguration($this->getEntityManager(), $wrapped->getMetadata()->getName());
if (!$config) {
return;
}
$entityClass = $config['useObjectClass'];
$translationMeta = $this->getClassMetadata(); // table inheritance support
$translationClass = $config['translationClass'] ?? $translationMeta->rootEntityName;
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->delete()
->from($translationClass, 'trans')
->where('trans.foreignKey = :entityId', 'trans.objectClass = :entityClass')
->setParameter('entityId', $entityId)
->setParameter('entityClass', $entityClass);
if ($field) {
$qb->andWhere('trans.field = :field')
->setParameter('field', $field);
}
if ($locale) {
$qb->andWhere('trans.locale = :locale')
->setParameter('locale', $locale);
}
$qb->getQuery()->execute();
}
}
/**
* Get the currently used TranslatableListener
*
* @throws RuntimeException if listener is not found
*/
private function getTranslatableListener(): TranslatableListener
{
if (null === $this->listener) {
foreach ($this->getEntityManager()->getEventManager()->getAllListeners() as $listeners) {
foreach ($listeners as $listener) {
if ($listener instanceof TranslatableListener) {
return $this->listener = $listener;
}
}
}
throw new RuntimeException('The translation listener could not be found');
}
return $this->listener;
}
}