7f28912bf3b5f32e3069de22c645e14efcbe5814
[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_Persistence_QOM_QueryObjectModelFactory
41 */
42 protected $QOMFactory;
43
44 /**
45 * A reference to the page select object providing methods to perform language and work space overlays
46 *
47 * @var t3lib_pageSelect
48 **/
49 protected $pageSelectObject;
50
51 /**
52 * Cached data maps
53 *
54 * @var array
55 **/
56 protected $dataMaps = array();
57
58 /**
59 * @var Tx_Extbase_Persistence_QueryFactoryInterface
60 */
61 protected $queryFactory;
62
63 /**
64 * The TYPO3 reference index object
65 *
66 * @var t3lib_refindex
67 **/
68 protected $referenceIndex;
69
70 /**
71 * Constructs a new mapper
72 *
73 */
74 public function __construct() {
75 $this->queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
76 }
77
78 /**
79 * Injects the identity map
80 *
81 * @param Tx_Extbase_Persistence_IdentityMap $identityMap
82 * @return void
83 */
84 public function injectIdentityMap(Tx_Extbase_Persistence_IdentityMap $identityMap) {
85 $this->identityMap = $identityMap;
86 }
87
88 /**
89 * Injects the persistence manager
90 *
91 * @param Tx_Extbase_Persistence_ManagerInterface $persistenceManager
92 * @return void
93 */
94 public function injectPersistenceManager(Tx_Extbase_Persistence_ManagerInterface $persistenceManager) {
95 $this->QOMFactory = $persistenceManager->getBackend()->getQOMFactory();
96 }
97
98 /**
99 * Maps the (aggregate root) rows and registers them as reconstituted
100 * with the session.
101 *
102 * @param Tx_Extbase_Persistence_RowIteratorInterface $rows
103 * @return array
104 */
105 public function map($className, Tx_Extbase_Persistence_RowIteratorInterface $rows) {
106 $objects = array();
107 foreach ($rows as $row) {
108 $objects[] = $this->mapSingleRow($className, $row);
109 }
110 return $objects;
111 }
112
113 /**
114 * Maps a single node into the object it represents
115 *
116 * @param Tx_Extbase_Persistence_RowInterface $node
117 * @return object
118 */
119 protected function mapSingleRow($className, Tx_Extbase_Persistence_RowInterface $row) {
120 if ($this->identityMap->hasUid($className, $row['uid'])) {
121 $object = $this->identityMap->getObjectByUid($className, $row['uid']);
122 } else {
123 $object = $this->createEmptyObject($className);
124 $this->thawProperties($object, $row);
125 $this->identityMap->registerObject($object, $object->getUid());
126 $object->_memorizeCleanState();
127 }
128 return $object;
129 }
130
131 /**
132 * Creates a skeleton of the specified object
133 *
134 * @param string $className Name of the class to create a skeleton for
135 * @return object The object skeleton
136
137 */
138 protected function createEmptyObject($className) {
139 // Note: The class_implements() function also invokes autoload to assure that the interfaces
140 // and the class are loaded. Would end up with __PHP_Incomplete_Class without it.
141 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);
142 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
143 return $object;
144 }
145
146 /**
147 * Sets the given properties on the object.
148 *
149 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to set properties on
150 * @param Tx_Extbase_Persistence_RowInterface $row
151 * @return void
152 */
153 protected function thawProperties(Tx_Extbase_DomainObject_DomainObjectInterface $object, Tx_Extbase_Persistence_RowInterface $row) {
154 $className = get_class($object);
155 $dataMap = $this->getDataMap($className);
156 $properties = $object->_getProperties();
157 $object->_setProperty('uid', $row['uid']);
158 foreach ($properties as $propertyName => $propertyValue) {
159 if (!$dataMap->isPersistableProperty($propertyName)) continue;
160 $columnMap = $dataMap->getColumnMap($propertyName);
161 $columnName = $columnMap->getColumnName();
162 $propertyValue = NULL;
163 $propertyType = $columnMap->getPropertyType();
164 switch ($propertyType) {
165 case Tx_Extbase_Persistence_PropertyType::STRING;
166 case Tx_Extbase_Persistence_PropertyType::DATE;
167 case Tx_Extbase_Persistence_PropertyType::LONG;
168 case Tx_Extbase_Persistence_PropertyType::DOUBLE;
169 case Tx_Extbase_Persistence_PropertyType::BOOLEAN;
170 if (isset($row[$columnName])) {
171 $rawPropertyValue = $row[$columnName];
172 $propertyValue = $dataMap->convertFieldValueToPropertyValue($propertyType, $rawPropertyValue);
173 }
174 break;
175 case (Tx_Extbase_Persistence_PropertyType::REFERENCE):
176 if (!is_null($row[$columnName])) {
177 $propertyValue = $this->mapRelatedObjects($object, $propertyName, $row, $columnMap);
178 } else {
179 $propertyValue = NULL;
180 }
181 break;
182 // FIXME we have an object to handle... -> exception
183 default:
184 // SK: We should throw an exception as this point as there was an undefined propertyType we can not handle.
185 if (isset($row[$columnName])) {
186 $property = $row[$columnName];
187 if (is_object($property)) {
188 $propertyValue = $this->mapObject($property);
189 // SK: THIS case can not happen I think. At least $this->mapObject() is not available.
190 } else {
191 // SK: This case does not make sense either. $this-mapSingleRow has a different signature
192 $propertyValue = $this->mapSingleRow($className, $property);
193 }
194 }
195 break;
196 }
197
198 $object->_setProperty($propertyName, $propertyValue);
199 }
200 }
201
202 /**
203 * Maps related objects to an ObjectStorage
204 *
205 * @param object $parentObject The parent object for the mapping result
206 * @param string $propertyName The target property name for the mapping result
207 * @param Tx_Extbase_Persistence_RowInterface $row The actual database row
208 * @param int $loadingStrategy The loading strategy; one of Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_*
209 * @return array|Tx_Extbase_Persistence_ObjectStorage|Tx_Extbase_Persistence_LazyLoadingProxy|another implementation of a loading strategy
210 */
211 // FIXME There is a recursion problem with post1 -> post2 and post2 -> post1
212 protected function mapRelatedObjects(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, Tx_Extbase_Persistence_RowInterface $row, Tx_Extbase_Persistence_Mapper_ColumnMap $columnMap) {
213 $dataMap = $this->getDataMap(get_class($parentObject));
214 $columnMap = $dataMap->getColumnMap($propertyName);
215 $fieldValue = $row[$columnMap->getColumnName()];
216 if ($columnMap->getLoadingStrategy() === Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_PROXY) {
217 // TODO Remove dependency to the loading strategy implementation
218 $result = t3lib_div::makeInstance('Tx_Extbase_Persistence_LazyLoadingProxy', $parentObject, $propertyName, $fieldValue, $columnMap);
219 } else {
220 $result = $this->fetchRelatedObjects( $parentObject, $propertyName, $fieldValue, $columnMap);
221 }
222
223 return $result;
224 }
225
226 /**
227 * Fetches a collection of objects related to a property of a parent object
228 *
229 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject The object instance this proxy is part of
230 * @param string $propertyName The name of the proxied property in it's parent
231 * @param mixed $fieldValue The raw field value.
232 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The corresponding Data Map of the property
233
234 */
235 public function fetchRelatedObjects(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, $fieldValue, Tx_Extbase_Persistence_Mapper_ColumnMap $columnMap) {
236 $queryFactory = t3lib_div::makeInstance('Tx_Extbase_Persistence_QueryFactory');
237 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
238 $query = $queryFactory->create($columnMap->getChildClassName());
239 // 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
240 // enableFields and storage page settings.
241 $query->getQuerySettings()->setRespectStoragePage(FALSE);
242 $result = current($query->matching($query->withUid((int)$fieldValue))->execute());
243 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
244 $objectStorage = new Tx_Extbase_Persistence_ObjectStorage();
245 $query = $queryFactory->create($columnMap->getChildClassName());
246 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
247 if (isset($parentKeyFieldName)) {
248 $objects = $query->matching($query->equals($columnMap->getParentKeyFieldName(), $parentObject->getUid()))->execute();
249 } else {
250 // TODO Is it necessary to "normalize" and intval the list?
251 $uids = t3lib_div::trimExplode(',', $fieldValue);
252 $uidArray = array();
253 foreach ($uids as $uid) {
254 $uidArray[] = (int)$uid;
255 }
256 $uids = implode(',', $uidArray);
257 // FIXME Using statement() is only a preliminary solution
258 $objects = $query->statement('SELECT * FROM ' . $columnMap->getChildTableName() . ' WHERE uid IN (' . $uids . ')')->execute();
259 }
260 foreach ($objects as $object) {
261 $objectStorage->attach($object);
262 }
263 $result = $objectStorage;
264 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
265 $objectStorage = new Tx_Extbase_Persistence_ObjectStorage();
266 $relationTableName = $columnMap->getRelationTableName();
267 $left = $this->QOMFactory->selector(NULL, $relationTableName);
268 $childClassName = $columnMap->getChildClassName();
269 $childTableName = $columnMap->getChildTableName();
270 $right = $this->QOMFactory->selector($childClassName, $childTableName);
271 $joinCondition = $this->QOMFactory->equiJoinCondition($relationTableName, $columnMap->getChildKeyFieldName(), $childTableName, 'uid');
272 $source = $this->QOMFactory->join(
273 $left,
274 $right,
275 Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER,
276 $joinCondition
277 );
278 $query = $queryFactory->create($columnMap->getChildClassName());
279 $query->setSource($source);
280 $objects = $query->matching($query->equals($columnMap->getParentKeyFieldName(), $parentObject->getUid()))->execute();
281 foreach ($objects as $object) {
282 $objectStorage->attach($object);
283 }
284 $result = $objectStorage;
285 }
286
287 return $result;
288 }
289
290 /**
291 * Delegates the call to the Data Map.
292 * Returns TRUE if the property is persistable (configured in $TCA)
293 *
294 * @param string $className The property name
295 * @param string $propertyName The property name
296 * @return boolean TRUE if the property is persistable (configured in $TCA)
297 */
298 public function isPersistableProperty($className, $propertyName) {
299 $dataMap = $this->getDataMap($className);
300 return $dataMap->isPersistableProperty($propertyName);
301 }
302
303 /**
304 * Returns a data map for a given class name
305 *
306 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
307 */
308 public function getDataMap($className) {
309 if (is_string($className) && strlen($className) > 0) {
310 if (empty($this->dataMaps[$className])) {
311 // FIXME This is a costy for table name aliases -> implement a DataMapBuilder (knowing the aliases defined in $TCA)
312 $mapping = array();
313 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
314 if (isset($extbaseSettings['persistence']['classes'][$className]) && !empty($extbaseSettings['persistence']['classes'][$className]['mapping']['tableName'])) {
315 $tableName = $extbaseSettings['persistence']['classes'][$className]['mapping']['tableName'];
316 } else {
317 foreach (class_parents($className) as $parentClassName) {
318 if (isset($extbaseSettings['persistence']['classes'][$parentClassName]) && !empty($extbaseSettings['persistence']['classes'][$parentClassName]['mapping']['tableName'])) {
319 $tableName = $extbaseSettings['persistence']['classes'][$parentClassName]['mapping']['tableName'];
320 break;
321 }
322 // TODO throw Exception
323 }
324 }
325 if (is_array($extbaseSettings['persistence']['classes'][$parentClassName]['mapping']['columns'])) {
326 $mapping = $extbaseSettings['persistence']['classes'][$parentClassName]['mapping']['columns'];
327 }
328
329 $dataMap = new Tx_Extbase_Persistence_Mapper_DataMap($className, $tableName, $mapping);
330 $this->dataMaps[$className] = $dataMap;
331 }
332 return $this->dataMaps[$className];
333 } else {
334 return NULL;
335 }
336 }
337
338 /**
339 * Returns the selector (table) name for a given class name.
340 *
341 * @param string $className
342 * @return string The selector name
343 */
344 public function convertClassNameToTableName($className) {
345
346 return $this->getDataMap($className)->getTableName();
347 }
348
349 /**
350 * Returns the column name for a given property name of the specified class.
351 *
352 * @param string $className
353 * @param string $propertyName
354 * @return string The column name
355 */
356 public function convertPropertyNameToColumnName($propertyName, $className = '') {
357 if (!empty($className)) {
358 $dataMap = $this->getDataMap($className);
359 if ($dataMap !== NULL) {
360 $columnMap = $dataMap->getColumnMap($propertyName);
361 if ($columnMap !== NULL) {
362 return $columnMap->getColumnName();
363 }
364 }
365 }
366 return Tx_Extbase_Utility_Plugin::convertCamelCaseToLowerCaseUnderscored($propertyName);
367 }
368
369 }
370 ?>