[+BUGFIX] Extbase (Persistence): Now, the sorting of relations is evaluated as well...
[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 manager
100 *
101 * @param Tx_Extbase_Persistence_ManagerInterface $persistenceManager
102 * @return void
103 */
104 public function injectPersistenceManager(Tx_Extbase_Persistence_ManagerInterface $persistenceManager) {
105 $this->QOMFactory = $persistenceManager->getBackend()->getQOMFactory();
106 $this->persistenceSession = $persistenceManager->getSession();
107 }
108
109 /**
110 * Injects the Reflection Service
111 *
112 * @param Tx_Extbase_Reflection_Service
113 * @return void
114 */
115 public function injectReflectionService(Tx_Extbase_Reflection_Service $reflectionService) {
116 $this->reflectionService = $reflectionService;
117 }
118
119 /**
120 * Maps the (aggregate root) rows and registers them as reconstituted
121 * with the session.
122 *
123 * @param Tx_Extbase_Persistence_RowIteratorInterface $rows
124 * @return array
125 */
126 public function map($className, Tx_Extbase_Persistence_RowIteratorInterface $rows) {
127 $objects = array();
128 foreach ($rows as $row) {
129 $objects[] = $this->mapSingleRow($className, $row);
130 }
131 return $objects;
132 }
133
134 /**
135 * Maps a single node into the object it represents
136 *
137 * @param Tx_Extbase_Persistence_RowInterface $node
138 * @return object
139 */
140 protected function mapSingleRow($className, Tx_Extbase_Persistence_RowInterface $row) {
141 if ($this->identityMap->hasIdentifier($row['uid'], $className)) {
142 $object = $this->identityMap->getObjectByIdentifier($row['uid'], $className);
143 } else {
144 $object = $this->createEmptyObject($className);
145 $this->thawProperties($object, $row);
146 $this->identityMap->registerObject($object, $object->getUid());
147 $object->_memorizeCleanState();
148 $this->persistenceSession->registerReconstitutedObject($object);
149 }
150 return $object;
151 }
152
153 /**
154 * Creates a skeleton of the specified object
155 *
156 * @param string $className Name of the class to create a skeleton for
157 * @return object The object skeleton
158 */
159 protected function createEmptyObject($className) {
160 // Note: The class_implements() function also invokes autoload to assure that the interfaces
161 // and the class are loaded. Would end up with __PHP_Incomplete_Class without it.
162 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);
163 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
164 return $object;
165 }
166
167 /**
168 * Sets the given properties on the object.
169 *
170 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to set properties on
171 * @param Tx_Extbase_Persistence_RowInterface $row
172 * @return void
173 */
174 protected function thawProperties(Tx_Extbase_DomainObject_DomainObjectInterface $object, Tx_Extbase_Persistence_RowInterface $row) {
175 $className = get_class($object);
176 $dataMap = $this->getDataMap($className);
177 $properties = $object->_getProperties();
178 $object->_setProperty('uid', $row['uid']);
179 foreach ($properties as $propertyName => $propertyValue) {
180 if (!$dataMap->isPersistableProperty($propertyName)) continue;
181 $columnMap = $dataMap->getColumnMap($propertyName);
182 $columnName = $columnMap->getColumnName();
183 $propertyValue = NULL;
184 $propertyType = $columnMap->getPropertyType();
185 switch ($propertyType) {
186 case Tx_Extbase_Persistence_PropertyType::STRING;
187 case Tx_Extbase_Persistence_PropertyType::DATE;
188 case Tx_Extbase_Persistence_PropertyType::LONG;
189 case Tx_Extbase_Persistence_PropertyType::DOUBLE;
190 case Tx_Extbase_Persistence_PropertyType::BOOLEAN;
191 if (isset($row[$columnName])) {
192 $rawPropertyValue = $row[$columnName];
193 $propertyValue = $dataMap->convertFieldValueToPropertyValue($propertyType, $rawPropertyValue);
194 }
195 break;
196 case (Tx_Extbase_Persistence_PropertyType::REFERENCE):
197 if (!is_null($row[$columnName])) {
198 $propertyValue = $this->mapRelatedObjects($object, $propertyName, $row, $columnMap);
199 } else {
200 $propertyValue = NULL;
201 }
202 break;
203 // FIXME we have an object to handle... -> exception
204 default:
205 // SK: We should throw an exception as this point as there was an undefined propertyType we can not handle.
206 if (isset($row[$columnName])) {
207 $property = $row[$columnName];
208 if (is_object($property)) {
209 $propertyValue = $this->mapObject($property);
210 // SK: THIS case can not happen I think. At least $this->mapObject() is not available.
211 } else {
212 // SK: This case does not make sense either. $this-mapSingleRow has a different signature
213 $propertyValue = $this->mapSingleRow($className, $property);
214 }
215 }
216 break;
217 }
218
219 $object->_setProperty($propertyName, $propertyValue);
220 }
221 }
222
223 /**
224 * Maps related objects to an ObjectStorage
225 *
226 * @param object $parentObject The parent object for the mapping result
227 * @param string $propertyName The target property name for the mapping result
228 * @param Tx_Extbase_Persistence_RowInterface $row The actual database row
229 * @param int $loadingStrategy The loading strategy; one of Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_*
230 * @return array|Tx_Extbase_Persistence_ObjectStorage|Tx_Extbase_Persistence_LazyLoadingProxy|another implementation of a loading strategy
231 */
232 protected function mapRelatedObjects(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, Tx_Extbase_Persistence_RowInterface $row, Tx_Extbase_Persistence_Mapper_ColumnMap $columnMap) {
233 $dataMap = $this->getDataMap(get_class($parentObject));
234 $columnMap = $dataMap->getColumnMap($propertyName);
235 $targetClassSchema = $this->reflectionService->getClassSchema(get_class($parentObject));
236 $propertyMetaData = $targetClassSchema->getProperty($propertyName);
237 $fieldValue = $row[$columnMap->getColumnName()];
238 if ($columnMap->getLoadingStrategy() === Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_LAZY_PROXY) {
239 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyLoadingProxy', $parentObject, $propertyName, $fieldValue, $columnMap);
240 } else {
241 $queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
242 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
243 $query = $queryFactory->create($columnMap->getChildClassName());
244 // 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
245 // enableFields and storage page settings.
246 $query->getQuerySettings()->setRespectStoragePage(FALSE);
247 $result = current($query->matching($query->withUid((int)$fieldValue))->execute());
248 } elseif (($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) || ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY)) {
249 if ($propertyMetaData['lazy'] === TRUE || $columnMap->getLoadingStrategy() === Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_LAZY_STORAGE) {
250 $result = new Tx_Extbase_Persistence_LazyObjectStorage($parentObject, $propertyName, $fieldValue, $columnMap);
251 } else {
252 $objects = $this->fetchRelatedObjects($parentObject, $propertyName, $fieldValue, $columnMap);
253 if ($propertyMetaData['type'] === 'ArrayObject') {
254 $result = new ArrayObject($objects);
255 } elseif ($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage' || $propertyMetaData['type'] === 'Tx_Extbase_Persistence_LazyObjectStorage') {
256 $result = new Tx_Extbase_Persistence_ObjectStorage();
257 foreach ($objects as $object) {
258 $result->attach($object);
259 }
260 } else {
261 $result = $objects;
262 }
263 }
264 }
265 }
266 return $result;
267 }
268
269 /**
270 * Fetches a collection of objects related to a property of a parent object
271 *
272 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject The object instance this proxy is part of
273 * @param string $propertyName The name of the proxied property in it's parent
274 * @param mixed $fieldValue The raw field value.
275 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The corresponding Data Map of the property
276 * @return Tx_Extbase_Persistence_ObjectStorage An Object Storage containing the related objects
277 */
278 public function fetchRelatedObjects(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, $fieldValue, Tx_Extbase_Persistence_Mapper_ColumnMap $columnMap) {
279 $queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
280 $objects = NULL;
281 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
282 $query = $queryFactory->create($columnMap->getChildClassName());
283 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
284 if (isset($parentKeyFieldName)) {
285 $query->matching($query->equals($columnMap->getParentKeyFieldName(), $parentObject->getUid()));
286 if ($columnMap->getChildSortByFieldName()) {
287 $query->setOrderings(array($columnMap->getChildSortByFieldName() => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING ) );
288 }
289 $objects = $query->execute();
290 } else {
291 $uidArray = t3lib_div::intExplode(',', $fieldValue);
292 $uids = implode(',', $uidArray);
293 // FIXME Using statement() is only a preliminary solution
294 $objects = $query->statement('SELECT * FROM ' . $columnMap->getChildTableName() . ' WHERE uid IN (' . $uids . ')')->execute();
295 }
296 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
297 $relationTableName = $columnMap->getRelationTableName();
298 $left = $this->QOMFactory->selector(NULL, $relationTableName);
299 $childClassName = $columnMap->getChildClassName();
300 $childTableName = $columnMap->getChildTableName();
301 $right = $this->QOMFactory->selector($childClassName, $childTableName);
302 $joinCondition = $this->QOMFactory->equiJoinCondition($relationTableName, $columnMap->getChildKeyFieldName(), $childTableName, 'uid');
303 $source = $this->QOMFactory->join(
304 $left,
305 $right,
306 Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER,
307 $joinCondition
308 );
309 $query = $queryFactory->create($columnMap->getChildClassName());
310 $query->setSource($source);
311 $query->setOrderings(array($columnMap->getChildSortByFieldName() => Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING));
312 // 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
313 // enableFields and storage page settings.
314 $query->getQuerySettings()->setRespectStoragePage(FALSE);
315 $objects = $query->matching($query->equals($columnMap->getParentKeyFieldName(), $parentObject->getUid()))->execute();
316 } else {
317 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
318 }
319 return $objects;
320 }
321
322 /**
323 * Delegates the call to the Data Map.
324 * Returns TRUE if the property is persistable (configured in $TCA)
325 *
326 * @param string $className The property name
327 * @param string $propertyName The property name
328 * @return boolean TRUE if the property is persistable (configured in $TCA)
329 */
330 public function isPersistableProperty($className, $propertyName) {
331 $dataMap = $this->getDataMap($className);
332 return $dataMap->isPersistableProperty($propertyName);
333 }
334
335 /**
336 * Returns a data map for a given class name
337 *
338 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
339 */
340 public function getDataMap($className) {
341 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);
342 if (!isset($this->dataMaps[$className])) {
343 // FIXME This is too expensive for table name aliases -> implement a DataMapBuilder (knowing the aliases defined in $TCA)
344 $columnMapping = array();
345 $tableName = '';
346 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
347 if (is_array($extbaseSettings['persistence']['classes'][$className])) {
348 $persistenceSettings = $extbaseSettings['persistence']['classes'][$className];
349 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
350 $tableName = $persistenceSettings['mapping']['tableName'];
351 }
352 if (is_array($persistenceSettings['mapping']['columns'])) {
353 $columnMapping = $persistenceSettings['mapping']['columns'];
354 }
355 } else {
356 foreach (class_parents($className) as $parentClassName) {
357 $persistenceSettings = $extbaseSettings['persistence']['classes'][$parentClassName];
358 if (is_array($persistenceSettings)) {
359 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
360 $tableName = $persistenceSettings['mapping']['tableName'];
361 }
362 if (is_array($persistenceSettings['mapping']['columns'])) {
363 $columnMapping = $persistenceSettings['mapping']['columns'];
364 }
365 }
366 break;
367 }
368 }
369 if (strlen($className) === 0) throw new Tx_Extbase_Persistence_Exception('Could not determine table name for given class.', 1256067130);
370
371 $dataMap = new Tx_Extbase_Persistence_Mapper_DataMap($className, $tableName, $columnMapping);
372 $this->dataMaps[$className] = $dataMap;
373 }
374 return $this->dataMaps[$className];
375 }
376
377 /**
378 * Returns the selector (table) name for a given class name.
379 *
380 * @param string $className
381 * @return string The selector name
382 */
383 public function convertClassNameToTableName($className) {
384 return $this->getDataMap($className)->getTableName();
385 }
386
387 /**
388 * Returns the column name for a given property name of the specified class.
389 *
390 * @param string $className
391 * @param string $propertyName
392 * @return string The column name
393 */
394 public function convertPropertyNameToColumnName($propertyName, $className = '') {
395 if (!empty($className)) {
396 $dataMap = $this->getDataMap($className);
397 if ($dataMap !== NULL) {
398 $columnMap = $dataMap->getColumnMap($propertyName);
399 if ($columnMap !== NULL) {
400 return $columnMap->getColumnName();
401 }
402 }
403 }
404 return Tx_Extbase_Utility_Extension::convertCamelCaseToLowerCaseUnderscored($propertyName);
405 }
406
407 }
408 ?>