EXTMVC:
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Mapper / TX_EXTMVC_Persistence_Mapper_ObjectRelationalMapper.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 *
17 * This script is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * This copyright notice MUST APPEAR in all copies of the script!
23 ***************************************************************/
24
25 require_once(PATH_t3lib . 'interfaces/interface.t3lib_singleton.php');
26 require_once(PATH_tslib . 'class.tslib_content.php');
27
28 /**
29 * A mapper to map database tables configured in $TCA on domain objects.
30 *
31 * @package TYPO3
32 * @subpackage extmvc
33 * @version $ID:$
34 */
35 class TX_EXTMVC_Persistence_Mapper_ObjectRelationalMapper implements t3lib_Singleton {
36
37 /**
38 * The content object
39 *
40 * @var tslib_cObj
41 **/
42 protected $cObj;
43
44 /**
45 * The persistence session
46 *
47 * @var TX_EXTMVC_Persistence_Session
48 **/
49 protected $session;
50
51 /**
52 * Cached data maps
53 *
54 * @var array
55 **/
56 protected $dataMaps = array();
57
58 /**
59 * Constructs a new mapper
60 *
61 */
62 public function __construct() {
63 $this->cObj = t3lib_div::makeInstance('tslib_cObj');
64 $this->session = t3lib_div::makeInstance('TX_EXTMVC_Persistence_Session');
65 $GLOBALS['TSFE']->includeTCA();
66 }
67
68 /**
69 * Finds objects matching a given WHERE Clause
70 *
71 * @param string $className The class name
72 * @param string $arguments The WHERE statement
73 * @return void
74 */
75 public function findWhere($className, $where = '1=1') {
76 // TODO check PID for records
77 $dataMap = $this->getDataMap($className);
78 // SK: Support for GroupBy, OrderBy, Limit!
79 $rows = $this->fetch($dataMap, $where);
80 $objects = $this->reconstituteObjects($dataMap, $rows);
81 return $objects;
82 }
83
84 /**
85 * Fetches rows from the database by given SQL statement snippets
86 *
87 * @param string $from FROM statement
88 * @param string $where WHERE statement
89 * @param string $groupBy GROUP BY statement
90 * @param string $orderBy ORDER BY statement
91 * @param string $limit LIMIT statement
92 * @return void
93 */
94 public function fetch($dataMap, $where = '1=1', $groupBy = '', $orderBy = '', $limit = '') {
95 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
96 '*', // TODO limit fetched fields
97 $dataMap->getTableName(),
98 $where . $this->cObj->enableFields($dataMap->getTableName()) . $this->cObj->enableFields($dataMap->getTableName()),
99 $groupBy,
100 $orderBy,
101 $limit
102 );
103 // SK: Do we want to make it possible to ignore "enableFields"?
104 // TODO language overlay; workspace overlay
105 return $rows ? $rows : array();
106 }
107
108 /**
109 * Fetches a rows from the database by given SQL statement snippets taking a relation table into account
110 *
111 * @param string Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT! You have to prepend 'AND ' to this parameter yourself!
112 * @param string Optional GROUP BY field(s), if none, supply blank string.
113 * @param string Optional ORDER BY field(s), if none, supply blank string.
114 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
115 */
116 // SK: Are SQL injections possible here? Can we somehow prevent them? I did not check it thoroughly yet, but I think they are possible
117 public function fetchWithRelationTable($parentObject, $columnMap, $where = '1=1', $groupBy = '', $orderBy = '', $limit = '') {
118 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
119 $columnMap->getChildTableName() . '.*, ' . $columnMap->getRelationTableName() . '.*',
120 $columnMap->getChildTableName() . ' LEFT JOIN ' . $columnMap->getRelationTableName() . ' ON (' . $columnMap->getChildTableName() . '.uid=' . $columnMap->getRelationTableName() . '.uid_foreign)',
121 $where . ' AND ' . $columnMap->getRelationTableName() . '.uid_local=' . t3lib_div::intval_positive($parentObject->getUid()) . $this->cObj->enableFields($columnMap->getChildTableName()) . $this->cObj->enableFields($columnMap->getChildTableName()),
122 $groupBy,
123 $orderBy,
124 $limit
125 );
126 // TODO language overlay; workspace overlay; sorting
127 return $rows ? $rows : array();
128 }
129
130 /**
131 * reconstitutes domain objects from $rows (array)
132 *
133 * @param TX_EXTMVC_Persistence_Mapper_DataMap $dataMap The data map corresponding to the domain object
134 * @param array $rows The rows array fetched from the database
135 * @return array An array of reconstituted domain objects
136 */
137 // SK: I Need to check this method more thoroughly.
138 // SK: Are loops detected during reconstitution?
139 // SK: What about "1:1" relations?
140 protected function reconstituteObjects($dataMap, array $rows) {
141 $objects = array();
142 foreach ($rows as $row) {
143 $properties = array();
144 foreach ($dataMap->getColumnMaps() as $columnMap) {
145 $properties[$columnMap->getPropertyName()] = $dataMap->convertFieldValueToPropertyValue($columnMap->getPropertyName(), $row[$columnMap->getColumnName()]);
146 }
147 $object = $this->reconstituteObject($dataMap->getClassName(), $properties);
148 foreach ($dataMap->getColumnMaps() as $columnMap) {
149 if ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
150 $where = $columnMap->getParentKeyFieldName() . '=' . intval($object->getUid());
151 $relatedDataMap = $this->getDataMap($columnMap->getChildClassName());
152 $relatedRows = $this->fetch($relatedDataMap, $where);
153 $relatedObjects = $this->reconstituteObjects($relatedDataMap, $relatedRows, $depth);
154 $object->_reconstituteProperty($columnMap->getPropertyName(), $relatedObjects);
155 } elseif ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
156 $relatedDataMap = $this->getDataMap($columnMap->getChildClassName());
157 $relatedRows = $this->fetchWithRelationTable($object, $columnMap);
158 $relatedObjects = $this->reconstituteObjects($relatedDataMap, $relatedRows, $depth);
159 $object->_reconstituteProperty($columnMap->getPropertyName(), $relatedObjects);
160 }
161 }
162 $this->session->registerReconstitutedObject($object);
163 $objects[] = $object;
164 }
165 return $objects;
166 }
167
168 /**
169 * Reconstitutes the specified object and fills it with the given properties.
170 *
171 * @param string $objectName Name of the object to reconstitute
172 * @param array $properties The names of properties and their values which should be set during the reconstitution
173 * @return object The reconstituted object
174 */
175 protected function reconstituteObject($className, array $properties = array()) {
176 // those objects will be fetched from within the __wakeup() method of the object...
177 $GLOBALS['EXTMVC']['reconstituteObject']['properties'] = $properties;
178 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
179 unset($GLOBALS['EXTMVC']['reconstituteObject']);
180 return $object;
181 }
182
183 /**
184 * Persists all objects of a persistence session
185 *
186 * @return void
187 */
188 public function persistAll() {
189 // first, persit all aggregate root objects
190 $aggregateRootClassNames = $this->session->getAggregateRootClassNames();
191 foreach ($aggregateRootClassNames as $className) {
192 $this->persistObjects($className);
193 }
194 // persist all remaining objects registered manually
195 // $this->persistObjects();
196 }
197
198 /**
199 * Persists all objects of a persitance session that are of a given class. If there
200 * is no class specified, it persits all objects of a session.
201 *
202 * @param string $className Name of the class of the objects to be persisted
203 */
204 protected function persistObjects($className = NULL) {
205 foreach ($this->session->getAddedObjects($className) as $object) {
206 $this->insertObject($object);
207 $this->session->unregisterObject($object);
208 $this->session->registerReconstitutedObject($object);
209 }
210 foreach ($this->session->getDirtyObjects($className) as $object) {
211 $this->updateObject($object);
212 $this->session->unregisterObject($object);
213 $this->session->registerReconstitutedObject($object);
214 }
215 foreach ($this->session->getRemovedObjects($className) as $object) {
216 $this->deleteObject($object);
217 $this->session->unregisterObject($object);
218 }
219 }
220
221 /**
222 * Inserts an object to the database.
223 *
224 * @return void
225 */
226 // SK: I need to check this more thorougly
227 protected function insertObject(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $parentObject = NULL, $parentPropertyName = NULL) {
228 $properties = $object->_getProperties();
229 $dataMap = $this->getDataMap(get_class($object));
230 $relations = $this->getRelations($dataMap, $properties);
231 $row = $this->getRow($dataMap, $properties);
232
233 if ($parentObject instanceof TX_EXTMVC_DomainObject_AbstractDomainObject && $parentPropertyName !== NULL) {
234 $parentDataMap = $this->getDataMap(get_class($parentObject));
235 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
236 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
237 if ($parentKeyFieldName !== NULL) {
238 $row[$parentKeyFieldName] = $parentObject->getUid();
239 }
240 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
241 if ($parentTableFieldName !== NULL) {
242 $row[$parentTableFieldName] = $parentDataMap->getTableName();
243 }
244 }
245
246 unset($row['uid']);
247 $row['pid'] = !empty($this->cObj->data['pages']) ? $this->cObj->data['pages'] : $GLOBALS['TSFE']->id;
248 $row['tstamp'] = time();
249
250 $tableName = $dataMap->getTableName();
251 $res = $GLOBALS['TYPO3_DB']->exec_INSERTquery(
252 $tableName,
253 $row
254 );
255 $object->_reconstituteProperty('uid', $GLOBALS['TYPO3_DB']->sql_insert_id());
256
257 $recursionMode = TRUE; // TODO make parametric
258 if ($recursionMode === TRUE) {
259 $this->processRelations($object, $propertyName, 'persist', $relations);
260 }
261 }
262
263 /**
264 * Updates a modified object in the database
265 *
266 * @return void
267 */
268 // SK: I need to check this more thorougly
269 protected function updateObject(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $parentObject = NULL, $parentPropertyName = NULL) {
270 $properties = $object->_getDirtyProperties();
271 $dataMap = $this->getDataMap(get_class($object));
272 $relations = $this->getRelations($dataMap, $properties);
273 $row = $this->getRow($dataMap, $properties);
274
275 unset($row['uid']);
276 $row['crdate'] = time();
277 if (!empty($GLOBALS['TSFE']->fe_user->user['uid'])) {
278 $row['cruser_id'] = $GLOBALS['TSFE']->fe_user->user['uid'];
279 }
280 if ($parentObject instanceof TX_EXTMVC_DomainObject_AbstractDomainObject && $parentPropertyName !== NULL) {
281 $parentDataMap = $this->getDataMap(get_class($parentObject));
282 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
283 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
284 if ($parentKeyFieldName !== NULL) {
285 $row[$parentKeyFieldName] = $parentObject->getUid();
286 }
287 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
288 if ($parentTableFieldName !== NULL) {
289 $row[$parentTableFieldName] = $parentDataMap->getTableName();
290 }
291 }
292
293 $tableName = $dataMap->getTableName();
294 $res = $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
295 $tableName,
296 'uid=' . $object->getUid(),
297 $row
298 );
299
300 $recursionMode = TRUE; // TODO make parametric
301 if ($recursionMode === TRUE) {
302 $this->processRelations($object, $propertyName, 'persist', $relations);
303 }
304 }
305
306 /**
307 * Deletes an object, it's 1:n related objects, and the m:n relations in relation tables (but not the m:n related objects!)
308 *
309 * @return void
310 */
311 // SK: I need to check this more thorougly
312 protected function deleteObject(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $parentObject = NULL, $parentPropertyName = NULL, $recursionMode = FALSE, $onlySetDeleted = TRUE) {
313 $relations = array();
314 $properties = $object->_getDirtyProperties();
315 $dataMap = $this->getDataMap(get_class($object));
316 $relations = $this->getRelations($dataMap, $properties);
317
318 $tableName = $dataMap->getTableName();
319 if ($onlySetDeleted === TRUE && !empty($deletedColumnName)) {
320 $deletedColumnName = $dataMap->getDeletedColumnName();
321 $res = $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
322 $tableName,
323 'uid=' . $object->getUid(),
324 array($deletedColumnName => 1)
325 );
326 } else {
327 $res = $GLOBALS['TYPO3_DB']->exec_DELETEquery(
328 $tableName,
329 'uid=' . $object->getUid()
330 );
331 }
332
333 if ($recursionMode === TRUE) {
334 $this->processRelations($object, $propertyName, 'delete', $relations);
335 }
336 }
337
338 /**
339 * Returns a table row to be inserted or updated in the database
340 *
341 * @param TX_EXTMVC_Persistence_Mapper_DataMap $dataMap The appropriate data map representing a database table
342 * @param string $properties The properties of the object
343 * @return array A single row to be inserted in the database
344 */
345 // SK: I need to check this more thorougly
346 protected function getRow(TX_EXTMVC_Persistence_Mapper_DataMap $dataMap, $properties) {
347 $relations = array();
348 foreach ($dataMap->getColumnMaps() as $columnMap) {
349 $propertyName = $columnMap->getPropertyName();
350 $columnName = $columnMap->getColumnName();
351 if ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
352 $row[$columnName] = count($properties[$propertyName]);
353 } elseif ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
354 $row[$columnName] = count($properties[$propertyName]);
355 } else {
356 if ($properties[$propertyName] !== NULL) {
357 $row[$columnName] = $dataMap->convertPropertyValueToFieldValue($properties[$propertyName]);
358 }
359 }
360 }
361 return $row;
362 }
363
364 /**
365 * Returns all property values holding child objects
366 *
367 * @param TX_EXTMVC_Persistence_Mapper_DataMap $dataMap The data map
368 * @param string $properties The object properties
369 * @return array An array of properties with related child objects
370 */
371 protected function getRelations(TX_EXTMVC_Persistence_Mapper_DataMap $dataMap, $properties) {
372 $relations = array();
373 foreach ($dataMap->getColumnMaps() as $columnMap) {
374 $propertyName = $columnMap->getPropertyName();
375 $columnName = $columnMap->getColumnName();
376 if ($columnMap->isRelation()) {
377 $relations[$propertyName] = $properties[$propertyName];
378 }
379 }
380 return $relations;
381 }
382
383 /**
384 * Processes all relations of an object. It also updates relation tables.
385 *
386 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $object The object for which the relations should be updated
387 * @param string $propertyName The name of the property holding the related child objects
388 * @param string $command The command (one of "persist", "delete"). Persist updates and inserts records as needed
389 * @param array $relations The queued relations
390 * @return void
391 */
392 protected function processRelations(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $propertyName, $command, array $relations) {
393 $dataMap = $this->getDataMap(get_class($object));
394 if ($command === 'persist') {
395 foreach ($relations as $propertyName => $relatedObjects) {
396 if (!empty($relatedObjects)) {
397 $typeOfRelation = $dataMap->getColumnMap($propertyName)->getTypeOfRelation();
398 foreach ($relatedObjects as $relatedObject) {
399 if (!$this->session->isReconstitutedObject($relatedObject)) {
400 $this->insertObject($relatedObject, $object, $propertyName);
401 if ($typeOfRelation === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
402 $this->insertRelationInRelationTable($relatedObject, $object, $propertyName);
403 }
404 } elseif ($this->session->isReconstitutedObject($relatedObject) && $relatedObject->_isDirty()) {
405 $this->updateObject($relatedObject, $object, $propertyName);
406 }
407 }
408 }
409 if ($typeOfRelation === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
410 $this->updateRelationsInRelationTable($relatedObjects, $object, $propertyName);
411 }
412 }
413 } elseif ($command === 'delete') {
414 foreach ($relations as $propertyName => $relatedObjects) {
415 foreach ($relatedObjects as $relatedObject) {
416 $this->deleteObject($relatedObject, $object, $propertyName);
417 if ($dataMap->getColumnMap($propertyName)->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
418 $this->deleteRelation($relatedObject, $object, $propertyName);
419 }
420 }
421 }
422 }
423 }
424
425 /**
426 * Inserts relation to a relation table
427 *
428 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $relatedObject The related object
429 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject The parent object
430 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
431 * @return void
432 */
433 protected function insertRelationInRelationTable(TX_EXTMVC_DomainObject_AbstractDomainObject $relatedObject, TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject, $parentPropertyName) {
434 $dataMap = $this->getDataMap(get_class($parentObject));
435 $rowToInsert = array(
436 'uid_local' => $parentObject->getUid(),
437 'uid_foreign' => $relatedObject->getUid(),
438 'tablenames' => $dataMap->getTableName(),
439 'sorting' => 9999 // TODO sorting of mm table items
440 );
441 $tableName = $dataMap->getColumnMap($parentPropertyName)->getRelationTableName();
442 $res = $GLOBALS['TYPO3_DB']->exec_INSERTquery(
443 $tableName,
444 $rowToInsert
445 );
446 }
447
448 /**
449 * Update relations in a relation table
450 *
451 * @param array $relatedObjects An array of related objects
452 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject The parent object
453 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
454 * @return void
455 */
456 protected function updateRelationsInRelationTable($relatedObjects, TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject, $parentPropertyName) {
457 $dataMap = $this->getDataMap(get_class($parentObject));
458 $tableName = $dataMap->getColumnMap($parentPropertyName)->getRelationTableName();
459 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
460 'uid_foreign',
461 $tableName,
462 'uid_local=' . $parentObject->getUid()
463 );
464 $existingRelations = array();
465 while($row = mysql_fetch_assoc($res)) {
466 $existingRelations[current($row)] = current($row);
467 }
468 $relationsToDelete = $existingRelations;
469 if (is_array($relatedObjects)) {
470 foreach ($relatedObjects as $relatedObject) {
471 $relatedObjectUid = $relatedObject->getUid();
472 if (array_key_exists($relatedObjectUid, $relationsToDelete)) {
473 unset($relationsToDelete[$relatedObjectUid]);
474 }
475 }
476 }
477 if (count($relationsToDelete) > 0) {
478 $relationsToDeleteList = implode(',', $relationsToDelete);
479 $res = $GLOBALS['TYPO3_DB']->exec_DELETEquery(
480 $tableName,
481 'uid_local=' . $parentObject->getUid() . ' AND uid_foreign IN (' . $relationsToDeleteList . ')'
482 );
483 }
484 }
485
486 /**
487 * Delegates the call to the Data Map.
488 * Returns TRUE if the property is persistable (configured in $TCA)
489 *
490 * @param string $className The property name
491 * @param string $propertyName The property name
492 * @return boolean TRUE if the property is persistable (configured in $TCA)
493 */
494 public function isPersistableProperty($className, $propertyName) {
495 $dataMap = new TX_EXTMVC_Persistence_Mapper_DataMap($className);
496 $dataMap->initialize();
497 return $dataMap->isPersistableProperty($propertyName);
498 }
499
500 /**
501 * Returns a data map for a given class name
502 *
503 * @return TX_EXTMVC_Persistence_Mapper_DataMap The data map
504 */
505 protected function getDataMap($className) {
506 // TODO Cache data maps
507 if (empty($this->dataMaps[$className])) {
508 $dataMap = new TX_EXTMVC_Persistence_Mapper_DataMap($className);
509 $dataMap->initialize();
510 $this->dataMaps[$className] = $dataMap;
511 }
512 return $this->dataMaps[$className];
513 }
514
515 }
516 ?>