Extbase:
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Backend.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
6 * All rights reserved
7 *
8 * This class is a backport of the corresponding class of FLOW3.
9 * All credits go to the v5 team.
10 *
11 * This script is part of the TYPO3 project. The TYPO3 project is
12 * free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27
28 /**
29 * A persistence backend. This backend maps objects to the relational model of the storage backend.
30 * It persists all added, removed and changed objects.
31 *
32 * @package Extbase
33 * @subpackage Persistence
34 * @version $Id: Backend.php 2183 2009-04-24 14:28:37Z k-fish $
35 */
36 class Tx_Extbase_Persistence_Backend implements Tx_Extbase_Persistence_BackendInterface, t3lib_Singleton {
37
38 /**
39 * @var Tx_Extbase_Persistence_Session
40 */
41 protected $session;
42
43 /**
44 * @var Tx_Extbase_Persistence_ObjectStorage
45 */
46 protected $aggregateRootObjects;
47
48 /**
49 * @var Tx_Extbase_Persistence_IdentityMap
50 **/
51 protected $identityMap;
52
53 /**
54 * @var Tx_Extbase_Persistence_QOM_QueryObjectModelFactoryInterface
55 */
56 protected $QOMFactory;
57
58 /**
59 * @var Tx_Extbase_Persistence_ValueFactoryInterface
60 */
61 protected $valueFactory;
62
63 /**
64 * @var Tx_Extbase_Persistence_Storage_BackendInterface
65 */
66 protected $storageBackend;
67
68 /**
69 * @var Tx_Extbase_Persistence_DataMapper
70 */
71 protected $dataMapper;
72
73 /**
74 * The TYPO3 reference index object
75 *
76 * @var t3lib_refindex
77 **/
78 protected $referenceIndex;
79
80 /**
81 * Constructs the backend
82 *
83 * @param Tx_Extbase_Persistence_Session $session The persistence session used to persist data
84 */
85 public function __construct(Tx_Extbase_Persistence_Session $session, Tx_Extbase_Persistence_Storage_BackendInterface $storageBackend) {
86 $this->session = $session;
87 $this->storageBackend = $storageBackend;
88 $this->referenceIndex = t3lib_div::makeInstance('t3lib_refindex');
89 $this->aggregateRootObjects = new Tx_Extbase_Persistence_ObjectStorage();
90 $this->persistenceBackend = $GLOBALS['TYPO3_DB']; // FIXME This is just an intermediate solution
91 }
92
93 /**
94 * Injects the DataMapper to map nodes to objects
95 *
96 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
97 * @return void
98 */
99 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper) {
100 $this->dataMapper = $dataMapper;
101 }
102
103 /**
104 * Injects the identity map
105 *
106 * @param Tx_Extbase_Persistence_IdentityMap $identityMap
107 * @return void
108 * @internal
109 */
110 public function injectIdentityMap(Tx_Extbase_Persistence_IdentityMap $identityMap) {
111 $this->identityMap = $identityMap;
112 }
113
114 /**
115 * Injects the QueryObjectModelFactory
116 *
117 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelFactoryInterface $dataMapper
118 * @return void
119 */
120 public function injectQOMFactory(Tx_Extbase_Persistence_QOM_QueryObjectModelFactoryInterface $QOMFactory) {
121 $this->QOMFactory = $QOMFactory;
122 }
123
124 /**
125 * Injects the ValueFactory
126 *
127 * @param Tx_Extbase_Persistence_ValueFactoryInterface $valueFactory
128 * @return void
129 */
130 public function injectValueFactory(Tx_Extbase_Persistence_ValueFactoryInterface $valueFactory) {
131 $this->valueFactory = $valueFactory;
132 }
133
134 /**
135 * Returns the repository session
136 *
137 * @return Tx_Extbase_Persistence_Session
138 */
139 public function getSession() {
140 return $this->session;
141 }
142
143 /**
144 * Returns the current QOM factory
145 *
146 * @return Tx_Extbase_Persistence_QOM_QueryObjectModelFactoryInterface
147 * @internal
148 */
149 public function getQOMFactory() {
150 return $this->QOMFactory;
151 }
152
153 /**
154 * Returns the current value factory
155 *
156 * @return Tx_Extbase_Persistence_ValueFactoryInterface
157 * @internal
158 */
159 public function getValueFactory() {
160 return $this->valueFactory;
161 }
162
163 /**
164 * Returns the current identityMap
165 *
166 * @return Tx_Extbase_Persistence_IdentityMap
167 * @internal
168 */
169 public function getIdentityMap() {
170 return $this->identityMap;
171 }
172
173 /**
174 * Returns the (internal) identifier for the object, if it is known to the
175 * backend. Otherwise NULL is returned.
176 *
177 * @param object $object
178 * @return string The identifier for the object if it is known, or NULL
179 */
180 public function getUidByObject($object) {
181 if ($this->identityMap->hasObject($object)) {
182 return $this->identityMap->getUidByObject($object);
183 } else {
184 return NULL;
185 }
186 }
187
188 /**
189 * Checks if the given object has ever been persisted.
190 *
191 * @param object $object The object to check
192 * @return boolean TRUE if the object is new, FALSE if the object exists in the repository
193 */
194 public function isNewObject($object) {
195 return ($this->getUidByObject($object) === NULL);
196 }
197
198 /**
199 * Replaces the given object by the second object.
200 *
201 * This method will unregister the existing object at the identity map and
202 * register the new object instead. The existing object must therefore
203 * already be registered at the identity map which is the case for all
204 * reconstituted objects.
205 *
206 * The new object will be identified by the uid which formerly belonged
207 * to the existing object. The existing object looses its uid.
208 *
209 * @param object $existingObject The existing object
210 * @param object $newObject The new object
211 * @return void
212 */
213 public function replaceObject($existingObject, $newObject) {
214 $existingUid = $this->getUidByObject($existingObject);
215 if ($existingUid === NULL) throw new Tx_Extbase_Persistence_Exception_UnknownObject('The given object is unknown to this persistence backend.', 1238070163);
216
217 $this->identityMap->unregisterObject($existingObject);
218 $this->identityMap->registerObject($newObject, $existingUid);
219 }
220
221 /**
222 * Sets the aggregate root objects
223 *
224 * @param Tx_Extbase_Persistence_ObjectStorage $objects
225 * @return void
226 */
227 public function setAggregateRootObjects(Tx_Extbase_Persistence_ObjectStorage $objects) {
228 $this->aggregateRootObjects = $objects;
229 }
230
231 /**
232 * Sets the deleted objects
233 *
234 * @param Tx_Extbase_Persistence_ObjectStorage $objects
235 * @return void
236 */
237 public function setDeletedObjects(Tx_Extbase_Persistence_ObjectStorage $objects) {
238 $this->deletedObjects = $objects;
239 }
240
241 /**
242 * Commits the current persistence session.
243 *
244 * @return void
245 */
246 public function commit() {
247 $this->persistObjects();
248 $this->processDeletedObjects();
249 }
250
251 /**
252 * Traverse and persist all aggregate roots and their object graph.
253 *
254 * @return void
255 */
256 protected function persistObjects() {
257 foreach ($this->aggregateRootObjects as $object) {
258 $this->persistObject($object);
259 }
260 }
261
262 /**
263 * Inserts an objects corresponding row into the database. If the object is a value object an
264 * existing instance will be looked up.
265 *
266 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to be inserted
267 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The parent object
268 * @param string $parentPropertyName The name of the property the object is stored in
269 * @return void
270 */
271 protected function persistObject($object, $parentObject = NULL, $parentPropertyName = NULL, $processQueue = TRUE) {
272 $row = array();
273 $queue = array();
274 $className = get_class($object);
275 $dataMap = $this->dataMapper->getDataMap($className);
276 $properties = $object->_getProperties();
277
278 if ($object instanceof Tx_Extbase_DomainObject_AbstractValueObject) {
279 $this->checkForAlreadyPersistedValueObject($object);
280 }
281
282
283 foreach ($properties as $propertyName => $propertyValue) {
284 if ($dataMap->isPersistableProperty($propertyName) && ($propertyValue instanceof Tx_Extbase_Persistence_LazyLoadingProxy)) {
285 continue;
286 }
287
288 $columnMap = $dataMap->getColumnMap($propertyName);
289 $columnName = $columnMap->getColumnName();
290 if ($object->_isNew() || $object->_isDirty($propertyName)) {
291 if ($columnMap->isRelation()) {
292 if (($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) || ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY)) {
293 $row[$columnName] = count($properties[$propertyName]);
294 foreach ($propertyValue as $containedObject) {
295 $queue[] = array($propertyName => $containedObject);
296 }
297 } elseif ($propertyValue instanceof Tx_Extbase_DomainObject_DomainObjectInterface) {
298 // TODO Handle Value Objects different
299 if ($propertyValue->_isNew()) {
300 $this->persistObject($propertyValue);
301 }
302 $row[$columnName] = $propertyValue->getUid();
303 }
304 } else {
305 $row[$columnName] = $dataMap->convertPropertyValueToFieldValue($properties[$propertyName], FALSE);
306 }
307 }
308 }
309
310 if ($object->_isNew()) {
311 $this->insertObject($object, $parentObject, $parentPropertyName, $row);
312 } elseif ($object->_isDirty()) {
313 $this->updateObject($object, $parentObject, $parentPropertyName, $row);
314 }
315
316 if ($parentObject instanceof Tx_Extbase_DomainObject_DomainObjectInterface && !empty($parentPropertyName)) {
317 $parentClassName = get_class($parentObject);
318 $parentDataMap = $this->dataMapper->getDataMap($parentClassName);
319 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
320
321 if (($parentColumnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY)) {
322 $this->insertRelation($object, $parentObject, $parentPropertyName);
323 }
324 }
325
326 if ($object instanceof Tx_Extbase_DomainObject_AbstractEntity) {
327 $object->_memorizeCleanState();
328 }
329
330 if ($processQueue === TRUE) {
331 foreach ($queue as $queuedObjects) {
332 foreach($queuedObjects as $propertyName => $queuedObject) {
333 $this->persistObject($queuedObject, $object, $propertyName);
334 }
335 }
336 }
337
338 }
339
340 /*
341 * Tests, if the given Domain Object already exists in the storage backend
342 *
343 * @param Tx_Extbase_DomainObject_AbstractValueObject $object The object to be tested
344 */
345 protected function checkForAlreadyPersistedValueObject(Tx_Extbase_DomainObject_AbstractValueObject $object) {
346 $dataMap = $this->dataMapper->getDataMap(get_class($object));
347 $properties = $object->_getProperties();
348 $result = $this->storageBackend->hasValueObject($properties, $dataMap);
349 if ($result !== FALSE) {
350 $object->_setProperty('uid', $result);
351 }
352 }
353
354 /**
355 * Inserts an object in the storage
356 *
357 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to be insterted in the storage
358 * @param Tx_Extbase_DomainObject_AbstractEntity|NULL $parentObject The parent object (if any)
359 * @param string|NULL $parentPropertyName The name of the property
360 * @param array $row The $row
361 */
362 protected function insertObject(Tx_Extbase_DomainObject_DomainObjectInterface $object, Tx_Extbase_DomainObject_AbstractEntity $parentObject = NULL, $parentPropertyName = NULL, array &$row) {
363 $className = get_class($object);
364 $dataMap = $this->dataMapper->getDataMap($className);
365 $tableName = $dataMap->getTableName();
366 $this->addCommonFieldsToRow($object, $parentObject, $parentPropertyName, $row);
367 $uid = $this->storageBackend->addRow(
368 $tableName,
369 $row
370 );
371 $object->_setProperty('uid', $uid);
372 $this->referenceIndex->updateRefIndexTable($tableName, $uid);
373 }
374
375 /**
376 * Inserts mm-relation into a relation table
377 *
378 * @param Tx_Extbase_DomainObject_DomainObjectInterface $relatedObject The related object
379 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The parent object
380 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
381 * @return void
382 */
383 protected function insertRelation(Tx_Extbase_DomainObject_DomainObjectInterface $relatedObject, Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $parentPropertyName) {
384 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
385 $row = array(
386 'uid_local' => (int)$parentObject->getUid(), // TODO Aliases for relation field names
387 'uid_foreign' => (int)$relatedObject->getUid(),
388 'tablenames' => $dataMap->getTableName(),
389 'sorting' => 9999 // TODO sorting of mm table items
390 );
391 $tableName = $dataMap->getColumnMap($parentPropertyName)->getRelationTableName();
392 $res = $this->storageBackend->addRow(
393 $tableName,
394 $row
395 );
396 return $res;
397 }
398
399 /**
400 * Updates a given object in the storage
401 *
402 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to be insterted in the storage
403 * @param Tx_Extbase_DomainObject_AbstractEntity|NULL $parentObject The parent object (if any)
404 * @param string|NULL $parentPropertyName The name of the property
405 * @param array $row The $row
406 */
407 protected function updateObject(Tx_Extbase_DomainObject_DomainObjectInterface $object, $parentObject = NULL, $parentPropertyName = NULL, array &$row) {
408 $className = get_class($object);
409 $dataMap = $this->dataMapper->getDataMap($className);
410 $tableName = $dataMap->getTableName();
411 $this->addCommonFieldsToRow($object, $parentObject, $parentPropertyName, $row);
412 $uid = $object->getUid();
413 $row['uid'] = $uid;
414 $res = $this->storageBackend->updateRow(
415 $tableName,
416 $row
417 );
418 $this->referenceIndex->updateRefIndexTable($tableName, $uid);
419 return $res;
420 }
421
422 /**
423 * Returns a table row to be inserted or updated in the database
424 *
425 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The appropriate data map representing a database table
426 * @param array $properties The properties of the object
427 * @return array A single row to be inserted in the database
428 */
429 protected function addCommonFieldsToRow(Tx_Extbase_DomainObject_DomainObjectInterface $object, $parentObject = NULL, $parentPropertyName = NULL, array &$row) {
430 $className = get_class($object);
431 $dataMap = $this->dataMapper->getDataMap($className);
432 if ($dataMap->hasCreationDateColumn() && $object->_isNew()) {
433 $row[$dataMap->getCreationDateColumnName()] = $GLOBALS['EXEC_TIME'];
434 }
435 if ($dataMap->hasTimestampColumn()) {
436 $row[$dataMap->getTimestampColumnName()] = $GLOBALS['EXEC_TIME'];
437 }
438 if ($dataMap->hasPidColumn()) {
439 // FIXME Make the settings from $this->cObj available
440 $row['pid'] = !empty($this->cObj->data['pages']) ? $this->cObj->data['pages'] : $GLOBALS['TSFE']->id;
441 }
442 if ($parentObject instanceof Tx_Extbase_DomainObject_DomainObjectInterface && !empty($parentPropertyName)) {
443 $parentDataMap = $this->dataMapper->getDataMap(get_class($parentObject));
444 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
445 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
446 if ($parentKeyFieldName !== NULL) {
447 $row[$parentKeyFieldName] = $parentObject->getUid();
448 }
449 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
450 if ($parentTableFieldName !== NULL) {
451 $row[$parentTableFieldName] = $parentDataMap->getTableName();
452 }
453 }
454 }
455
456 /**
457 * Inserts and updates all relations of an object. It also inserts and updates data in relation tables.
458 *
459 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object for which the relations should be updated
460 * @param string $propertyName The name of the property holding the related child objects
461 * @param array $relations The queued relations
462 * @return void
463 */
464 protected function persistRelations(Tx_Extbase_DomainObject_DomainObjectInterface $object, $propertyName, array $relations) {
465 $dataMap = $this->dataMapper->getDataMap(get_class($object));
466 foreach ($relations as $propertyName => $relatedObjects) {
467 if (!empty($relatedObjects)) {
468 $typeOfRelation = $dataMap->getColumnMap($propertyName)->getTypeOfRelation();
469 foreach ($relatedObjects as $relatedObject) {
470 if ($relatedObject->_isNew()) {
471 $this->persistObject($relatedObject, $object, $propertyName);
472 if ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
473 $this->insertRelationInRelationTable($relatedObject, $object, $propertyName);
474 }
475 } elseif ($relatedObject->_isDirty()) {
476 $this->persistObject($relatedObject, $object, $propertyName);
477 }
478 }
479 }
480 }
481 }
482
483 /**
484 * Iterate over deleted objects and process them
485 *
486 * @return void
487 */
488 protected function processDeletedObjects() {
489 foreach ($this->deletedObjects as $object) {
490 $this->deleteObject($object);
491 if ($this->identityMap->hasObject($object)) {
492 $this->session->registerRemovedObject($object);
493 $this->identityMap->unregisterObject($object);
494 }
495 }
496 $this->deletedObjects = new Tx_Extbase_Persistence_ObjectStorage();
497 }
498
499 /**
500 * Deletes an object, it's 1:n related objects, and the m:n relations in relation tables (but not the m:n related objects!)
501 *
502 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to be insterted in the storage
503 * @param Tx_Extbase_DomainObject_AbstractEntity|NULL $parentObject The parent object (if any)
504 * @param string|NULL $parentPropertyName The name of the property
505 * @param bool $markAsDeleted Shold we only mark the row as deleted instead of deleting (TRUE by default)?
506 * @param bool $recurseIntoRelations Shold we delete also dependant aggregates (FALSE by default)?
507 * @return void
508 */
509 protected function deleteObject(Tx_Extbase_DomainObject_DomainObjectInterface $object, $parentObject = NULL, $parentPropertyName = NULL, $markAsDeleted = TRUE, $recurseIntoRelations = FALSE) {
510 // TODO Implement recursive deletions
511 $dataMap = $this->dataMapper->getDataMap(get_class($object));
512 $tableName = $dataMap->getTableName();
513 if ($markAsDeleted === TRUE && $dataMap->hasDeletedColumn()) {
514 $deletedColumnName = $dataMap->getDeletedColumnName();
515 $res = $this->storageBackend->updateRow(
516 $tableName,
517 array(
518 'uid' => $object->getUid(),
519 $deletedColumnName => 1
520 )
521 );
522 } else {
523 $res = $this->storageBackend->removeRow(
524 $tableName,
525 $object->getUid()
526 );
527 }
528 $this->referenceIndex->updateRefIndexTable($tableName, $uid);
529 }
530
531 /**
532 * Deletes all relations of an object.
533 *
534 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object for which the relations should be updated
535 * @param string $propertyName The name of the property holding the related child objects
536 * @param array $relations The queued relations
537 * @return void
538 */
539 protected function deleteRelatedObjects(Tx_Extbase_DomainObject_DomainObjectInterface $object, array $relations) {
540 $dataMap = $this->dataMapper->getDataMap(get_class($object));
541 foreach ($relations as $propertyName => $relatedObjects) {
542 if (is_array($relatedObjects)) {
543 foreach ($relatedObjects as $relatedObject) {
544 $this->deleteObject($relatedObject, $object, $propertyName);
545 if ($dataMap->getColumnMap($propertyName)->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
546 $this->deleteRelationInRelationTable($relatedObject, $object, $propertyName);
547 }
548 }
549 }
550 }
551 }
552
553 /**
554 * Update relations in a relation table
555 *
556 * @param array $relatedObjects An array of related objects
557 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The parent object
558 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
559 * @return void
560 */
561 protected function deleteRelationInRelationTable($relatedObject, Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $parentPropertyName) {
562 $dataMap = $this->dataMapper->getDataMap(get_class($parentObject));
563 $tableName = $dataMap->getColumnMap($parentPropertyName)->getRelationTableName();
564 // TODO Remove dependency to the t3lib_db instance
565 $res = $this->persistenceBackend->exec_SELECTquery(
566 'uid_foreign',
567 $tableName,
568 'uid_local=' . $parentObject->getUid()
569 );
570 $existingRelations = array();
571 while($row = $this->persistenceBackend->sql_fetch_assoc($res)) {
572 $existingRelations[current($row)] = current($row);
573 }
574 $relationsToDelete = $existingRelations;
575 if (is_array($relatedObject)) {
576 foreach ($relatedObject as $relatedObject) {
577 $relatedObjectUid = $relatedObject->getUid();
578 if (array_key_exists($relatedObjectUid, $relationsToDelete)) {
579 unset($relationsToDelete[$relatedObjectUid]);
580 }
581 }
582 }
583 if (count($relationsToDelete) > 0) {
584 $relationsToDeleteList = implode(',', $relationsToDelete);
585 $res = $this->persistenceBackend->exec_DELETEquery(
586 $tableName,
587 'uid_local=' . $parentObject->getUid() . ' AND uid_foreign IN (' . $relationsToDeleteList . ')'
588 );
589 }
590 }
591
592 /**
593 * Delegates the call to the Data Map.
594 * Returns TRUE if the property is persistable (configured in $TCA)
595 *
596 * @param string $className The property name
597 * @param string $propertyName The property name
598 * @return boolean TRUE if the property is persistable (configured in $TCA)
599 */
600 public function isPersistableProperty($className, $propertyName) {
601 $dataMap = $this->dataMapper->getDataMap($className);
602 return $dataMap->isPersistableProperty($propertyName);
603 }
604
605 }
606
607 ?>