5aeb7abbd748c6d777637741c8181fb1dce167d9
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Mapper / DataMapper.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 /**
26 * A mapper to map database tables configured in $TCA on domain objects.
27 *
28 * @package Extbase
29 * @subpackage Persistence\Mapper
30 * @version $ID:$
31 */
32 class Tx_Extbase_Persistence_Mapper_DataMapper implements t3lib_Singleton {
33
34 /**
35 * @var Tx_Extbase_Persistence_IdentityMap
36 */
37 protected $identityMap;
38
39 /**
40 * @var Tx_Extbase_Reflection_Service
41 */
42 protected $reflectionService;
43
44 /**
45 * @var Tx_Extbase_Persistence_QOM_QueryObjectModelFactory
46 */
47 protected $QomFactory;
48
49 /**
50 * @var Tx_Extbase_Persistence_Session
51 */
52 protected $persistenceSession;
53
54 /**
55 * A reference to the page select object providing methods to perform language and work space overlays
56 *
57 * @var t3lib_pageSelect
58 **/
59 protected $pageSelectObject;
60
61 /**
62 * Cached data maps
63 *
64 * @var array
65 **/
66 protected $dataMaps = array();
67
68 /**
69 * @var Tx_Extbase_Persistence_QueryFactoryInterface
70 */
71 protected $queryFactory;
72
73 /**
74 * The TYPO3 reference index object
75 *
76 * @var t3lib_refindex
77 **/
78 protected $referenceIndex;
79
80 /**
81 * Constructs a new mapper
82 *
83 */
84 public function __construct() {
85 $this->queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
86 }
87
88 /**
89 * Injects the identity map
90 *
91 * @param Tx_Extbase_Persistence_IdentityMap $identityMap
92 * @return void
93 */
94 public function injectIdentityMap(Tx_Extbase_Persistence_IdentityMap $identityMap) {
95 $this->identityMap = $identityMap;
96 }
97
98 /**
99 * Injects the persistence session
100 *
101 * @param Tx_Extbase_Persistence_Session $persistenceSession
102 * @return void
103 */
104 public function injectSession(Tx_Extbase_Persistence_Session $persistenceSession) {
105 $this->persistenceSession = $persistenceSession;
106 }
107
108 /**
109 * Injects the Reflection Service
110 *
111 * @param Tx_Extbase_Reflection_Service
112 * @return void
113 */
114 public function injectReflectionService(Tx_Extbase_Reflection_Service $reflectionService) {
115 $this->reflectionService = $reflectionService;
116 }
117
118 /**
119 * Sets the query object model factory
120 *
121 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelFactory $qomFactory
122 * @return void
123 */
124 public function setQomFactory(Tx_Extbase_Persistence_QOM_QueryObjectModelFactory $qomFactory) {
125 $this->qomFactory = $qomFactory;
126 }
127
128 /**
129 * Maps the (aggregate root) rows and registers them as reconstituted
130 * with the session.
131 *
132 * @param Tx_Extbase_Persistence_RowIteratorInterface $rows
133 * @return array
134 */
135 public function map($className, ARRAY $rows) {
136 $objects = array();
137 foreach ($rows as $row) {
138 $objects[] = $this->mapSingleRow($className, $row);
139 }
140 return $objects;
141 }
142
143 /**
144 * Maps a single node into the object it represents
145 *
146 * @param Tx_Extbase_Persistence_RowInterface $node
147 * @return object
148 */
149 protected function mapSingleRow($className, array $row) {
150 if ($this->identityMap->hasIdentifier($row['uid'], $className)) {
151 $object = $this->identityMap->getObjectByIdentifier($row['uid'], $className);
152 } else {
153 $object = $this->createEmptyObject($className);
154 $this->identityMap->registerObject($object, $row['uid']);
155 $this->thawProperties($object, $row);
156 $object->_memorizeCleanState();
157 $this->persistenceSession->registerReconstitutedObject($object);
158 }
159 return $object;
160 }
161
162 /**
163 * Creates a skeleton of the specified object
164 *
165 * @param string $className Name of the class to create a skeleton for
166 * @return object The object skeleton
167 */
168 protected function createEmptyObject($className) {
169 // Note: The class_implements() function also invokes autoload to assure that the interfaces
170 // and the class are loaded. Would end up with __PHP_Incomplete_Class without it.
171 if (!in_array('Tx_Extbase_DomainObject_DomainObjectInterface', class_implements($className))) throw new Tx_Extbase_Object_Exception_CannotReconstituteObject('Cannot create empty instance of the class "' . $className . '" because it does not implement the Tx_Extbase_DomainObject_DomainObjectInterface.', 1234386924);
172 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
173 return $object;
174 }
175
176 /**
177 * Sets the given properties on the object.
178 *
179 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to set properties on
180 * @param Tx_Extbase_Persistence_RowInterface $row
181 * @return void
182 */
183 protected function thawProperties(Tx_Extbase_DomainObject_DomainObjectInterface $object, array $row) {
184 $className = get_class($object);
185 $dataMap = $this->getDataMap($className);
186 $properties = $object->_getProperties();
187 $localizedUid = $row['_LOCALIZED_UID'];
188 if ($localizedUid !== NULL) {
189 $object->_setProperty('uid', $localizedUid);
190 $object->_setProperty('_localizationParentUid', $row['uid']);
191 } else {
192 $object->_setProperty('uid', $row['uid']);
193 }
194 unset($properties['uid']);
195 foreach ($properties as $propertyName => $propertyValue) {
196 if (!$dataMap->isPersistableProperty($propertyName)) continue;
197 $columnMap = $dataMap->getColumnMap($propertyName);
198 $columnName = $columnMap->getColumnName();
199 $propertyValue = NULL;
200
201 $propertyMetaData = $this->reflectionService->getClassSchema($className)->getProperty($propertyName);
202 $propertyType = Tx_Extbase_Persistence_PropertyType::valueFromType($propertyMetaData['type']);
203
204 if ($propertyType == Tx_Extbase_Persistence_PropertyType::UNDEFINED) {
205 $propertyType = $columnMap->getPropertyType();
206 }
207
208 switch ($propertyType) {
209 case Tx_Extbase_Persistence_PropertyType::STRING;
210 case Tx_Extbase_Persistence_PropertyType::DATE;
211 case Tx_Extbase_Persistence_PropertyType::LONG;
212 case Tx_Extbase_Persistence_PropertyType::DOUBLE;
213 case Tx_Extbase_Persistence_PropertyType::BOOLEAN;
214 if (isset($row[$columnName])) {
215 $rawPropertyValue = $row[$columnName];
216 $propertyValue = $dataMap->convertFieldValueToPropertyValue($propertyType, $rawPropertyValue);
217 }
218 break;
219 case (Tx_Extbase_Persistence_PropertyType::REFERENCE):
220 $propertyValue = $row[$columnName];
221 if (!is_null($propertyValue)) {
222 $fieldValue = $row[$columnName];
223 $result = $this->fetchRelated($object, $propertyName, $fieldValue);
224 $propertyValue = $this->mapResultToPropertyValue($object, $propertyName, $result);
225 }
226 break;
227 default:
228 // FIXME throw exception
229 break;
230 }
231 $object->_setProperty($propertyName, $propertyValue);
232 }
233 }
234
235 /**
236 * Fetches a collection of objects related to a property of a parent object
237 *
238 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
239 * @param string $propertyName The name of the proxied property in it's parent
240 * @param mixed $fieldValue The raw field value.
241 * @param bool $enableLazyLoading A flag indication if the related objects should be lazy loaded
242 * @param bool $performLanguageOverlay A flag indication if the related objects should be localized
243 * @return mixed The result
244 */
245 public function fetchRelated(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '', $enableLazyLoading = TRUE, $performLanguageOverlay = TRUE) {
246 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
247 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
248 if ($enableLazyLoading === TRUE && ($propertyMetaData['lazy'] || ($columnMap->getLoadingStrategy() !== Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_EAGER))) {
249 if (($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') || ($columnMap->getLoadingStrategy() === Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_LAZY_STORAGE)) {
250 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyObjectStorage', $parentObject, $propertyName, $fieldValue);
251 } else {
252 if (empty($fieldValue)) {
253 $result = NULL;
254 } else {
255 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyLoadingProxy', $parentObject, $propertyName, $fieldValue);
256 }
257 }
258 } else {
259 $result = $this->fetchRelatedEager($parentObject, $propertyName, $fieldValue, $performLanguageOverlay);
260 }
261 return $result;
262 }
263
264 /**
265 * Fetches the related objects from the storage backend.
266 *
267 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
268 * @param string $propertyName The name of the proxied property in it's parent
269 * @param mixed $fieldValue The raw field value.
270 * @param bool $performLanguageOverlay A flag indication if the related objects should be localized
271 * @return void
272 */
273 protected function fetchRelatedEager(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '', $performLanguageOverlay = TRUE) {
274 if ($fieldValue === '') return array();
275 $query = $this->getPreparedQuery($parentObject, $propertyName, $fieldValue);
276 $query->getQuerySettings()->setRespectSysLanguage($performLanguageOverlay);
277 return $query->execute();
278 }
279
280 /**
281 * Builds and returns the prepared query, ready to be executed.
282 *
283 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject
284 * @param string $propertyName
285 * @param string $fieldValue
286 * @return void
287 */
288 protected function getPreparedQuery(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '') {
289 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
290 $queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
291 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
292 $childSortByFieldName = $columnMap->getChildSortByFieldName();
293 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
294 $query = $queryFactory->create($this->getType($parentObject, $propertyName));
295 if (isset($parentKeyFieldName)) {
296 $query->matching($query->equals($parentKeyFieldName, $parentObject->getUid()));
297 } else {
298 $query->matching($query->withUid(intval($fieldValue)));
299 }
300 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
301 $query = $queryFactory->create($this->getElementType($parentObject, $propertyName));
302 // TODO: This is an ugly hack, just ignoring the storage page state from here. Actually, the query settings would have to be passed into the DataMapper, so we can respect
303 // enableFields and storage page settings.
304 $query->getQuerySettings()->setRespectStoragePage(FALSE);
305 if (!empty($childSortByFieldName)) {
306 $query->setOrderings(array($childSortByFieldName => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
307 }
308 if (isset($parentKeyFieldName)) {
309 $query->matching($query->equals($parentKeyFieldName, $parentObject->getUid()));
310 } else {
311 $query->matching($query->in('uid', t3lib_div::intExplode(',', $fieldValue)));
312 }
313 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
314 $query = $queryFactory->create($this->getElementType($parentObject, $propertyName));
315 // TODO: This is an ugly hack, just ignoring the storage page state from here. Actually, the query settings would have to be passed into the DataMapper, so we can respect
316 // enableFields and storage page settings.
317 $query->getQuerySettings()->setRespectStoragePage(FALSE);
318 $relationTableName = $columnMap->getRelationTableName();
319 $left = $this->qomFactory->selector(NULL, $relationTableName);
320 $childClassName = $this->getElementType($parentObject, $propertyName);
321 $childTableName = $columnMap->getChildTableName();
322 $right = $this->qomFactory->selector($childClassName, $childTableName);
323 $joinCondition = $this->qomFactory->equiJoinCondition($relationTableName, $columnMap->getChildKeyFieldName(), $childTableName, 'uid');
324 $source = $this->qomFactory->join(
325 $left,
326 $right,
327 Tx_Extbase_Persistence_QueryInterface::JCR_JOIN_TYPE_INNER,
328 $joinCondition
329 );
330
331 $query->setSource($source);
332 if (!empty($childSortByFieldName)) {
333 $query->setOrderings(array($relationTableName . '.' . $childSortByFieldName => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
334 }
335
336 // attempt to support MM_match_fields
337 $conditions = $query->equals($parentKeyFieldName, $parentObject->getUid());
338
339 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
340 if (count($relationTableMatchFields)) {
341 foreach($relationTableMatchFields as $relationTableMatchFieldName => $relationTableMatchFieldValue) {
342 $relationMatchCondition = $query->equals($relationTableName . '.' . $relationTableMatchFieldName, $relationTableMatchFieldValue);
343 $conditions = $query->logicalAnd($conditions, $relationMatchCondition);
344 }
345 }
346 $query->matching($conditions);
347
348 } else {
349 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
350 }
351 return $query;
352 }
353
354 /**
355 * Returns the given result as property value of the specified property type.
356 *
357 * @param mixed $result The result could be an object or an ObjectStorage
358 * @param array $propertyMetaData The property meta data
359 * @return void
360 */
361 public function mapResultToPropertyValue(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $result) {
362 if ($result instanceof Tx_Extbase_Persistence_LoadingStrategyInterface) {
363 $propertyValue = $result;
364 } else {
365 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
366 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
367 if (in_array($propertyMetaData['type'], array('array', 'ArrayObject', 'Tx_Extbase_Persistence_ObjectStorage'))) {
368 $elementType = $this->getElementType($parentObject, $propertyName);
369 $objects = array();
370 foreach ($result as $value) {
371 $objects[] = $value;
372 }
373
374 if ($propertyMetaData['type'] === 'ArrayObject') {
375 $propertyValue = new ArrayObject($objects);
376 } elseif ($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') {
377 $propertyValue = new Tx_Extbase_Persistence_ObjectStorage();
378 foreach ($objects as $object) {
379 $propertyValue->attach($object);
380 }
381 } else {
382 $propertyValue = $objects;
383 }
384 } elseif (strpos($propertyMetaData['type'], '_') !== FALSE) {
385 $propertyValue = current($result);
386 }
387 }
388 return $propertyValue;
389 }
390
391 /**
392 * Counts the number of related objects assigned to a property of a parent object
393 *
394 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
395 * @param string $propertyName The name of the proxied property in it's parent
396 * @param mixed $fieldValue The raw field value.
397 */
398 public function countRelated(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '') {
399 $query = $this->getPreparedQuery($parentObject, $propertyName, $fieldValue);
400 return $query->count();
401 }
402
403 /**
404 * Delegates the call to the Data Map.
405 * Returns TRUE if the property is persistable (configured in $TCA)
406 *
407 * @param string $className The property name
408 * @param string $propertyName The property name
409 * @return boolean TRUE if the property is persistable (configured in $TCA)
410 */
411 public function isPersistableProperty($className, $propertyName) {
412 $dataMap = $this->getDataMap($className);
413 return $dataMap->isPersistableProperty($propertyName);
414 }
415
416 /**
417 * Returns a data map for a given class name
418 *
419 * @param string $className The class name you want to fetch the Data Map for
420 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
421 */
422 public function getDataMap($className) {
423 if (!is_string($className) || strlen($className) === 0) throw new Tx_Extbase_Persistence_Exception('No class name was given to retrieve the Data Map for.', 1251315965);
424 if (!isset($this->dataMaps[$className])) {
425 // FIXME This is too expensive for table name aliases -> implement a DataMapBuilder (knowing the aliases defined in $TCA)
426 $columnMapping = array();
427 $tableName = '';
428 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
429 if (is_array($extbaseSettings['persistence']['classes'][$className])) {
430 $persistenceSettings = $extbaseSettings['persistence']['classes'][$className];
431 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
432 $tableName = $persistenceSettings['mapping']['tableName'];
433 }
434 if (is_array($persistenceSettings['mapping']['columns'])) {
435 $columnMapping = $persistenceSettings['mapping']['columns'];
436 }
437 } elseif (class_exists($className)) {
438 foreach (class_parents($className) as $parentClassName) {
439 $persistenceSettings = $extbaseSettings['persistence']['classes'][$parentClassName];
440 if (is_array($persistenceSettings)) {
441 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
442 $tableName = $persistenceSettings['mapping']['tableName'];
443 }
444 if (is_array($persistenceSettings['mapping']['columns'])) {
445 $columnMapping = $persistenceSettings['mapping']['columns'];
446 }
447 }
448 break;
449 }
450 } else {
451 throw new Tx_Extbase_Persistence_Exception('Could not determine a Data Map for given class name.', 1256067130);
452 }
453
454 $dataMap = new Tx_Extbase_Persistence_Mapper_DataMap($className, $tableName, $columnMapping);
455 $this->dataMaps[$className] = $dataMap;
456 }
457 return $this->dataMaps[$className];
458 }
459
460 /**
461 * Returns the selector (table) name for a given class name.
462 *
463 * @param string $className
464 * @return string The selector name
465 */
466 public function convertClassNameToTableName($className) {
467 return $this->getDataMap($className)->getTableName();
468 }
469
470 /**
471 * Returns the column name for a given property name of the specified class.
472 *
473 * @param string $className
474 * @param string $propertyName
475 * @return string The column name
476 */
477 public function convertPropertyNameToColumnName($propertyName, $className = '') {
478 if (!empty($className)) {
479 $dataMap = $this->getDataMap($className);
480 if ($dataMap !== NULL) {
481 $columnMap = $dataMap->getColumnMap($propertyName);
482 if ($columnMap !== NULL) {
483 return $columnMap->getColumnName();
484 }
485 }
486 }
487 return Tx_Extbase_Utility_Extension::convertCamelCaseToLowerCaseUnderscored($propertyName);
488 }
489
490 /**
491 * Returns the type of a child object.
492 *
493 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
494 * @param string $propertyName The name of the proxied property in it's parent
495 * @return string The class name of the child object
496 */
497 protected function getType(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName) {
498 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
499 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
500 $childClassName = $columnMap->getChildClassName();
501 if (!empty($childClassName)) {
502 $elementType = $childClassName;
503 } elseif (!empty($propertyMetaData['type'])) {
504 $elementType = $propertyMetaData['type'];
505 } else {
506 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('Could not determine the child object object type.', 1251315967);
507 }
508 return $elementType;
509 }
510
511 /**
512 * Returns the type of the elements inside an ObjectStorage or array.
513 *
514 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
515 * @param string $propertyName The name of the proxied property in it's parent
516 * @return string The class name of the elements inside an ObjectStorage
517 */
518 protected function getElementType(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName) {
519 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
520 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
521 $childClassName = $columnMap->getChildClassName();
522 if (!empty($childClassName)) {
523 $elementType = $childClassName;
524 } elseif (!empty($propertyMetaData['elementType'])) {
525 $elementType = $propertyMetaData['elementType'];
526 } else {
527 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('Could not determine the type of the contained objects.', 1251315966);
528 }
529 return $elementType;
530 }
531
532 }
533 ?>