[BUGFIX] Respect tablenames, fieldname when updating mm record
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Generic / Backend.php
1 <?php
2 namespace TYPO3\CMS\Extbase\Persistence\Generic;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface;
18 use TYPO3\CMS\Extbase\Persistence\ObjectMonitoringInterface;
19
20 /**
21 * A persistence backend. This backend maps objects to the relational model of the storage backend.
22 * It persists all added, removed and changed objects.
23 */
24 class Backend implements \TYPO3\CMS\Extbase\Persistence\Generic\BackendInterface, \TYPO3\CMS\Core\SingletonInterface {
25
26 /**
27 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Session
28 * @inject
29 */
30 protected $session;
31
32 /**
33 * @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
34 */
35 protected $persistenceManager;
36
37 /**
38 * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage
39 */
40 protected $aggregateRootObjects;
41
42 /**
43 * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage
44 */
45 protected $deletedEntities;
46
47 /**
48 * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage
49 */
50 protected $changedEntities;
51
52 /**
53 * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage
54 */
55 protected $visitedDuringPersistence;
56
57 /**
58 * @var \TYPO3\CMS\Extbase\Reflection\ReflectionService
59 * @inject
60 */
61 protected $reflectionService;
62
63 /**
64 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelFactory
65 * @inject
66 */
67 protected $qomFactory;
68
69 /**
70 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Storage\BackendInterface
71 * @inject
72 */
73 protected $storageBackend;
74
75 /**
76 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
77 * @inject
78 */
79 protected $dataMapper;
80
81 /**
82 * The TYPO3 reference index object
83 *
84 * @var \TYPO3\CMS\Core\Database\ReferenceIndex
85 */
86 protected $referenceIndex;
87
88 /**
89 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
90 */
91 protected $configurationManager;
92
93 /**
94 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
95 * @inject
96 */
97 protected $signalSlotDispatcher;
98
99 /**
100 * Constructs the backend
101 *
102 * @param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
103 */
104 public function __construct(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager) {
105 $this->configurationManager = $configurationManager;
106 $this->referenceIndex = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\ReferenceIndex');
107 $this->aggregateRootObjects = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
108 $this->deletedEntities = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
109 $this->changedEntities = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
110 }
111
112 /**
113 * @param \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface $persistenceManager
114 */
115 public function setPersistenceManager(\TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface $persistenceManager) {
116 $this->persistenceManager = $persistenceManager;
117 }
118
119 /**
120 * Returns the repository session
121 *
122 * @return \TYPO3\CMS\Extbase\Persistence\Generic\Session
123 */
124 public function getSession() {
125 return $this->session;
126 }
127
128 /**
129 * Returns the Data Mapper
130 *
131 * @return \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
132 */
133 public function getDataMapper() {
134 return $this->dataMapper;
135 }
136
137 /**
138 * Returns the current QOM factory
139 *
140 * @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelFactory
141 */
142 public function getQomFactory() {
143 return $this->qomFactory;
144 }
145
146 /**
147 * Returns the reflection service
148 *
149 * @return \TYPO3\CMS\Extbase\Reflection\ReflectionService
150 */
151 public function getReflectionService() {
152 return $this->reflectionService;
153 }
154
155 /**
156 * Returns the number of records matching the query.
157 *
158 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
159 * @return integer
160 * @api
161 */
162 public function getObjectCountByQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query) {
163 return $this->storageBackend->getObjectCountByQuery($query);
164 }
165
166 /**
167 * Returns the object data matching the $query.
168 *
169 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
170 * @return array
171 * @api
172 */
173 public function getObjectDataByQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query) {
174 $query = $this->emitBeforeGettingObjectDataSignal($query);
175 $result = $this->storageBackend->getObjectDataByQuery($query);
176 $result = $this->emitafterGettingObjectDataSignal($query, $result);
177 return $result;
178 }
179
180 /**
181 * Emits a signal before object data is fetched
182 *
183 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
184 * @return \TYPO3\CMS\Extbase\Persistence\QueryInterface Modified query
185 */
186 protected function emitBeforeGettingObjectDataSignal(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query) {
187 $signalArguments = $this->signalSlotDispatcher->dispatch(__CLASS__, 'beforeGettingObjectData', array($query));
188 return $signalArguments[0];
189 }
190
191 /**
192 * Emits a signal after object data is fetched
193 *
194 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
195 * @param array $result
196 * @return array Modified result
197 */
198 protected function emitAfterGettingObjectDataSignal(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query, array $result) {
199 $signalArguments = $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterGettingObjectData', array($query, $result));
200 return $signalArguments[1];
201 }
202
203 /**
204 * Returns the (internal) identifier for the object, if it is known to the
205 * backend. Otherwise NULL is returned.
206 *
207 * @param object $object
208 * @return string The identifier for the object if it is known, or NULL
209 */
210 public function getIdentifierByObject($object) {
211 if ($object instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
212 $object = $object->_loadRealInstance();
213 if (!is_object($object)) {
214 return NULL;
215 }
216 }
217 return $this->session->getIdentifierByObject($object);
218 }
219
220 /**
221 * Returns the object with the (internal) identifier, if it is known to the
222 * backend. Otherwise NULL is returned.
223 *
224 * @param string $identifier
225 * @param string $className
226 * @return object The object for the identifier if it is known, or NULL
227 */
228 public function getObjectByIdentifier($identifier, $className) {
229 if ($this->session->hasIdentifier($identifier, $className)) {
230 return $this->session->getObjectByIdentifier($identifier, $className);
231 } else {
232 $query = $this->persistenceManager->createQueryForType($className);
233 $query->getQuerySettings()->setRespectStoragePage(FALSE);
234 $query->getQuerySettings()->setRespectSysLanguage(FALSE);
235 return $query->matching($query->equals('uid', $identifier))->execute()->getFirst();
236 }
237 }
238
239 /**
240 * Checks if the given object has ever been persisted.
241 *
242 * @param object $object The object to check
243 * @return boolean TRUE if the object is new, FALSE if the object exists in the repository
244 */
245 public function isNewObject($object) {
246 return $this->getIdentifierByObject($object) === NULL;
247 }
248
249 /**
250 * Replaces the given object by the second object.
251 *
252 * This method will unregister the existing object at the identity map and
253 * register the new object instead. The existing object must therefore
254 * already be registered at the identity map which is the case for all
255 * reconstituted objects.
256 *
257 * The new object will be identified by the uid which formerly belonged
258 * to the existing object. The existing object looses its uid.
259 *
260 * @param object $existingObject The existing object
261 * @param object $newObject The new object
262 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException
263 * @return void
264 * @deprecated since 6.1, will be removed two versions later
265 */
266 public function replaceObject($existingObject, $newObject) {
267 $this->session->replaceReconstitutedEntity($existingObject, $newObject);
268 }
269
270 /**
271 * Sets the aggregate root objects
272 *
273 * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objects
274 * @return void
275 */
276 public function setAggregateRootObjects(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $objects) {
277 $this->aggregateRootObjects = $objects;
278 }
279
280 /**
281 * Sets the changed objects
282 *
283 * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $entities
284 * @return void
285 */
286 public function setChangedEntities(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $entities) {
287 $this->changedEntities = $entities;
288 }
289
290 /**
291 * Sets the deleted objects
292 *
293 * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $entities
294 * @return void
295 */
296 public function setDeletedEntities(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $entities) {
297 $this->deletedEntities = $entities;
298 }
299
300 /**
301 * Commits the current persistence session.
302 *
303 * @return void
304 */
305 public function commit() {
306 $this->persistObjects();
307 $this->processDeletedObjects();
308 }
309
310 /**
311 * Sets the deleted objects
312 *
313 * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objects
314 * @return void
315 * @deprecated since 6.1, will be removed two versions later
316 */
317 public function setDeletedObjects(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $objects) {
318 $this->setDeletedEntities($objects);
319 }
320
321 /**
322 * Traverse and persist all aggregate roots and their object graph.
323 *
324 * @return void
325 */
326 protected function persistObjects() {
327 $this->visitedDuringPersistence = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
328 foreach ($this->aggregateRootObjects as $object) {
329 /** @var DomainObjectInterface $object */
330 if ($object->_isNew()) {
331 $this->insertObject($object);
332 }
333 $this->persistObject($object, NULL);
334 }
335 foreach ($this->changedEntities as $object) {
336 $this->persistObject($object, NULL);
337 }
338 }
339
340 /**
341 * Persists the given object.
342 *
343 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to be inserted
344 * @return void
345 */
346 protected function persistObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object) {
347 if (isset($this->visitedDuringPersistence[$object])) {
348 return;
349 }
350 $row = array();
351 $queue = array();
352 $dataMap = $this->dataMapper->getDataMap(get_class($object));
353 $properties = $object->_getProperties();
354 foreach ($properties as $propertyName => $propertyValue) {
355 if (!$dataMap->isPersistableProperty($propertyName) || $this->propertyValueIsLazyLoaded($propertyValue)) {
356 continue;
357 }
358 $columnMap = $dataMap->getColumnMap($propertyName);
359 if ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\ObjectStorage) {
360 $cleanProperty = $object->_getCleanProperty($propertyName);
361 // objectstorage needs to be persisted if the object is new, the objectstorge is dirty, meaning it has
362 // been changed after initial build, or a empty objectstorge is present and the cleanstate objectstorage
363 // has childelements, meaning all elements should been removed from the objectstorage
364 if ($object->_isNew() || $propertyValue->_isDirty() || ($propertyValue->count() == 0 && $cleanProperty && $cleanProperty->count() > 0)) {
365 $this->persistObjectStorage($propertyValue, $object, $propertyName, $row);
366 $propertyValue->_memorizeCleanState();
367 }
368 foreach ($propertyValue as $containedObject) {
369 if ($containedObject instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
370 $queue[] = $containedObject;
371 }
372 }
373 } elseif ($propertyValue instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface
374 && $object instanceof ObjectMonitoringInterface) {
375 if ($object->_isDirty($propertyName)) {
376 if ($propertyValue->_isNew()) {
377 $this->insertObject($propertyValue, $object, $propertyName);
378 }
379 // Check explicitly for NULL, as getPlainValue would convert this to 'NULL'
380 $row[$columnMap->getColumnName()] = $propertyValue !== NULL
381 ? $this->dataMapper->getPlainValue($propertyValue)
382 : NULL;
383 }
384 $queue[] = $propertyValue;
385 } elseif ($object->_isNew() || $object->_isDirty($propertyName)) {
386 $row[$columnMap->getColumnName()] = $this->dataMapper->getPlainValue($propertyValue, $columnMap);
387 }
388 }
389 if (count($row) > 0) {
390 $this->updateObject($object, $row);
391 $object->_memorizeCleanState();
392 }
393 $this->visitedDuringPersistence[$object] = $object->getUid();
394 foreach ($queue as $queuedObject) {
395 $this->persistObject($queuedObject);
396 }
397 $this->emitAfterPersistObjectSignal($object);
398 }
399
400 /**
401 * Checks, if the property value is lazy loaded and was not initialized
402 *
403 * @param mixed $propertyValue The property value
404 * @return boolean
405 */
406 protected function propertyValueIsLazyLoaded($propertyValue) {
407 if ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
408 return TRUE;
409 }
410 if ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyObjectStorage) {
411 if ($propertyValue->isInitialized() === FALSE) {
412 return TRUE;
413 }
414 }
415 return FALSE;
416 }
417
418 /**
419 * Persists a an object storage. Objects of a 1:n or m:n relation are queued and processed with the parent object. A 1:1 relation
420 * gets persisted immediately. Objects which were removed from the property were detached from the parent object. They will not be
421 * deleted by default. You have to annotate the property with "@cascade remove" if you want them to be deleted as well.
422 *
423 * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage The object storage to be persisted.
424 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object. One of the properties holds the object storage.
425 * @param string $propertyName The name of the property holding the object storage.
426 * @param array &$row The row array of the parent object to be persisted. It's passed by reference and gets filled with either a comma separated list of uids (csv) or the number of contained objects.
427 * @return void
428 */
429 protected function persistObjectStorage(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $propertyName, array &$row) {
430 $className = get_class($parentObject);
431 $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
432 $propertyMetaData = $this->reflectionService->getClassSchema($className)->getProperty($propertyName);
433 foreach ($this->getRemovedChildObjects($parentObject, $propertyName) as $removedObject) {
434 $this->detachObjectFromParentObject($removedObject, $parentObject, $propertyName);
435 if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY && $propertyMetaData['cascade'] === 'remove') {
436 $this->removeEntity($removedObject);
437 }
438 }
439
440 $currentUids = array();
441 $sortingPosition = 1;
442 $updateSortingOfFollowing = FALSE;
443
444 foreach ($objectStorage as $object) {
445 /** @var DomainObjectInterface $object */
446 if (empty($currentUids)) {
447 $sortingPosition = 1;
448 } else {
449 $sortingPosition++;
450 }
451 $cleanProperty = $parentObject->_getCleanProperty($propertyName);
452 if ($object->_isNew()) {
453 $this->insertObject($object);
454 $this->attachObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition);
455 // if a new object is inserted, all objects after this need to have their sorting updated
456 $updateSortingOfFollowing = TRUE;
457 } elseif ($cleanProperty === NULL || $cleanProperty->getPosition($object) === NULL) {
458 // if parent object is new then it doesn't have cleanProperty yet; before attaching object it's clean position is null
459 $this->attachObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition);
460 // if a relation is dirty (speaking the same object is removed and added again at a different position), all objects after this needs to be updated the sorting
461 $updateSortingOfFollowing = TRUE;
462 } elseif ($objectStorage->isRelationDirty($object) || $cleanProperty->getPosition($object) !== $objectStorage->getPosition($object)) {
463 $this->updateRelationOfObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition);
464 $updateSortingOfFollowing = TRUE;
465 } elseif ($updateSortingOfFollowing) {
466 if ($sortingPosition > $objectStorage->getPosition($object)) {
467 $this->updateRelationOfObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition);
468 } else {
469 $sortingPosition = $objectStorage->getPosition($object);
470 }
471 }
472 $currentUids[] = $object->getUid();
473 }
474
475 if ($columnMap->getParentKeyFieldName() === NULL) {
476 $row[$columnMap->getColumnName()] = implode(',', $currentUids);
477 } else {
478 $row[$columnMap->getColumnName()] = $this->dataMapper->countRelated($parentObject, $propertyName);
479 }
480 }
481
482 /**
483 * Returns the removed objects determined by a comparison of the clean property value
484 * with the actual property value.
485 *
486 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object
487 * @param string $propertyName
488 * @return array An array of removed objects
489 */
490 protected function getRemovedChildObjects(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, $propertyName) {
491 $removedObjects = array();
492 $cleanPropertyValue = $object->_getCleanProperty($propertyName);
493 if (is_array($cleanPropertyValue) || $cleanPropertyValue instanceof \Iterator) {
494 $propertyValue = $object->_getProperty($propertyName);
495 foreach ($cleanPropertyValue as $containedObject) {
496 if (!$propertyValue->contains($containedObject)) {
497 $removedObjects[] = $containedObject;
498 }
499 }
500 }
501 return $removedObjects;
502 }
503
504 /**
505 * Updates the fields defining the relation between the object and the parent object.
506 *
507 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
508 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject
509 * @param string $parentPropertyName
510 * @param integer $sortingPosition
511 * @return void
512 */
513 protected function attachObjectToParentObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName, $sortingPosition = 0) {
514 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
515 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
516 if ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
517 $this->attachObjectToParentObjectRelationHasMany($object, $parentObject, $parentPropertyName, $sortingPosition);
518 } elseif ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
519 $this->insertRelationInRelationtable($object, $parentObject, $parentPropertyName, $sortingPosition);
520 }
521 }
522
523 /**
524 * Updates the fields defining the relation between the object and the parent object.
525 *
526 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
527 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractEntity $parentObject
528 * @param string $parentPropertyName
529 * @param integer $sortingPosition
530 * @return void
531 */
532 protected function updateRelationOfObjectToParentObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\AbstractEntity $parentObject, $parentPropertyName, $sortingPosition = 0) {
533 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
534 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
535 if ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
536 $this->attachObjectToParentObjectRelationHasMany($object, $parentObject, $parentPropertyName, $sortingPosition);
537 } elseif ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
538 $this->updateRelationInRelationTable($object, $parentObject, $parentPropertyName, $sortingPosition);
539 }
540 }
541
542 /**
543 * Updates fields defining the relation between the object and the parent object in relation has-many.
544 *
545 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
546 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractEntity $parentObject
547 * @param string $parentPropertyName
548 * @param integer $sortingPosition
549 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalRelationTypeException
550 * @return void
551 */
552 protected function attachObjectToParentObjectRelationHasMany(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\AbstractEntity $parentObject, $parentPropertyName, $sortingPosition = 0) {
553 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
554 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
555 if ($parentColumnMap->getTypeOfRelation() !== \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
556 throw new \TYPO3\CMS\Extbase\Persistence\Exception\IllegalRelationTypeException(
557 'Parent column relation type is ' . $parentColumnMap->getTypeOfRelation() .
558 ' but should be ' . \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY,
559 1345368105
560 );
561 }
562 $row = array();
563 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
564 if ($parentKeyFieldName !== NULL) {
565 $row[$parentKeyFieldName] = $parentObject->getUid();
566 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
567 if ($parentTableFieldName !== NULL) {
568 $row[$parentTableFieldName] = $parentDataMap->getTableName();
569 }
570 $relationTableMatchFields = $parentColumnMap->getRelationTableMatchFields();
571 if (is_array($relationTableMatchFields)) {
572 $row = array_merge($relationTableMatchFields, $row);
573 }
574 }
575 $childSortByFieldName = $parentColumnMap->getChildSortByFieldName();
576 if (!empty($childSortByFieldName)) {
577 $row[$childSortByFieldName] = $sortingPosition;
578 }
579 if (!empty($row)) {
580 $this->updateObject($object, $row);
581 }
582 }
583
584 /**
585 * Updates the fields defining the relation between the object and the parent object.
586 *
587 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
588 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject
589 * @param string $parentPropertyName
590 * @return void
591 */
592 protected function detachObjectFromParentObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName) {
593 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
594 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
595 if ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
596 $row = array();
597 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
598 if ($parentKeyFieldName !== NULL) {
599 $row[$parentKeyFieldName] = '';
600 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
601 if ($parentTableFieldName !== NULL) {
602 $row[$parentTableFieldName] = '';
603 }
604 $relationTableMatchFields = $parentColumnMap->getRelationTableMatchFields();
605 if (is_array($relationTableMatchFields) && count($relationTableMatchFields)) {
606 $row = array_merge(array_fill_keys(array_keys($relationTableMatchFields), ''), $row);
607 }
608 }
609 $childSortByFieldName = $parentColumnMap->getChildSortByFieldName();
610 if (!empty($childSortByFieldName)) {
611 $row[$childSortByFieldName] = 0;
612 }
613 if (count($row) > 0) {
614 $this->updateObject($object, $row);
615 }
616 } elseif ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
617 $this->deleteRelationFromRelationtable($object, $parentObject, $parentPropertyName);
618 }
619 }
620
621 /**
622 * Inserts an object in the storage backend
623 *
624 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to be insterted in the storage
625 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parentobject.
626 * @param string $parentPropertyName
627 * @return void
628 */
629 protected function insertObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject = NULL, $parentPropertyName = '') {
630 if ($object instanceof \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject) {
631 $result = $this->getUidOfAlreadyPersistedValueObject($object);
632 if ($result !== FALSE) {
633 $object->_setProperty('uid', (int)$result);
634 return;
635 }
636 }
637 $dataMap = $this->dataMapper->getDataMap(get_class($object));
638 $row = array();
639 $this->addCommonFieldsToRow($object, $row);
640 if ($dataMap->getLanguageIdColumnName() !== NULL) {
641 $row[$dataMap->getLanguageIdColumnName()] = -1;
642 }
643 if ($parentObject !== NULL && $parentPropertyName) {
644 $parentColumnDataMap = $this->dataMapper->getDataMap(get_class($parentObject))->getColumnMap($parentPropertyName);
645 $relationTableMatchFields = $parentColumnDataMap->getRelationTableMatchFields();
646 if (is_array($relationTableMatchFields)) {
647 $row = array_merge($relationTableMatchFields, $row);
648 }
649 if ($parentColumnDataMap->getParentKeyFieldName() !== NULL) {
650 $row[$parentColumnDataMap->getParentKeyFieldName()] = (int)$parentObject->getUid();
651 }
652 }
653 $uid = $this->storageBackend->addRow($dataMap->getTableName(), $row);
654 $object->_setProperty('uid', (int)$uid);
655 if ((int)$uid >= 1) {
656 $this->emitAfterInsertObjectSignal($object);
657 }
658 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
659 if ($frameworkConfiguration['persistence']['updateReferenceIndex'] === '1') {
660 $this->referenceIndex->updateRefIndexTable($dataMap->getTableName(), $uid);
661 }
662 $this->session->registerObject($object, $uid);
663 }
664
665 /**
666 * Emits a signal after an object was added to the storage
667 *
668 * @param DomainObjectInterface $object
669 */
670 protected function emitAfterInsertObjectSignal(DomainObjectInterface $object) {
671 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterInsertObject', array($object));
672 }
673
674 /**
675 * Tests, if the given Value Object already exists in the storage backend and if so, it returns the uid.
676 *
677 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object The object to be tested
678 * @return mixed The matching uid if an object was found, else FALSE
679 */
680 protected function getUidOfAlreadyPersistedValueObject(\TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object) {
681 return $this->storageBackend->getUidOfAlreadyPersistedValueObject($object);
682 }
683
684 /**
685 * Inserts mm-relation into a relation table
686 *
687 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The related object
688 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
689 * @param string $propertyName The name of the parent object's property where the related objects are stored in
690 * @param integer $sortingPosition Defaults to NULL
691 * @return integer The uid of the inserted row
692 */
693 protected function insertRelationInRelationtable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $propertyName, $sortingPosition = NULL) {
694 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
695 $columnMap = $dataMap->getColumnMap($propertyName);
696 $row = array(
697 $columnMap->getParentKeyFieldName() => (int)$parentObject->getUid(),
698 $columnMap->getChildKeyFieldName() => (int)$object->getUid(),
699 $columnMap->getChildSortByFieldName() => !is_null($sortingPosition) ? (int)$sortingPosition : 0
700 );
701 $relationTableName = $columnMap->getRelationTableName();
702 if ($columnMap->getRelationTablePageIdColumnName() !== NULL) {
703 $row[$columnMap->getRelationTablePageIdColumnName()] = $this->determineStoragePageIdForNewRecord();
704 }
705 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
706 if (is_array($relationTableMatchFields)) {
707 $row = array_merge($relationTableMatchFields, $row);
708 }
709 $relationTableInsertFields = $columnMap->getRelationTableInsertFields();
710 if (is_array($relationTableInsertFields)) {
711 $row = array_merge($relationTableInsertFields, $row);
712 }
713 $res = $this->storageBackend->addRow($relationTableName, $row, TRUE);
714 return $res;
715 }
716
717 /**
718 * Updates mm-relation in a relation table
719 *
720 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The related object
721 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
722 * @param string $propertyName The name of the parent object's property where the related objects are stored in
723 * @param integer $sortingPosition Defaults to NULL
724 * @return bool TRUE if update was successfully
725 */
726 protected function updateRelationInRelationTable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $propertyName, $sortingPosition = 0) {
727 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
728 $columnMap = $dataMap->getColumnMap($propertyName);
729 $row = array(
730 $columnMap->getParentKeyFieldName() => (int)$parentObject->getUid(),
731 $columnMap->getChildKeyFieldName() => (int)$object->getUid(),
732 $columnMap->getChildSortByFieldName() => (int)$sortingPosition
733 );
734 $relationTableName = $columnMap->getRelationTableName();
735 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
736 if (is_array($relationTableMatchFields)) {
737 $row = array_merge($relationTableMatchFields, $row);
738 }
739 $res = $this->storageBackend->updateRelationTableRow(
740 $relationTableName,
741 $row);
742 return $res;
743 }
744
745 /**
746 * Delete all mm-relations of a parent from a relation table
747 *
748 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
749 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
750 * @return bool TRUE if delete was successfully
751 */
752 protected function deleteAllRelationsFromRelationtable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName) {
753 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
754 $columnMap = $dataMap->getColumnMap($parentPropertyName);
755 $relationTableName = $columnMap->getRelationTableName();
756 $relationMatchFields = array(
757 $columnMap->getParentKeyFieldName() => (int)$parentObject->getUid()
758 );
759 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
760 if (is_array($relationTableMatchFields)) {
761 $relationMatchFields = array_merge($relationTableMatchFields, $relationMatchFields);
762 }
763 $res = $this->storageBackend->removeRow($relationTableName, $relationMatchFields, FALSE);
764 return $res;
765 }
766
767 /**
768 * Delete an mm-relation from a relation table
769 *
770 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $relatedObject The related object
771 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
772 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
773 * @return boolean
774 */
775 protected function deleteRelationFromRelationtable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $relatedObject, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName) {
776 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
777 $columnMap = $dataMap->getColumnMap($parentPropertyName);
778 $relationTableName = $columnMap->getRelationTableName();
779 $relationMatchFields = array(
780 $columnMap->getParentKeyFieldName() => (int)$parentObject->getUid(),
781 $columnMap->getChildKeyFieldName() => (int)$relatedObject->getUid()
782 );
783 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
784 if (is_array($relationTableMatchFields)) {
785 $relationMatchFields = array_merge($relationTableMatchFields, $relationMatchFields);
786 }
787 $res = $this->storageBackend->removeRow($relationTableName, $relationMatchFields, FALSE);
788 return $res;
789 }
790
791 /**
792 * Fetches maximal value currently used for sorting field in parent table
793 *
794 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
795 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
796 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalRelationTypeException
797 * @return mixed the max value
798 */
799 protected function fetchMaxSortingFromParentTable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName) {
800 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
801 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
802 if ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
803 $tableName = $parentColumnMap->getChildTableName();
804 $sortByFieldName = $parentColumnMap->getChildSortByFieldName();
805
806 if (empty($sortByFieldName)) {
807 return FALSE;
808 }
809 $matchFields = array();
810 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
811 if ($parentKeyFieldName !== NULL) {
812 $matchFields[$parentKeyFieldName] = $parentObject->getUid();
813 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
814 if ($parentTableFieldName !== NULL) {
815 $matchFields[$parentTableFieldName] = $parentDataMap->getTableName();
816 }
817 }
818
819 if (empty($matchFields)) {
820 return FALSE;
821 }
822 } elseif ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
823 $tableName = $parentColumnMap->getRelationTableName();
824 $sortByFieldName = $parentColumnMap->getChildSortByFieldName();
825
826 $matchFields = array(
827 $parentColumnMap->getParentKeyFieldName() => (int)$parentObject->getUid()
828 );
829
830 $relationTableMatchFields = $parentColumnMap->getRelationTableMatchFields();
831 if (is_array($relationTableMatchFields)) {
832 $matchFields = array_merge($relationTableMatchFields, $matchFields);
833 }
834 } else {
835 throw new \TYPO3\CMS\Extbase\Persistence\Exception\IllegalRelationTypeException('Unexpected parent column relation type:' . $parentColumnMap->getTypeOfRelation(), 1345368106);
836 }
837
838 $result = $this->storageBackend->getMaxValueFromTable(
839 $tableName,
840 $matchFields,
841 $sortByFieldName);
842 return $result;
843 }
844
845 /**
846 * Updates a given object in the storage
847 *
848 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to be updated
849 * @param array $row Row to be stored
850 * @return boolean
851 */
852 protected function updateObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, array $row) {
853 $dataMap = $this->dataMapper->getDataMap(get_class($object));
854 $this->addCommonFieldsToRow($object, $row);
855 $row['uid'] = $object->getUid();
856 if ($dataMap->getLanguageIdColumnName() !== NULL) {
857 $row[$dataMap->getLanguageIdColumnName()] = $object->_getProperty('_languageUid');
858 if ($object->_getProperty('_localizedUid') !== NULL) {
859 $row['uid'] = $object->_getProperty('_localizedUid');
860 }
861 }
862 $res = $this->storageBackend->updateRow($dataMap->getTableName(), $row);
863 if ($res === TRUE) {
864 $this->emitAfterUpdateObjectSignal($object);
865 }
866 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
867 if ($frameworkConfiguration['persistence']['updateReferenceIndex'] === '1') {
868 $this->referenceIndex->updateRefIndexTable($dataMap->getTableName(), $row['uid']);
869 }
870 return $res;
871 }
872
873 /**
874 * Emits a signal after an object was updated in storage
875 *
876 * @param DomainObjectInterface $object
877 */
878 protected function emitAfterUpdateObjectSignal(DomainObjectInterface $object) {
879 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterUpdateObject', array($object));
880 }
881
882 /**
883 * Emits a signal after an object was persisted
884 *
885 * @param DomainObjectInterface $object
886 */
887 protected function emitAfterPersistObjectSignal(DomainObjectInterface $object) {
888 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterPersistObject', array($object));
889 }
890
891 /**
892 * Adds common databse fields to a row
893 *
894 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
895 * @param array &$row
896 * @return void
897 */
898 protected function addCommonFieldsToRow(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, array &$row) {
899 $dataMap = $this->dataMapper->getDataMap(get_class($object));
900 $this->addCommonDateFieldsToRow($object, $row);
901 if ($dataMap->getRecordTypeColumnName() !== NULL && $dataMap->getRecordType() !== NULL) {
902 $row[$dataMap->getRecordTypeColumnName()] = $dataMap->getRecordType();
903 }
904 if ($object->_isNew() && !isset($row['pid'])) {
905 $row['pid'] = $this->determineStoragePageIdForNewRecord($object);
906 }
907 }
908
909 /**
910 * Adjustes the common date fields of the given row to the current time
911 *
912 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
913 * @param array &$row The row to be updated
914 * @return void
915 */
916 protected function addCommonDateFieldsToRow(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, array &$row) {
917 $dataMap = $this->dataMapper->getDataMap(get_class($object));
918 if ($object->_isNew() && $dataMap->getCreationDateColumnName() !== NULL) {
919 $row[$dataMap->getCreationDateColumnName()] = $GLOBALS['EXEC_TIME'];
920 }
921 if ($dataMap->getModificationDateColumnName() !== NULL) {
922 $row[$dataMap->getModificationDateColumnName()] = $GLOBALS['EXEC_TIME'];
923 }
924 }
925
926 /**
927 * Iterate over deleted aggregate root objects and process them
928 *
929 * @return void
930 */
931 protected function processDeletedObjects() {
932 foreach ($this->deletedEntities as $entity) {
933 if ($this->session->hasObject($entity)) {
934 $this->removeEntity($entity);
935 $this->session->unregisterReconstitutedEntity($entity);
936 $this->session->unregisterObject($entity);
937 }
938 }
939 $this->deletedEntities = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
940 }
941
942 /**
943 * Deletes an object
944 *
945 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to be removed from the storage
946 * @param boolean $markAsDeleted Whether to just flag the row deleted (default) or really delete it
947 * @return void
948 */
949 protected function removeEntity(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, $markAsDeleted = TRUE) {
950 $dataMap = $this->dataMapper->getDataMap(get_class($object));
951 $tableName = $dataMap->getTableName();
952 if ($markAsDeleted === TRUE && $dataMap->getDeletedFlagColumnName() !== NULL) {
953 $deletedColumnName = $dataMap->getDeletedFlagColumnName();
954 $row = array(
955 'uid' => $object->getUid(),
956 $deletedColumnName => 1
957 );
958 $this->addCommonDateFieldsToRow($object, $row);
959 $res = $this->storageBackend->updateRow($tableName, $row);
960 } else {
961 $res = $this->storageBackend->removeRow($tableName, array('uid' => $object->getUid()));
962 }
963 if ($res === TRUE) {
964 $this->emitAfterRemoveObjectSignal($object);
965 }
966 $this->removeRelatedObjects($object);
967 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
968 if ($frameworkConfiguration['persistence']['updateReferenceIndex'] === '1') {
969 $this->referenceIndex->updateRefIndexTable($tableName, $object->getUid());
970 }
971 }
972
973 /**
974 * Emits a signal after an object was removed from storage
975 *
976 * @param DomainObjectInterface $object
977 */
978 protected function emitAfterRemoveObjectSignal(DomainObjectInterface $object) {
979 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterRemoveObject', array($object));
980 }
981
982 /**
983 * Remove related objects
984 *
985 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to scanned for related objects
986 * @return void
987 */
988 protected function removeRelatedObjects(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object) {
989 $className = get_class($object);
990 $dataMap = $this->dataMapper->getDataMap($className);
991 $classSchema = $this->reflectionService->getClassSchema($className);
992 $properties = $object->_getProperties();
993 foreach ($properties as $propertyName => $propertyValue) {
994 $columnMap = $dataMap->getColumnMap($propertyName);
995 $propertyMetaData = $classSchema->getProperty($propertyName);
996 if ($propertyMetaData['cascade'] === 'remove') {
997 if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
998 foreach ($propertyValue as $containedObject) {
999 $this->removeEntity($containedObject);
1000 }
1001 } elseif ($propertyValue instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
1002 $this->removeEntity($propertyValue);
1003 }
1004 }
1005 }
1006 }
1007
1008 /**
1009 * Determine the storage page ID for a given NEW record
1010 *
1011 * This does the following:
1012 * - If the domain object has an accessible property 'pid' (i.e. through a getPid() method), that is used to store the record.
1013 * - If there is a TypoScript configuration "classes.CLASSNAME.newRecordStoragePid", that is used to store new records.
1014 * - If there is no such TypoScript configuration, it uses the first value of The "storagePid" taken for reading records.
1015 *
1016 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
1017 * @return integer the storage Page ID where the object should be stored
1018 */
1019 protected function determineStoragePageIdForNewRecord(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object = NULL) {
1020 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
1021 if ($object !== NULL) {
1022 if (\TYPO3\CMS\Extbase\Reflection\ObjectAccess::isPropertyGettable($object, 'pid')) {
1023 $pid = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getProperty($object, 'pid');
1024 if (isset($pid)) {
1025 return (int)$pid;
1026 }
1027 }
1028 $className = get_class($object);
1029 if (isset($frameworkConfiguration['persistence']['classes'][$className]) && !empty($frameworkConfiguration['persistence']['classes'][$className]['newRecordStoragePid'])) {
1030 return (int)$frameworkConfiguration['persistence']['classes'][$className]['newRecordStoragePid'];
1031 }
1032 }
1033 $storagePidList = \TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $frameworkConfiguration['persistence']['storagePid']);
1034 return (int)$storagePidList[0];
1035 }
1036 }