[+FEATURE] Extbase (Persistence): Implemented (still experimental) feature to be...
[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 given rows on objects of the given class
130 *
131 * @param string $className The name of the target class
132 * @param array $rows An array of arrays with field_name => value pairs
133 * @return array An array of objects of the given class
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 row on an object of the given class
145 *
146 * @param string $className The name of the target class
147 * @param array $row A single array with field_name => value pairs
148 * @return object An object of the given class
149 */
150 protected function mapSingleRow($className, array $row) {
151 if ($this->identityMap->hasIdentifier($row['uid'], $className)) {
152 $object = $this->identityMap->getObjectByIdentifier($row['uid'], $className);
153 } else {
154 $object = $this->createEmptyObject($className);
155 $this->identityMap->registerObject($object, $row['uid']);
156 $this->thawProperties($object, $row);
157 $object->_memorizeCleanState();
158 $this->persistenceSession->registerReconstitutedObject($object);
159 }
160 return $object;
161 }
162
163 /**
164 * Creates a skeleton of the specified object
165 *
166 * @param string $className Name of the class to create a skeleton for
167 * @return object The object skeleton
168 */
169 protected function createEmptyObject($className) {
170 // Note: The class_implements() function also invokes autoload to assure that the interfaces
171 // and the class are loaded. Would end up with __PHP_Incomplete_Class without it.
172 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);
173 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
174 return $object;
175 }
176
177 /**
178 * Sets the given properties on the object.
179 *
180 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to set properties on
181 * @param Tx_Extbase_Persistence_RowInterface $row
182 * @return void
183 */
184 protected function thawProperties(Tx_Extbase_DomainObject_DomainObjectInterface $object, array $row) {
185 $className = get_class($object);
186 $dataMap = $this->getDataMap($className);
187 $properties = $object->_getProperties();
188 $localizedUid = $row['_LOCALIZED_UID'];
189 if ($localizedUid !== NULL) {
190 $object->_setProperty('uid', $localizedUid);
191 $object->_setProperty('_localizationParentUid', $row['uid']);
192 } else {
193 $object->_setProperty('uid', $row['uid']);
194 }
195 unset($properties['uid']);
196 foreach ($properties as $propertyName => $propertyValue) {
197 if (!$dataMap->isPersistableProperty($propertyName)) continue;
198 $columnMap = $dataMap->getColumnMap($propertyName);
199 $columnName = $columnMap->getColumnName();
200 $propertyValue = NULL;
201
202 $propertyMetaData = $this->reflectionService->getClassSchema($className)->getProperty($propertyName);
203 $propertyType = Tx_Extbase_Persistence_PropertyType::valueFromType($propertyMetaData['type']);
204
205 if ($propertyType == Tx_Extbase_Persistence_PropertyType::UNDEFINED) {
206 $propertyType = $columnMap->getPropertyType();
207 }
208
209 switch ($propertyType) {
210 case Tx_Extbase_Persistence_PropertyType::STRING;
211 case Tx_Extbase_Persistence_PropertyType::DATE;
212 case Tx_Extbase_Persistence_PropertyType::LONG;
213 case Tx_Extbase_Persistence_PropertyType::DOUBLE;
214 case Tx_Extbase_Persistence_PropertyType::BOOLEAN;
215 if (isset($row[$columnName])) {
216 $rawPropertyValue = $row[$columnName];
217 $propertyValue = $dataMap->convertFieldValueToPropertyValue($propertyType, $rawPropertyValue);
218 }
219 break;
220 case (Tx_Extbase_Persistence_PropertyType::REFERENCE):
221 $propertyValue = $row[$columnName];
222 if (!is_null($propertyValue)) {
223 $fieldValue = $row[$columnName];
224 $result = $this->fetchRelated($object, $propertyName, $fieldValue);
225 $propertyValue = $this->mapResultToPropertyValue($object, $propertyName, $result);
226 }
227 break;
228 default:
229 // FIXME throw exception
230 break;
231 }
232 $object->_setProperty($propertyName, $propertyValue);
233 }
234 }
235
236 /**
237 * Fetches a collection of objects related to a property of a parent object
238 *
239 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
240 * @param string $propertyName The name of the proxied property in it's parent
241 * @param mixed $fieldValue The raw field value.
242 * @param bool $enableLazyLoading A flag indication if the related objects should be lazy loaded
243 * @param bool $performLanguageOverlay A flag indication if the related objects should be localized
244 * @return mixed The result
245 */
246 public function fetchRelated(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '', $enableLazyLoading = TRUE, $performLanguageOverlay = TRUE) {
247 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
248 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
249 if ($enableLazyLoading === TRUE && ($propertyMetaData['lazy'] || ($columnMap->getLoadingStrategy() !== Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_EAGER))) {
250 if (($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') || ($columnMap->getLoadingStrategy() === Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_LAZY_STORAGE)) {
251 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyObjectStorage', $parentObject, $propertyName, $fieldValue);
252 } else {
253 if (empty($fieldValue)) {
254 $result = NULL;
255 } else {
256 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyLoadingProxy', $parentObject, $propertyName, $fieldValue);
257 }
258 }
259 } else {
260 $result = $this->fetchRelatedEager($parentObject, $propertyName, $fieldValue, $performLanguageOverlay);
261 }
262 return $result;
263 }
264
265 /**
266 * Fetches the related objects from the storage backend.
267 *
268 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
269 * @param string $propertyName The name of the proxied property in it's parent
270 * @param mixed $fieldValue The raw field value.
271 * @param bool $performLanguageOverlay A flag indication if the related objects should be localized
272 * @return void
273 */
274 protected function fetchRelatedEager(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '', $performLanguageOverlay = TRUE) {
275 if ($fieldValue === '') return array();
276 $query = $this->getPreparedQuery($parentObject, $propertyName, $fieldValue);
277 $query->getQuerySettings()->setRespectSysLanguage($performLanguageOverlay);
278 return $query->execute();
279 }
280
281 /**
282 * Builds and returns the prepared query, ready to be executed.
283 *
284 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject
285 * @param string $propertyName
286 * @param string $fieldValue
287 * @return void
288 */
289 protected function getPreparedQuery(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '') {
290 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
291 $queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
292 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
293 $childSortByFieldName = $columnMap->getChildSortByFieldName();
294 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
295 $query = $queryFactory->create($this->getType($parentObject, $propertyName));
296 if (isset($parentKeyFieldName)) {
297 $query->matching($query->equals($parentKeyFieldName, $parentObject->getUid()));
298 } else {
299 $query->matching($query->withUid(intval($fieldValue)));
300 }
301 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
302 $query = $queryFactory->create($this->getElementType(get_class($parentObject), $propertyName));
303 // 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
304 // enableFields and storage page settings.
305 $query->getQuerySettings()->setRespectStoragePage(FALSE);
306 if (!empty($childSortByFieldName)) {
307 $query->setOrderings(array($childSortByFieldName => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
308 }
309 if (isset($parentKeyFieldName)) {
310 $query->matching($query->equals($parentKeyFieldName, $parentObject->getUid()));
311 } else {
312 $query->matching($query->in('uid', t3lib_div::intExplode(',', $fieldValue)));
313 }
314 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
315 $query = $queryFactory->create($this->getElementType(get_class($parentObject), $propertyName));
316 // 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
317 // enableFields and storage page settings.
318 $query->getQuerySettings()->setRespectStoragePage(FALSE);
319 $relationTableName = $columnMap->getRelationTableName();
320 $left = $this->qomFactory->selector(NULL, $relationTableName);
321 $childClassName = $this->getElementType(get_class($parentObject), $propertyName);
322 $childTableName = $columnMap->getChildTableName();
323 $right = $this->qomFactory->selector($childClassName, $childTableName);
324 $joinCondition = $this->qomFactory->equiJoinCondition($relationTableName, $columnMap->getChildKeyFieldName(), $childTableName, 'uid');
325 $source = $this->qomFactory->join(
326 $left,
327 $right,
328 Tx_Extbase_Persistence_QueryInterface::JCR_JOIN_TYPE_INNER,
329 $joinCondition
330 );
331
332 $query->setSource($source);
333 if (!empty($childSortByFieldName)) {
334 $query->setOrderings(array($relationTableName . '.' . $childSortByFieldName => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
335 }
336
337 // attempt to support MM_match_fields
338 $conditions = $query->equals($parentKeyFieldName, $parentObject->getUid());
339
340 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
341 if (count($relationTableMatchFields)) {
342 foreach($relationTableMatchFields as $relationTableMatchFieldName => $relationTableMatchFieldValue) {
343 $relationMatchCondition = $query->equals($relationTableName . '.' . $relationTableMatchFieldName, $relationTableMatchFieldValue);
344 $conditions = $query->logicalAnd($conditions, $relationMatchCondition);
345 }
346 }
347 $query->matching($conditions);
348
349 } else {
350 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
351 }
352 return $query;
353 }
354
355 /**
356 * Returns the given result as property value of the specified property type.
357 *
358 * @param mixed $result The result could be an object or an ObjectStorage
359 * @param array $propertyMetaData The property meta data
360 * @return void
361 */
362 public function mapResultToPropertyValue(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $result) {
363 if ($result instanceof Tx_Extbase_Persistence_LoadingStrategyInterface) {
364 $propertyValue = $result;
365 } else {
366 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
367 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
368 if (in_array($propertyMetaData['type'], array('array', 'ArrayObject', 'Tx_Extbase_Persistence_ObjectStorage'))) {
369 $elementType = $this->getElementType(get_class($parentObject), $propertyName);
370 $objects = array();
371 foreach ($result as $value) {
372 $objects[] = $value;
373 }
374
375 if ($propertyMetaData['type'] === 'ArrayObject') {
376 $propertyValue = new ArrayObject($objects);
377 } elseif ($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') {
378 $propertyValue = new Tx_Extbase_Persistence_ObjectStorage();
379 foreach ($objects as $object) {
380 $propertyValue->attach($object);
381 }
382 } else {
383 $propertyValue = $objects;
384 }
385 } elseif (strpos($propertyMetaData['type'], '_') !== FALSE) {
386 $propertyValue = current($result);
387 }
388 }
389 return $propertyValue;
390 }
391
392 /**
393 * Counts the number of related objects assigned to a property of a parent object
394 *
395 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
396 * @param string $propertyName The name of the proxied property in it's parent
397 * @param mixed $fieldValue The raw field value.
398 */
399 public function countRelated(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '') {
400 $query = $this->getPreparedQuery($parentObject, $propertyName, $fieldValue);
401 return $query->count();
402 }
403
404 /**
405 * Delegates the call to the Data Map.
406 * Returns TRUE if the property is persistable (configured in $TCA)
407 *
408 * @param string $className The property name
409 * @param string $propertyName The property name
410 * @return boolean TRUE if the property is persistable (configured in $TCA)
411 */
412 public function isPersistableProperty($className, $propertyName) {
413 $dataMap = $this->getDataMap($className);
414 return $dataMap->isPersistableProperty($propertyName);
415 }
416
417 /**
418 * Returns a data map for a given class name
419 *
420 * @param string $className The class name you want to fetch the Data Map for
421 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
422 */
423 public function getDataMap($className) {
424 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);
425 if (!isset($this->dataMaps[$className])) {
426 // FIXME This is too expensive for table name aliases -> implement a DataMapBuilder (knowing the aliases defined in $TCA)
427 $columnMapping = array();
428 $tableName = '';
429 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
430 if (is_array($extbaseSettings['persistence']['classes'][$className])) {
431 $persistenceSettings = $extbaseSettings['persistence']['classes'][$className];
432 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
433 $tableName = $persistenceSettings['mapping']['tableName'];
434 }
435 if (is_array($persistenceSettings['mapping']['columns'])) {
436 $columnMapping = $persistenceSettings['mapping']['columns'];
437 }
438 } elseif (class_exists($className)) {
439 foreach (class_parents($className) as $parentClassName) {
440 $persistenceSettings = $extbaseSettings['persistence']['classes'][$parentClassName];
441 if (is_array($persistenceSettings)) {
442 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
443 $tableName = $persistenceSettings['mapping']['tableName'];
444 }
445 if (is_array($persistenceSettings['mapping']['columns'])) {
446 $columnMapping = $persistenceSettings['mapping']['columns'];
447 }
448 }
449 break;
450 }
451 } else {
452 throw new Tx_Extbase_Persistence_Exception('Could not determine a Data Map for given class name.', 1256067130);
453 }
454
455 $dataMap = new Tx_Extbase_Persistence_Mapper_DataMap($className, $tableName, $columnMapping);
456 $this->dataMaps[$className] = $dataMap;
457 }
458 return $this->dataMaps[$className];
459 }
460
461 /**
462 * Returns the selector (table) name for a given class name.
463 *
464 * @param string $className
465 * @return string The selector name
466 */
467 public function convertClassNameToTableName($className = NULL) {
468 if (!empty($className)) {
469 return $this->getDataMap($className)->getTableName();
470 }
471 return strtolower($className);
472 }
473
474 /**
475 * Returns the column name for a given property name of the specified class.
476 *
477 * @param string $className
478 * @param string $propertyName
479 * @return string The column name
480 */
481 public function convertPropertyNameToColumnName($propertyName, $className = NULL) {
482 if (!empty($className)) {
483 $dataMap = $this->getDataMap($className);
484 if ($dataMap !== NULL) {
485 $columnMap = $dataMap->getColumnMap($propertyName);
486 if ($columnMap !== NULL) {
487 return $columnMap->getColumnName();
488 }
489 }
490 }
491 return Tx_Extbase_Utility_Extension::convertCamelCaseToLowerCaseUnderscored($propertyName);
492 }
493
494 /**
495 * Returns the type of a child object.
496 *
497 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
498 * @param string $propertyName The name of the proxied property in it's parent
499 * @return string The class name of the child object
500 */
501 protected function getType(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName) {
502 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
503 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
504 $childClassName = $columnMap->getChildClassName();
505 if (!empty($childClassName)) {
506 $elementType = $childClassName;
507 } elseif (!empty($propertyMetaData['type'])) {
508 $elementType = $propertyMetaData['type'];
509 } else {
510 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('Could not determine the child object object type.', 1251315967);
511 }
512 return $elementType;
513 }
514
515 /**
516 * Returns the type of the elements inside an ObjectStorage or array.
517 *
518 * @param string $parentClassName The class name of the object this proxy is part of
519 * @param string $propertyName The name of the proxied property in it's parent
520 * @return string The class name of the elements inside an ObjectStorage
521 */
522 public function getElementType($parentClassName, $propertyName) {
523 $propertyMetaData = $this->reflectionService->getClassSchema($parentClassName)->getProperty($propertyName);
524 $columnMap = $this->getDataMap($parentClassName)->getColumnMap($propertyName);
525 $childClassName = $columnMap->getChildClassName();
526 if (!empty($childClassName)) {
527 $elementType = $childClassName;
528 } elseif (!empty($propertyMetaData['elementType'])) {
529 $elementType = $propertyMetaData['elementType'];
530 } else {
531 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('Could not determine the type of the contained objects.', 1251315966);
532 }
533 return $elementType;
534 }
535
536 }
537 ?>