[+BUGFIX] Extbase (Persistence): DataMapper::thawProperties() called getValue() twice...
[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, Tx_Extbase_Persistence_RowIteratorInterface $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, Tx_Extbase_Persistence_RowInterface $row) {
150 if ($this->identityMap->hasIdentifier($row->getValue('uid'), $className)) {
151 $object = $this->identityMap->getObjectByIdentifier($row->getValue('uid'), $className);
152 } else {
153 $object = $this->createEmptyObject($className);
154 $this->thawProperties($object, $row);
155 $this->identityMap->registerObject($object, $object->getUid());
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, Tx_Extbase_Persistence_RowInterface $row) {
184 $className = get_class($object);
185 $dataMap = $this->getDataMap($className);
186 $properties = $object->_getProperties();
187 $object->_setProperty('uid', $row->getValue('uid'));
188 foreach ($properties as $propertyName => $propertyValue) {
189 if (!$dataMap->isPersistableProperty($propertyName)) continue;
190 $columnMap = $dataMap->getColumnMap($propertyName);
191 $columnName = $columnMap->getColumnName();
192 $propertyValue = NULL;
193 $propertyType = $columnMap->getPropertyType();
194 switch ($propertyType) {
195 case Tx_Extbase_Persistence_PropertyType::STRING;
196 case Tx_Extbase_Persistence_PropertyType::DATE;
197 case Tx_Extbase_Persistence_PropertyType::LONG;
198 case Tx_Extbase_Persistence_PropertyType::DOUBLE;
199 case Tx_Extbase_Persistence_PropertyType::BOOLEAN;
200 if ($row->hasValue($columnName)) {
201 $rawPropertyValue = $row->getValue($columnName);
202 $propertyValue = $dataMap->convertFieldValueToPropertyValue($propertyType, $rawPropertyValue);
203 }
204 break;
205 case (Tx_Extbase_Persistence_PropertyType::REFERENCE):
206 $propertyValue = $row->getValue($columnName);
207 if (!is_null($propertyValue)) {
208 $fieldValue = $row->getValue($columnName);
209 $result = $this->fetchRelated($object, $propertyName, $fieldValue);
210 $propertyValue = $this->mapResultToPropertyValue($object, $propertyName, $result);
211 }
212 break;
213 default:
214 // FIXME throw exception
215 break;
216 }
217 $object->_setProperty($propertyName, $propertyValue);
218 }
219 }
220
221 /**
222 * Fetches a collection of objects related to a property of a parent object
223 *
224 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject The object instance this proxy is part of
225 * @param string $propertyName The name of the proxied property in it's parent
226 * @param mixed $fieldValue The raw field value.
227 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The corresponding Data Map of the property
228 * @return mixed The result
229 */
230 public function fetchRelated(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, $fieldValue = '', $enableLazyLoading = TRUE) {
231 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
232 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
233 if ($enableLazyLoading === TRUE && ($propertyMetaData['lazy'] || ($columnMap->getLoadingStrategy() !== Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_EAGER))) {
234 if (($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') || ($columnMap->getLoadingStrategy() === Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_LAZY_STORAGE)) {
235 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyObjectStorage', $parentObject, $propertyName, $fieldValue);
236 } else {
237 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyLoadingProxy', $parentObject, $propertyName, $fieldValue);
238 }
239 } else {
240 $result = $this->fetchRelatedEager($parentObject, $propertyName, $fieldValue);
241 }
242 return $result;
243 }
244
245 /**
246 * Fetches the related objects from the storage backend.
247 *
248 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject The object instance this proxy is part of
249 * @param string $propertyName The name of the proxied property in it's parent
250 * @param mixed $fieldValue The raw field value.
251 * @return void
252 */
253 protected function fetchRelatedEager(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, $fieldValue = '') {
254 if ($fieldValue === '') return array();
255 $query = $this->getPreparedQuery($parentObject, $propertyName, $fieldValue);
256 return $query->execute();
257 }
258
259 /**
260 * Builds and returns the prepared query, ready to be executed.
261 *
262 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject
263 * @param string $propertyName
264 * @param string $fieldValue
265 * @return void
266 */
267 protected function getPreparedQuery(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, $fieldValue = '') {
268 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
269 $queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
270 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
271 $childSortByFieldName = $columnMap->getChildSortByFieldName();
272 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
273 $query = $queryFactory->create($this->getType($parentObject, $propertyName));
274 $query->matching($query->withUid(intval($fieldValue)));
275 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
276 $query = $queryFactory->create($this->getElementType($parentObject, $propertyName));
277 // 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
278 // enableFields and storage page settings.
279 $query->getQuerySettings()->setRespectStoragePage(FALSE);
280 if (!empty($childSortByFieldName)) {
281 $query->setOrderings(array($childSortByFieldName => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
282 }
283 if (isset($parentKeyFieldName)) {
284 $query->matching($query->equals($parentKeyFieldName, $parentObject->getUid()));
285 } else {
286 $query->matching($query->equals('uid', t3lib_div::intExplode(',', $fieldValue)));
287 }
288 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
289 $query = $queryFactory->create($this->getElementType($parentObject, $propertyName));
290 // 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
291 // enableFields and storage page settings.
292 $query->getQuerySettings()->setRespectStoragePage(FALSE);
293 $relationTableName = $columnMap->getRelationTableName();
294 $left = $this->qomFactory->selector(NULL, $relationTableName);
295 $childClassName = $this->getElementType($parentObject, $propertyName);
296 $childTableName = $columnMap->getChildTableName();
297 $right = $this->qomFactory->selector($childClassName, $childTableName);
298 $joinCondition = $this->qomFactory->equiJoinCondition($relationTableName, $columnMap->getChildKeyFieldName(), $childTableName, 'uid');
299 $source = $this->qomFactory->join(
300 $left,
301 $right,
302 Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER,
303 $joinCondition
304 );
305 $query->setSource($source);
306 if (!empty($childSortByFieldName)) {
307 $query->setOrderings(array($relationTableName . '.' . $childSortByFieldName => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
308 }
309 $query->matching($query->equals($parentKeyFieldName, $parentObject->getUid()));
310 } else {
311 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
312 }
313 return $query;
314 }
315
316 /**
317 * Returns the given result as property value of the specified property type.
318 *
319 * @param mixed $result The result could be an object or an ObjectStorage
320 * @param array $propertyMetaData The property meta data
321 * @return void
322 */
323 public function mapResultToPropertyValue(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, $result) {
324 if ($result instanceof Tx_Extbase_Persistence_LoadingStrategyInterface) {
325 $propertyValue = $result;
326 } else {
327 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
328 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
329 if (in_array($propertyMetaData['type'], array('array', 'ArrayObject', 'Tx_Extbase_Persistence_ObjectStorage'))) {
330 $elementType = $this->getElementType($parentObject, $propertyName);
331 $objects = array();
332 foreach ($result as $value) {
333 $objects[] = $value;
334 }
335
336 if ($propertyMetaData['type'] === 'ArrayObject') {
337 $propertyValue = new ArrayObject($objects);
338 } elseif ($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') {
339 $propertyValue = new Tx_Extbase_Persistence_ObjectStorage();
340 foreach ($objects as $object) {
341 $propertyValue->attach($object);
342 }
343 } else {
344 $propertyValue = $objects;
345 }
346 } elseif (strpos($propertyMetaData['type'], '_') !== FALSE) {
347 $propertyValue = current($result);
348 }
349 }
350 return $propertyValue;
351 }
352
353 /**
354 * Counts the number of related objects assigned to a property of a parent object
355 *
356 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject The object instance this proxy is part of
357 * @param string $propertyName The name of the proxied property in it's parent
358 * @param mixed $fieldValue The raw field value.
359 */
360 public function countRelated(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, $fieldValue = '') {
361 $query = $this->getPreparedQuery($parentObject, $propertyName, $fieldValue);
362 return $query->count();
363 }
364
365 /**
366 * Delegates the call to the Data Map.
367 * Returns TRUE if the property is persistable (configured in $TCA)
368 *
369 * @param string $className The property name
370 * @param string $propertyName The property name
371 * @return boolean TRUE if the property is persistable (configured in $TCA)
372 */
373 public function isPersistableProperty($className, $propertyName) {
374 $dataMap = $this->getDataMap($className);
375 return $dataMap->isPersistableProperty($propertyName);
376 }
377
378 /**
379 * Returns a data map for a given class name
380 *
381 * @param string $className The class name you want to fetch the Data Map for
382 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
383 */
384 public function getDataMap($className) {
385 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);
386 if (!isset($this->dataMaps[$className])) {
387 // FIXME This is too expensive for table name aliases -> implement a DataMapBuilder (knowing the aliases defined in $TCA)
388 $columnMapping = array();
389 $tableName = '';
390 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
391 if (is_array($extbaseSettings['persistence']['classes'][$className])) {
392 $persistenceSettings = $extbaseSettings['persistence']['classes'][$className];
393 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
394 $tableName = $persistenceSettings['mapping']['tableName'];
395 }
396 if (is_array($persistenceSettings['mapping']['columns'])) {
397 $columnMapping = $persistenceSettings['mapping']['columns'];
398 }
399 } elseif (class_exists($className)) {
400 foreach (class_parents($className) as $parentClassName) {
401 $persistenceSettings = $extbaseSettings['persistence']['classes'][$parentClassName];
402 if (is_array($persistenceSettings)) {
403 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
404 $tableName = $persistenceSettings['mapping']['tableName'];
405 }
406 if (is_array($persistenceSettings['mapping']['columns'])) {
407 $columnMapping = $persistenceSettings['mapping']['columns'];
408 }
409 }
410 break;
411 }
412 } else {
413 throw new Tx_Extbase_Persistence_Exception('Could not determine a Data Map for given class name.', 1256067130);
414 }
415
416 $dataMap = new Tx_Extbase_Persistence_Mapper_DataMap($className, $tableName, $columnMapping);
417 $this->dataMaps[$className] = $dataMap;
418 }
419 return $this->dataMaps[$className];
420 }
421
422 /**
423 * Returns the selector (table) name for a given class name.
424 *
425 * @param string $className
426 * @return string The selector name
427 */
428 public function convertClassNameToTableName($className) {
429 return $this->getDataMap($className)->getTableName();
430 }
431
432 /**
433 * Returns the column name for a given property name of the specified class.
434 *
435 * @param string $className
436 * @param string $propertyName
437 * @return string The column name
438 */
439 public function convertPropertyNameToColumnName($propertyName, $className = '') {
440 if (!empty($className)) {
441 $dataMap = $this->getDataMap($className);
442 if ($dataMap !== NULL) {
443 $columnMap = $dataMap->getColumnMap($propertyName);
444 if ($columnMap !== NULL) {
445 return $columnMap->getColumnName();
446 }
447 }
448 }
449 return Tx_Extbase_Utility_Extension::convertCamelCaseToLowerCaseUnderscored($propertyName);
450 }
451
452 /**
453 * Returns the type of a child object.
454 *
455 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject The object instance this proxy is part of
456 * @param string $propertyName The name of the proxied property in it's parent
457 * @return string The class name of the child object
458 */
459 protected function getType(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName) {
460 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
461 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
462 $childClassName = $columnMap->getChildClassName();
463 if (!empty($childClassName)) {
464 $elementType = $childClassName;
465 } elseif (!empty($propertyMetaData['type'])) {
466 $elementType = $propertyMetaData['type'];
467 } else {
468 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('Could not determine the child object object type.', 1251315967);
469 }
470 return $elementType;
471 }
472
473 /**
474 * Returns the type of the elements inside an ObjectStorage or array.
475 *
476 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject The object instance this proxy is part of
477 * @param string $propertyName The name of the proxied property in it's parent
478 * @return string The class name of the elements inside an ObjectStorage
479 */
480 protected function getElementType(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName) {
481 $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName);
482 $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName);
483 $childClassName = $columnMap->getChildClassName();
484 if (!empty($childClassName)) {
485 $elementType = $childClassName;
486 } elseif (!empty($propertyMetaData['elementType'])) {
487 $elementType = $propertyMetaData['elementType'];
488 } else {
489 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('Could not determine the type of the contained objects.', 1251315966);
490 }
491 return $elementType;
492 }
493
494 }
495 ?>