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