aef09941f9660ecf2b8cc0f6e24d0b6ce82159a5
[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_Mapper_DataMapFactory
70 */
71 protected $dataMapFactory;
72
73 /**
74 * @var Tx_Extbase_Persistence_QueryFactoryInterface
75 */
76 protected $queryFactory;
77
78 /**
79 * The TYPO3 reference index object
80 *
81 * @var t3lib_refindex
82 **/
83 protected $referenceIndex;
84
85 /**
86 * Constructs a new mapper
87 *
88 */
89 public function __construct() {
90 $this->queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
91 }
92
93 /**
94 * Injects the identity map
95 *
96 * @param Tx_Extbase_Persistence_IdentityMap $identityMap
97 * @return void
98 */
99 public function injectIdentityMap(Tx_Extbase_Persistence_IdentityMap $identityMap) {
100 $this->identityMap = $identityMap;
101 }
102
103 /**
104 * Injects the persistence session
105 *
106 * @param Tx_Extbase_Persistence_Session $persistenceSession
107 * @return void
108 */
109 public function injectSession(Tx_Extbase_Persistence_Session $persistenceSession) {
110 $this->persistenceSession = $persistenceSession;
111 }
112
113 /**
114 * Injects the Reflection Service
115 *
116 * @param Tx_Extbase_Reflection_Service
117 * @return void
118 */
119 public function injectReflectionService(Tx_Extbase_Reflection_Service $reflectionService) {
120 $this->reflectionService = $reflectionService;
121 }
122
123 /**
124 * Injects the DataMap Factory
125 *
126 * @param Tx_Extbase_Persistence_Mapper_DataMapFactory
127 * @return void
128 */
129 public function injectDataMapFactory(Tx_Extbase_Persistence_Mapper_DataMapFactory $dataMapFactory) {
130 $this->dataMapFactory = $dataMapFactory;
131 }
132
133 /**
134 * Sets the query object model factory
135 *
136 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelFactory $qomFactory
137 * @return void
138 */
139 public function setQomFactory(Tx_Extbase_Persistence_QOM_QueryObjectModelFactory $qomFactory) {
140 $this->qomFactory = $qomFactory;
141 }
142
143 /**
144 * Maps the given rows on objects
145 *
146 * @param string $className The name of the class
147 * @param array $rows An array of arrays with field_name => value pairs
148 * @return array An array of objects of the given class
149 */
150 public function map($className, array $rows) {
151 $objects = array();
152 foreach ($rows as $row) {
153 $objects[] = $this->mapSingleRow($this->getTargetType($className, $row), $row);
154 }
155 return $objects;
156 }
157
158 /**
159 * Returns the target type for the given row.
160 *
161 * @param string $className The name of the class
162 * @param array $row A single array with field_name => value pairs
163 * @return string The target type (a class name)
164 */
165 public function getTargetType($className, array $row) {
166 $dataMap = $this->getDataMap($className);
167 $targetType = $className;
168 if ($dataMap->getRecordTypeColumnName() !== NULL) {
169 foreach ($dataMap->getSubclasses() as $subclassName) {
170 $recordSubtype = $this->getDataMap($subclassName)->getRecordType();
171 if ($row[$dataMap->getRecordTypeColumnName()] === $recordSubtype) {
172 $targetType = $subclassName;
173 break;
174 }
175 }
176 }
177 return $targetType;
178 }
179
180 /**
181 * Maps a single row on an object of the given class
182 *
183 * @param string $className The name of the target class
184 * @param array $row A single array with field_name => value pairs
185 * @return object An object of the given class
186 */
187 protected function mapSingleRow($className, array $row) {
188 if ($this->identityMap->hasIdentifier($row['uid'], $className)) {
189 $object = $this->identityMap->getObjectByIdentifier($row['uid'], $className);
190 } else {
191 $object = $this->createEmptyObject($className);
192 $this->identityMap->registerObject($object, $row['uid']);
193 $this->thawProperties($object, $row);
194 $object->_memorizeCleanState();
195 $this->persistenceSession->registerReconstitutedObject($object);
196 }
197 return $object;
198 }
199
200 /**
201 * Creates a skeleton of the specified object
202 *
203 * @param string $className Name of the class to create a skeleton for
204 * @return object The object skeleton
205 */
206 protected function createEmptyObject($className) {
207 // Note: The class_implements() function also invokes autoload to assure that the interfaces
208 // and the class are loaded. Would end up with __PHP_Incomplete_Class without it.
209 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);
210 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
211 return $object;
212 }
213
214 /**
215 * Sets the given properties on the object.
216 *
217 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to set properties on
218 * @param Tx_Extbase_Persistence_RowInterface $row
219 * @return void
220 */
221 protected function thawProperties(Tx_Extbase_DomainObject_DomainObjectInterface $object, array $row) {
222 $className = get_class($object);
223 $dataMap = $this->getDataMap($className);
224 $object->_setProperty('uid', intval($row['uid']));
225 $object->_setProperty('_localizedUid', intval($row['uid']));
226 if ($dataMap->getLanguageIdColumnName() !== NULL) {
227 $object->_setProperty('_languageUid', intval($row[$dataMap->getLanguageIdColumnName()]));
228 if (isset($row['_LOCALIZED_UID'])) {
229 $object->_setProperty('_localizedUid', intval($row['_LOCALIZED_UID']));
230 }
231 }
232 $properties = $object->_getProperties();
233 foreach ($properties as $propertyName => $propertyValue) {
234 if (!$dataMap->isPersistableProperty($propertyName)) continue;
235 $columnMap = $dataMap->getColumnMap($propertyName);
236 $columnName = $columnMap->getColumnName();
237 $propertyData = $this->reflectionService->getClassSchema($className)->getProperty($propertyName);
238 $propertyValue = NULL;
239 if ($row[$columnName] !== NULL) {
240 switch ($propertyData['type']) {
241 case 'integer':
242 $propertyValue = (int) $row[$columnName];
243 break;
244 case 'float':
245 $propertyValue = (float) $row[$columnName];
246 break;
247 case 'boolean':
248 $propertyValue = (boolean) $row[$columnName];
249 break;
250 case 'string':
251 $propertyValue = (string) $row[$columnName];
252 break;
253 case 'array':
254 // $propertyValue = $this->mapArray($row[$columnName]); // Not supported, yet!
255 break;
256 case 'SplObjectStorage':
257 case 'Tx_Extbase_Persistence_ObjectStorage':
258 $propertyValue = $this->mapResultToPropertyValue($object, $propertyName, $this->fetchRelated($object, $propertyName, $row[$columnName]));
259 $propertyValue->_memorizeCleanState();
260 break;
261 default:
262 if (($propertyData['type'] === 'DateTime') || in_array('DateTime', class_parents($propertyData['type']))) {
263 $propertyValue = $this->mapDateTime($row[$columnName]);
264 } else {
265 $propertyValue = $this->mapResultToPropertyValue($object, $propertyName, $this->fetchRelated($object, $propertyName, $row[$columnName]));
266 // $propertyValue = $this->mapToObject($row[$columnName]); // Not supported, yet!
267 }
268 break;
269 }
270 }
271
272 if ($propertyValue !== NULL) {
273 $object->_setProperty($propertyName, $propertyValue);
274 }
275 }
276 }
277
278 /**
279 * Creates a DateTime from an unix timestamp. If the input is empty
280 * NULL is returned.
281 *
282 * @param integer $timestamp
283 * @return DateTime
284 */
285 protected function mapDateTime($timestamp) {
286 if (empty($timestamp)) { // 0 -> NULL !!!
287 return NULL;
288 } else {
289 return new DateTime(date('c', $timestamp));
290 }
291 }
292
293 /**
294 * Fetches a collection of objects related to a property of a parent object
295 *
296 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
297 * @param string $propertyName The name of the proxied property in it's parent
298 * @param mixed $fieldValue The raw field value.
299 * @param bool $enableLazyLoading A flag indication if the related objects should be lazy loaded
300 * @param bool $performLanguageOverlay A flag indication if the related objects should be localized
301 * @return mixed The result
302 */
303 public function fetchRelated(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '', $enableLazyLoading = TRUE) {
304 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
305 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
306 if ($enableLazyLoading === TRUE && $propertyMetaData['lazy']) {
307 if ($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') {
308 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyObjectStorage', $parentObject, $propertyName, $fieldValue);
309 } else {
310 if (empty($fieldValue)) {
311 $result = NULL;
312 } else {
313 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyLoadingProxy', $parentObject, $propertyName, $fieldValue);
314 }
315 }
316 } else {
317 $result = $this->fetchRelatedEager($parentObject, $propertyName, $fieldValue);
318 }
319 return $result;
320 }
321
322 /**
323 * Fetches the related objects from the storage backend.
324 *
325 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
326 * @param string $propertyName The name of the proxied property in it's parent
327 * @param mixed $fieldValue The raw field value.
328 * @param bool $performLanguageOverlay A flag indication if the related objects should be localized
329 * @return void
330 */
331 protected function fetchRelatedEager(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '') {
332 if ($fieldValue === '') return array();
333 $query = $this->getPreparedQuery($parentObject, $propertyName, $fieldValue);
334 return $query->execute();
335 }
336
337 /**
338 * Builds and returns the prepared query, ready to be executed.
339 *
340 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject
341 * @param string $propertyName
342 * @param string $fieldValue
343 * @return void
344 */
345 protected function getPreparedQuery(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '') {
346 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
347 $queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
348 $type = $this->getType(get_class($parentObject), $propertyName);
349 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
350 $query = $queryFactory->create($type);
351 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
352 $query = $queryFactory->create($type);
353 $query->getQuerySettings()->setRespectStoragePage(FALSE);
354 if ($columnMap->getChildSortByFieldName() !== NULL) {
355 $query->setOrderings(array($columnMap->getChildSortByFieldName() => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
356 }
357 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
358 $query = $queryFactory->create($type);
359 $query->getQuerySettings()->setRespectStoragePage(FALSE);
360 $query->setSource($this->getSource($parentObject, $propertyName));
361 if ($columnMap->getChildSortByFieldName() !== NULL) {
362 $query->setOrderings(array($columnMap->getChildSortByFieldName() => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
363 }
364 } else {
365 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation for the property "' . $propertyName . '". This is mainly caused by a missing type declaration above the property definition. If the PHPDoc comment is there, make sure it starts with "/**" and not just with "/*".', 1252502725);
366 }
367 $query->matching($this->getConstraint($query, $parentObject, $propertyName, $fieldValue, $columnMap->getRelationTableMatchFields()));
368 return $query;
369 }
370
371 /**
372 * Builds and returns the constraint for multi value properties.
373 *
374 * @param Tx_Extbase_Persistence_QueryInterface $query
375 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject
376 * @param string $propertyName
377 * @param string $fieldValue
378 * @param array $relationTableMatchFields
379 * @return Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint
380 */
381 protected function getConstraint(Tx_Extbase_Persistence_QueryInterface $query, Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '', $relationTableMatchFields = array()) {
382 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
383 if ($columnMap->getParentKeyFieldName() !== NULL) {
384 $constraint = $query->equals($columnMap->getParentKeyFieldName(), $parentObject);
385 if($columnMap->getParentTableFieldName() !== NULL) {
386 $constraint = $query->logicalAnd(
387 $constraint,
388 $query->equals($columnMap->getParentTableFieldName(), $this->getDataMap(get_class($parentObject))->getTableName())
389 );
390 }
391 } else {
392 $constraint = $query->in('uid', t3lib_div::intExplode(',', $fieldValue));
393 }
394 if (count($relationTableMatchFields) > 0) {
395 foreach($relationTableMatchFields as $relationTableMatchFieldName => $relationTableMatchFieldValue) {
396 $constraint = $query->logicalAnd($constraint, $query->equals($relationTableMatchFieldName, $relationTableMatchFieldValue));
397 }
398 }
399 return $constraint;
400 }
401
402 /**
403 * Builds and returns the source to build a join for a m:n relation.
404 *
405 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject
406 * @param string $propertyName
407 * @return Tx_Extbase_Persistence_QOM_SourceInterface $source
408 */
409 protected function getSource(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName) {
410 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
411 $left = $this->qomFactory->selector(NULL, $columnMap->getRelationTableName());
412 $childClassName = $this->getType(get_class($parentObject), $propertyName);
413 $right = $this->qomFactory->selector($childClassName, $columnMap->getChildTableName());
414 $joinCondition = $this->qomFactory->equiJoinCondition($columnMap->getRelationTableName(), $columnMap->getChildKeyFieldName(), $columnMap->getChildTableName(), 'uid');
415 $source = $this->qomFactory->join(
416 $left,
417 $right,
418 Tx_Extbase_Persistence_QueryInterface::JCR_JOIN_TYPE_INNER,
419 $joinCondition
420 );
421 return $source;
422 }
423
424 /**
425 * Returns the given result as property value of the specified property type.
426 *
427 * @param mixed $result The result could be an object or an ObjectStorage
428 * @param array $propertyMetaData The property meta data
429 * @param array $result The result
430 * @return void
431 */
432 public function mapResultToPropertyValue(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $result) {
433 if ($result instanceof Tx_Extbase_Persistence_LoadingStrategyInterface) {
434 $propertyValue = $result;
435 } else {
436 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
437 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
438 if (in_array($propertyMetaData['type'], array('array', 'ArrayObject', 'SplObjectStorage', 'Tx_Extbase_Persistence_ObjectStorage'))) {
439 $elementType = $this->getType(get_class($parentObject), $propertyName);
440 $objects = array();
441 foreach ($result as $value) {
442 $objects[] = $value;
443 }
444
445 if ($propertyMetaData['type'] === 'ArrayObject') {
446 $propertyValue = new ArrayObject($objects);
447 } elseif ($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') {
448 $propertyValue = new Tx_Extbase_Persistence_ObjectStorage();
449 foreach ($objects as $object) {
450 $propertyValue->attach($object);
451 }
452 } else {
453 $propertyValue = $objects;
454 }
455 } elseif (strpos($propertyMetaData['type'], '_') !== FALSE) {
456 if (is_array($result)) {
457 $propertyValue = current($result);
458 } else {
459 $propertyValue = $result;
460 }
461 }
462 }
463 return $propertyValue;
464 }
465
466 /**
467 * Counts the number of related objects assigned to a property of a parent object
468 *
469 * @param Tx_Extbase_DomainObject_DomainObjectInterface $parentObject The object instance this proxy is part of
470 * @param string $propertyName The name of the proxied property in it's parent
471 * @param mixed $fieldValue The raw field value.
472 */
473 public function countRelated(Tx_Extbase_DomainObject_DomainObjectInterface $parentObject, $propertyName, $fieldValue = '') {
474 $query = $this->getPreparedQuery($parentObject, $propertyName, $fieldValue);
475 return $query->count();
476 }
477
478 /**
479 * Delegates the call to the Data Map.
480 * Returns TRUE if the property is persistable (configured in $TCA)
481 *
482 * @param string $className The property name
483 * @param string $propertyName The property name
484 * @return boolean TRUE if the property is persistable (configured in $TCA)
485 */
486 public function isPersistableProperty($className, $propertyName) {
487 $dataMap = $this->getDataMap($className);
488 return $dataMap->isPersistableProperty($propertyName);
489 }
490
491 /**
492 * Returns a data map for a given class name
493 *
494 * @param string $className The class name you want to fetch the Data Map for
495 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
496 */
497 public function getDataMap($className) {
498 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);
499 if (!isset($this->dataMaps[$className])) {
500 $this->dataMaps[$className] = $this->dataMapFactory->buildDataMap($className);
501 }
502 return $this->dataMaps[$className];
503 }
504
505 /**
506 * Returns the selector (table) name for a given class name.
507 *
508 * @param string $className
509 * @return string The selector name
510 */
511 public function convertClassNameToTableName($className = NULL) {
512 if ($className !== NULL) {
513 $tableName = $this->getDataMap($className)->getTableName();
514 } else {
515 $tableName = strtolower($className);
516 }
517 return $tableName;
518 }
519
520 /**
521 * Returns the column name for a given property name of the specified class.
522 *
523 * @param string $className
524 * @param string $propertyName
525 * @return string The column name
526 */
527 public function convertPropertyNameToColumnName($propertyName, $className = NULL) {
528 if (!empty($className)) {
529 $dataMap = $this->getDataMap($className);
530 if ($dataMap !== NULL) {
531 $columnMap = $dataMap->getColumnMap($propertyName);
532 if ($columnMap !== NULL) {
533 return $columnMap->getColumnName();
534 }
535 }
536 }
537 return Tx_Extbase_Utility_Extension::convertCamelCaseToLowerCaseUnderscored($propertyName);
538 }
539
540 /**
541 * Returns the type of a child object.
542 *
543 * @param string $parentClassName The class name of the object this proxy is part of
544 * @param string $propertyName The name of the proxied property in it's parent
545 * @return string The class name of the child object
546 */
547 public function getType($parentClassName, $propertyName) {
548 $propertyMetaData = $this->reflectionService->getClassSchema($parentClassName)->getProperty($propertyName);
549 if (!empty($propertyMetaData['elementType'])) {
550 $type = $propertyMetaData['elementType'];
551 } elseif (!empty($propertyMetaData['type'])) {
552 $type = $propertyMetaData['type'];
553 } else {
554 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('Could not determine the child object type.', 1251315967);
555 }
556 return $type;
557 }
558
559 }
560 ?>