[CLEANUP] Remove redundant code in Persistence
[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 }
398
399 /**
400 * Checks, if the property value is lazy loaded and was not initialized
401 *
402 * @param mixed $propertyValue The property value
403 * @return boolean
404 */
405 protected function propertyValueIsLazyLoaded($propertyValue) {
406 if ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
407 return TRUE;
408 }
409 if ($propertyValue instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyObjectStorage) {
410 if ($propertyValue->isInitialized() === FALSE) {
411 return TRUE;
412 }
413 }
414 return FALSE;
415 }
416
417 /**
418 * 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
419 * gets persisted immediately. Objects which were removed from the property were detached from the parent object. They will not be
420 * deleted by default. You have to annotate the property with "@cascade remove" if you want them to be deleted as well.
421 *
422 * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage The object storage to be persisted.
423 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object. One of the properties holds the object storage.
424 * @param string $propertyName The name of the property holding the object storage.
425 * @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.
426 * @return void
427 */
428 protected function persistObjectStorage(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $propertyName, array &$row) {
429 $className = get_class($parentObject);
430 $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
431 $propertyMetaData = $this->reflectionService->getClassSchema($className)->getProperty($propertyName);
432 foreach ($this->getRemovedChildObjects($parentObject, $propertyName) as $removedObject) {
433 $this->detachObjectFromParentObject($removedObject, $parentObject, $propertyName);
434 if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY && $propertyMetaData['cascade'] === 'remove') {
435 $this->removeEntity($removedObject);
436 }
437 }
438
439 $currentUids = array();
440 $sortingPosition = 1;
441 $updateSortingOfFollowing = FALSE;
442
443 foreach ($objectStorage as $object) {
444 /** @var DomainObjectInterface $object */
445 if (empty($currentUids)) {
446 $sortingPosition = 1;
447 } else {
448 $sortingPosition++;
449 }
450 $cleanProperty = $parentObject->_getCleanProperty($propertyName);
451 if ($object->_isNew()) {
452 $this->insertObject($object);
453 $this->attachObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition);
454 // if a new object is inserted, all objects after this need to have their sorting updated
455 $updateSortingOfFollowing = TRUE;
456 } elseif ($cleanProperty === NULL || $cleanProperty->getPosition($object) === NULL) {
457 // if parent object is new then it doesn't have cleanProperty yet; before attaching object it's clean position is null
458 $this->attachObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition);
459 // 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
460 $updateSortingOfFollowing = TRUE;
461 } elseif ($objectStorage->isRelationDirty($object) || $cleanProperty->getPosition($object) !== $objectStorage->getPosition($object)) {
462 $this->updateRelationOfObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition);
463 $updateSortingOfFollowing = TRUE;
464 } elseif ($updateSortingOfFollowing) {
465 if ($sortingPosition > $objectStorage->getPosition($object)) {
466 $this->updateRelationOfObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition);
467 } else {
468 $sortingPosition = $objectStorage->getPosition($object);
469 }
470 }
471 $currentUids[] = $object->getUid();
472 }
473
474 if ($columnMap->getParentKeyFieldName() === NULL) {
475 $row[$columnMap->getColumnName()] = implode(',', $currentUids);
476 } else {
477 $row[$columnMap->getColumnName()] = $this->dataMapper->countRelated($parentObject, $propertyName);
478 }
479 }
480
481 /**
482 * Returns the removed objects determined by a comparison of the clean property value
483 * with the actual property value.
484 *
485 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object
486 * @param string $propertyName
487 * @return array An array of removed objects
488 */
489 protected function getRemovedChildObjects(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, $propertyName) {
490 $removedObjects = array();
491 $cleanPropertyValue = $object->_getCleanProperty($propertyName);
492 if (is_array($cleanPropertyValue) || $cleanPropertyValue instanceof \Iterator) {
493 $propertyValue = $object->_getProperty($propertyName);
494 foreach ($cleanPropertyValue as $containedObject) {
495 if (!$propertyValue->contains($containedObject)) {
496 $removedObjects[] = $containedObject;
497 }
498 }
499 }
500 return $removedObjects;
501 }
502
503 /**
504 * Updates the fields defining the relation between the object and the parent object.
505 *
506 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
507 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject
508 * @param string $parentPropertyName
509 * @param integer $sortingPosition
510 * @return void
511 */
512 protected function attachObjectToParentObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName, $sortingPosition = 0) {
513 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
514 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
515 if ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
516 $this->attachObjectToParentObjectRelationHasMany($object, $parentObject, $parentPropertyName, $sortingPosition);
517 } elseif ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
518 $this->insertRelationInRelationtable($object, $parentObject, $parentPropertyName, $sortingPosition);
519 }
520 }
521
522 /**
523 * Updates the fields defining the relation between the object and the parent object.
524 *
525 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
526 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractEntity $parentObject
527 * @param string $parentPropertyName
528 * @param integer $sortingPosition
529 * @return void
530 */
531 protected function updateRelationOfObjectToParentObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\AbstractEntity $parentObject, $parentPropertyName, $sortingPosition = 0) {
532 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
533 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
534 if ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
535 $this->attachObjectToParentObjectRelationHasMany($object, $parentObject, $parentPropertyName, $sortingPosition);
536 } elseif ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
537 $this->updateRelationInRelationTable($object, $parentObject, $parentPropertyName, $sortingPosition);
538 }
539 }
540
541 /**
542 * Updates fields defining the relation between the object and the parent object in relation has-many.
543 *
544 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
545 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractEntity $parentObject
546 * @param string $parentPropertyName
547 * @param integer $sortingPosition
548 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalRelationTypeException
549 * @return void
550 */
551 protected function attachObjectToParentObjectRelationHasMany(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\AbstractEntity $parentObject, $parentPropertyName, $sortingPosition = 0) {
552 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
553 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
554 if ($parentColumnMap->getTypeOfRelation() !== \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
555 throw new \TYPO3\CMS\Extbase\Persistence\Exception\IllegalRelationTypeException(
556 'Parent column relation type is ' . $parentColumnMap->getTypeOfRelation() .
557 ' but should be ' . \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY,
558 1345368105
559 );
560 }
561 $row = array();
562 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
563 if ($parentKeyFieldName !== NULL) {
564 $row[$parentKeyFieldName] = $parentObject->getUid();
565 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
566 if ($parentTableFieldName !== NULL) {
567 $row[$parentTableFieldName] = $parentDataMap->getTableName();
568 }
569 $relationTableMatchFields = $parentColumnMap->getRelationTableMatchFields();
570 if (is_array($relationTableMatchFields)) {
571 $row = array_merge($relationTableMatchFields, $row);
572 }
573 }
574 $childSortByFieldName = $parentColumnMap->getChildSortByFieldName();
575 if (!empty($childSortByFieldName)) {
576 $row[$childSortByFieldName] = $sortingPosition;
577 }
578 if (!empty($row)) {
579 $this->updateObject($object, $row);
580 }
581 }
582
583 /**
584 * Updates the fields defining the relation between the object and the parent object.
585 *
586 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
587 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject
588 * @param string $parentPropertyName
589 * @return void
590 */
591 protected function detachObjectFromParentObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName) {
592 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
593 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
594 if ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
595 $row = array();
596 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
597 if ($parentKeyFieldName !== NULL) {
598 $row[$parentKeyFieldName] = '';
599 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
600 if ($parentTableFieldName !== NULL) {
601 $row[$parentTableFieldName] = '';
602 }
603 $relationTableMatchFields = $parentColumnMap->getRelationTableMatchFields();
604 if (is_array($relationTableMatchFields) && count($relationTableMatchFields)) {
605 $row = array_merge(array_fill_keys(array_keys($relationTableMatchFields), ''), $row);
606 }
607 }
608 $childSortByFieldName = $parentColumnMap->getChildSortByFieldName();
609 if (!empty($childSortByFieldName)) {
610 $row[$childSortByFieldName] = 0;
611 }
612 if (count($row) > 0) {
613 $this->updateObject($object, $row);
614 }
615 } elseif ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
616 $this->deleteRelationFromRelationtable($object, $parentObject, $parentPropertyName);
617 }
618 }
619
620 /**
621 * Inserts an object in the storage backend
622 *
623 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to be insterted in the storage
624 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parentobject.
625 * @param string $parentPropertyName
626 * @return void
627 */
628 protected function insertObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject = NULL, $parentPropertyName = '') {
629 if ($object instanceof \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject) {
630 $result = $this->getUidOfAlreadyPersistedValueObject($object);
631 if ($result !== FALSE) {
632 $object->_setProperty('uid', (int)$result);
633 return;
634 }
635 }
636 $dataMap = $this->dataMapper->getDataMap(get_class($object));
637 $row = array();
638 $this->addCommonFieldsToRow($object, $row);
639 if ($dataMap->getLanguageIdColumnName() !== NULL) {
640 $row[$dataMap->getLanguageIdColumnName()] = -1;
641 }
642 if ($parentObject !== NULL && $parentPropertyName) {
643 $parentColumnDataMap = $this->dataMapper->getDataMap(get_class($parentObject))->getColumnMap($parentPropertyName);
644 $relationTableMatchFields = $parentColumnDataMap->getRelationTableMatchFields();
645 if (is_array($relationTableMatchFields)) {
646 $row = array_merge($relationTableMatchFields, $row);
647 }
648 if ($parentColumnDataMap->getParentKeyFieldName() !== NULL) {
649 $row[$parentColumnDataMap->getParentKeyFieldName()] = (int)$parentObject->getUid();
650 }
651 }
652 $uid = $this->storageBackend->addRow($dataMap->getTableName(), $row);
653 $object->_setProperty('uid', (int)$uid);
654 if ((int)$uid >= 1) {
655 $this->emitAfterInsertObjectSignal($object);
656 }
657 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
658 if ($frameworkConfiguration['persistence']['updateReferenceIndex'] === '1') {
659 $this->referenceIndex->updateRefIndexTable($dataMap->getTableName(), $uid);
660 }
661 $this->session->registerObject($object, $uid);
662 }
663
664 /**
665 * Emits a signal after an object was added to the storage
666 *
667 * @param DomainObjectInterface $object
668 */
669 protected function emitAfterInsertObjectSignal(DomainObjectInterface $object) {
670 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterInsertObject', array($object));
671 }
672
673 /**
674 * Tests, if the given Value Object already exists in the storage backend and if so, it returns the uid.
675 *
676 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object The object to be tested
677 * @return mixed The matching uid if an object was found, else FALSE
678 */
679 protected function getUidOfAlreadyPersistedValueObject(\TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object) {
680 return $this->storageBackend->getUidOfAlreadyPersistedValueObject($object);
681 }
682
683 /**
684 * Inserts mm-relation into a relation table
685 *
686 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The related object
687 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
688 * @param string $propertyName The name of the parent object's property where the related objects are stored in
689 * @param integer $sortingPosition Defaults to NULL
690 * @return integer The uid of the inserted row
691 */
692 protected function insertRelationInRelationtable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $propertyName, $sortingPosition = NULL) {
693 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
694 $columnMap = $dataMap->getColumnMap($propertyName);
695 $row = array(
696 $columnMap->getParentKeyFieldName() => (int)$parentObject->getUid(),
697 $columnMap->getChildKeyFieldName() => (int)$object->getUid(),
698 $columnMap->getChildSortByFieldName() => !is_null($sortingPosition) ? (int)$sortingPosition : 0
699 );
700 $relationTableName = $columnMap->getRelationTableName();
701 if ($columnMap->getRelationTablePageIdColumnName() !== NULL) {
702 $row[$columnMap->getRelationTablePageIdColumnName()] = $this->determineStoragePageIdForNewRecord();
703 }
704 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
705 if (is_array($relationTableMatchFields)) {
706 $row = array_merge($relationTableMatchFields, $row);
707 }
708 $relationTableInsertFields = $columnMap->getRelationTableInsertFields();
709 if (is_array($relationTableInsertFields)) {
710 $row = array_merge($relationTableInsertFields, $row);
711 }
712 $res = $this->storageBackend->addRow($relationTableName, $row, TRUE);
713 return $res;
714 }
715
716 /**
717 * Inserts mm-relation into a relation table
718 *
719 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The related object
720 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
721 * @param string $propertyName The name of the parent object's property where the related objects are stored in
722 * @param integer $sortingPosition Defaults to NULL
723 * @return integer The uid of the inserted row
724 */
725 protected function updateRelationInRelationTable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $propertyName, $sortingPosition = 0) {
726 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
727 $columnMap = $dataMap->getColumnMap($propertyName);
728 $row = array(
729 $columnMap->getParentKeyFieldName() => (int)$parentObject->getUid(),
730 $columnMap->getChildKeyFieldName() => (int)$object->getUid(),
731 $columnMap->getChildSortByFieldName() => (int)$sortingPosition
732 );
733 $relationTableName = $columnMap->getRelationTableName();
734 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
735 if (is_array($relationTableMatchFields)) {
736 $row = array_merge($relationTableMatchFields, $row);
737 }
738 $res = $this->storageBackend->updateRelationTableRow(
739 $relationTableName,
740 $row);
741 return $res;
742 }
743
744 /**
745 * Delete all mm-relations of a parent from a relation table
746 *
747 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
748 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
749 * @return boolean
750 */
751 protected function deleteAllRelationsFromRelationtable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName) {
752 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
753 $columnMap = $dataMap->getColumnMap($parentPropertyName);
754 $relationTableName = $columnMap->getRelationTableName();
755 $relationMatchFields = array(
756 $columnMap->getParentKeyFieldName() => (int)$parentObject->getUid()
757 );
758 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
759 if (is_array($relationTableMatchFields)) {
760 $relationMatchFields = array_merge($relationTableMatchFields, $relationMatchFields);
761 }
762 $res = $this->storageBackend->removeRow($relationTableName, $relationMatchFields, FALSE);
763 return $res;
764 }
765
766 /**
767 * Delete an mm-relation from a relation table
768 *
769 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $relatedObject The related object
770 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
771 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
772 * @return boolean
773 */
774 protected function deleteRelationFromRelationtable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $relatedObject, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName) {
775 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
776 $columnMap = $dataMap->getColumnMap($parentPropertyName);
777 $relationTableName = $columnMap->getRelationTableName();
778 $relationMatchFields = array(
779 $columnMap->getParentKeyFieldName() => (int)$parentObject->getUid(),
780 $columnMap->getChildKeyFieldName() => (int)$relatedObject->getUid()
781 );
782 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
783 if (is_array($relationTableMatchFields)) {
784 $relationMatchFields = array_merge($relationTableMatchFields, $relationMatchFields);
785 }
786 $res = $this->storageBackend->removeRow($relationTableName, $relationMatchFields, FALSE);
787 return $res;
788 }
789
790 /**
791 * Fetches maximal value currently used for sorting field in parent table
792 *
793 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object
794 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
795 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalRelationTypeException
796 * @return mixed the max value
797 */
798 protected function fetchMaxSortingFromParentTable(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $parentPropertyName) {
799 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
800 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
801 if ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
802 $tableName = $parentColumnMap->getChildTableName();
803 $sortByFieldName = $parentColumnMap->getChildSortByFieldName();
804
805 if (empty($sortByFieldName)) {
806 return FALSE;
807 }
808 $matchFields = array();
809 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
810 if ($parentKeyFieldName !== NULL) {
811 $matchFields[$parentKeyFieldName] = $parentObject->getUid();
812 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
813 if ($parentTableFieldName !== NULL) {
814 $matchFields[$parentTableFieldName] = $parentDataMap->getTableName();
815 }
816 }
817
818 if (empty($matchFields)) {
819 return FALSE;
820 }
821 } elseif ($parentColumnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
822 $tableName = $parentColumnMap->getRelationTableName();
823 $sortByFieldName = $parentColumnMap->getChildSortByFieldName();
824
825 $matchFields = array(
826 $parentColumnMap->getParentKeyFieldName() => (int)$parentObject->getUid()
827 );
828
829 $relationTableMatchFields = $parentColumnMap->getRelationTableMatchFields();
830 if (is_array($relationTableMatchFields)) {
831 $matchFields = array_merge($relationTableMatchFields, $matchFields);
832 }
833 } else {
834 throw new \TYPO3\CMS\Extbase\Persistence\Exception\IllegalRelationTypeException('Unexpected parent column relation type:' . $parentColumnMap->getTypeOfRelation(), 1345368106);
835 }
836
837 $result = $this->storageBackend->getMaxValueFromTable(
838 $tableName,
839 $matchFields,
840 $sortByFieldName);
841 return $result;
842 }
843
844 /**
845 * Updates a given object in the storage
846 *
847 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to be updated
848 * @param array $row Row to be stored
849 * @return boolean
850 */
851 protected function updateObject(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, array $row) {
852 $dataMap = $this->dataMapper->getDataMap(get_class($object));
853 $this->addCommonFieldsToRow($object, $row);
854 $row['uid'] = $object->getUid();
855 if ($dataMap->getLanguageIdColumnName() !== NULL) {
856 $row[$dataMap->getLanguageIdColumnName()] = $object->_getProperty('_languageUid');
857 if ($object->_getProperty('_localizedUid') !== NULL) {
858 $row['uid'] = $object->_getProperty('_localizedUid');
859 }
860 }
861 $res = $this->storageBackend->updateRow($dataMap->getTableName(), $row);
862 if ($res === TRUE) {
863 $this->emitAfterUpdateObjectSignal($object);
864 }
865 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
866 if ($frameworkConfiguration['persistence']['updateReferenceIndex'] === '1') {
867 $this->referenceIndex->updateRefIndexTable($dataMap->getTableName(), $row['uid']);
868 }
869 return $res;
870 }
871
872 /**
873 * Emits a signal after an object was updated in storage
874 *
875 * @param DomainObjectInterface $object
876 */
877 protected function emitAfterUpdateObjectSignal(DomainObjectInterface $object) {
878 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterUpdateObject', array($object));
879 }
880
881 /**
882 * Adds common databse fields to a row
883 *
884 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
885 * @param array &$row
886 * @return void
887 */
888 protected function addCommonFieldsToRow(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, array &$row) {
889 $dataMap = $this->dataMapper->getDataMap(get_class($object));
890 $this->addCommonDateFieldsToRow($object, $row);
891 if ($dataMap->getRecordTypeColumnName() !== NULL && $dataMap->getRecordType() !== NULL) {
892 $row[$dataMap->getRecordTypeColumnName()] = $dataMap->getRecordType();
893 }
894 if ($object->_isNew() && !isset($row['pid'])) {
895 $row['pid'] = $this->determineStoragePageIdForNewRecord($object);
896 }
897 }
898
899 /**
900 * Adjustes the common date fields of the given row to the current time
901 *
902 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
903 * @param array &$row The row to be updated
904 * @return void
905 */
906 protected function addCommonDateFieldsToRow(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, array &$row) {
907 $dataMap = $this->dataMapper->getDataMap(get_class($object));
908 if ($object->_isNew() && $dataMap->getCreationDateColumnName() !== NULL) {
909 $row[$dataMap->getCreationDateColumnName()] = $GLOBALS['EXEC_TIME'];
910 }
911 if ($dataMap->getModificationDateColumnName() !== NULL) {
912 $row[$dataMap->getModificationDateColumnName()] = $GLOBALS['EXEC_TIME'];
913 }
914 }
915
916 /**
917 * Iterate over deleted aggregate root objects and process them
918 *
919 * @return void
920 */
921 protected function processDeletedObjects() {
922 foreach ($this->deletedEntities as $entity) {
923 if ($this->session->hasObject($entity)) {
924 $this->removeEntity($entity);
925 $this->session->unregisterReconstitutedEntity($entity);
926 $this->session->unregisterObject($entity);
927 }
928 }
929 $this->deletedEntities = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
930 }
931
932 /**
933 * Deletes an object
934 *
935 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to be removed from the storage
936 * @param boolean $markAsDeleted Whether to just flag the row deleted (default) or really delete it
937 * @return void
938 */
939 protected function removeEntity(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, $markAsDeleted = TRUE) {
940 $dataMap = $this->dataMapper->getDataMap(get_class($object));
941 $tableName = $dataMap->getTableName();
942 if ($markAsDeleted === TRUE && $dataMap->getDeletedFlagColumnName() !== NULL) {
943 $deletedColumnName = $dataMap->getDeletedFlagColumnName();
944 $row = array(
945 'uid' => $object->getUid(),
946 $deletedColumnName => 1
947 );
948 $this->addCommonDateFieldsToRow($object, $row);
949 $res = $this->storageBackend->updateRow($tableName, $row);
950 } else {
951 $res = $this->storageBackend->removeRow($tableName, array('uid' => $object->getUid()));
952 }
953 if ($res === TRUE) {
954 $this->emitAfterRemoveObjectSignal($object);
955 }
956 $this->removeRelatedObjects($object);
957 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
958 if ($frameworkConfiguration['persistence']['updateReferenceIndex'] === '1') {
959 $this->referenceIndex->updateRefIndexTable($tableName, $object->getUid());
960 }
961 }
962
963 /**
964 * Emits a signal after an object was removed from storage
965 *
966 * @param DomainObjectInterface $object
967 */
968 protected function emitAfterRemoveObjectSignal(DomainObjectInterface $object) {
969 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterRemoveObject', array($object));
970 }
971
972 /**
973 * Remove related objects
974 *
975 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to scanned for related objects
976 * @return void
977 */
978 protected function removeRelatedObjects(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object) {
979 $className = get_class($object);
980 $dataMap = $this->dataMapper->getDataMap($className);
981 $classSchema = $this->reflectionService->getClassSchema($className);
982 $properties = $object->_getProperties();
983 foreach ($properties as $propertyName => $propertyValue) {
984 $columnMap = $dataMap->getColumnMap($propertyName);
985 $propertyMetaData = $classSchema->getProperty($propertyName);
986 if ($propertyMetaData['cascade'] === 'remove') {
987 if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
988 foreach ($propertyValue as $containedObject) {
989 $this->removeEntity($containedObject);
990 }
991 } elseif ($propertyValue instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
992 $this->removeEntity($propertyValue);
993 }
994 }
995 }
996 }
997
998 /**
999 * Determine the storage page ID for a given NEW record
1000 *
1001 * This does the following:
1002 * - If the domain object has an accessible property 'pid' (i.e. through a getPid() method), that is used to store the record.
1003 * - If there is a TypoScript configuration "classes.CLASSNAME.newRecordStoragePid", that is used to store new records.
1004 * - If there is no such TypoScript configuration, it uses the first value of The "storagePid" taken for reading records.
1005 *
1006 * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object
1007 * @return integer the storage Page ID where the object should be stored
1008 */
1009 protected function determineStoragePageIdForNewRecord(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object = NULL) {
1010 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
1011 if ($object !== NULL) {
1012 if (\TYPO3\CMS\Extbase\Reflection\ObjectAccess::isPropertyGettable($object, 'pid')) {
1013 $pid = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getProperty($object, 'pid');
1014 if (isset($pid)) {
1015 return (int)$pid;
1016 }
1017 }
1018 $className = get_class($object);
1019 if (isset($frameworkConfiguration['persistence']['classes'][$className]) && !empty($frameworkConfiguration['persistence']['classes'][$className]['newRecordStoragePid'])) {
1020 return (int)$frameworkConfiguration['persistence']['classes'][$className]['newRecordStoragePid'];
1021 }
1022 }
1023 $storagePidList = \TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $frameworkConfiguration['persistence']['storagePid']);
1024 return (int)$storagePidList[0];
1025 }
1026 }