[+FEATURE] Extbase (Persistence): Implemented support for mm_opposite_field now....
[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 * 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 $GLOBALS['TSFE']->includeTCA(); // TODO Move this to an appropriate position
77 }
78
79 /**
80 * Injects the identity map
81 *
82 * @param Tx_Extbase_Persistence_IdentityMap $identityMap
83 * @return void
84 */
85 public function injectIdentityMap(Tx_Extbase_Persistence_IdentityMap $identityMap) {
86 $this->identityMap = $identityMap;
87 }
88
89 /**
90 * Injects the persistence manager
91 *
92 * @param Tx_Extbase_Persistence_ManagerInterface $persistenceManager
93 * @return void
94 */
95 public function injectPersistenceManager(Tx_Extbase_Persistence_ManagerInterface $persistenceManager) {
96 $this->persistenceManager = $persistenceManager;
97 $this->QOMFactory = $this->persistenceManager->getBackend()->getQOMFactory();
98 }
99
100 /**
101 * Maps the (aggregate root) rows and registers them as reconstituted
102 * with the session.
103 *
104 * @param Tx_Extbase_Persistence_RowIteratorInterface $rows
105 * @return array
106 */
107 public function map($className, Tx_Extbase_Persistence_RowIteratorInterface $rows) {
108 $objects = array();
109 foreach ($rows as $row) {
110 $objects[] = $this->mapSingleRow($className, $row);
111 }
112 return $objects;
113 }
114
115 /**
116 * Maps a single node into the object it represents
117 *
118 * @param Tx_Extbase_Persistence_RowInterface $node
119 * @return object
120 */
121 protected function mapSingleRow($className, Tx_Extbase_Persistence_RowInterface $row) {
122 if ($this->identityMap->hasUid($className, $row['uid'])) {
123 $object = $this->identityMap->getObjectByUid($className, $row['uid']);
124 } else {
125 $object = $this->createEmptyObject($className);
126 $this->thawProperties($object, $row);
127 $this->identityMap->registerObject($object, $object->getUid());
128 $object->_memorizeCleanState();
129 }
130 return $object;
131 }
132
133 /**
134 * Creates a skeleton of the specified object
135 *
136 * @param string $className Name of the class to create a skeleton for
137 * @return object The object skeleton
138 * @internal
139 */
140 protected function createEmptyObject($className) {
141 // Note: The class_implements() function also invokes autoload to assure that the interfaces
142 // and the class are loaded. Would end up with __PHP_Incomplete_Class without it.
143 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);
144 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
145 return $object;
146 }
147
148 /**
149 * Sets the given properties on the object.
150 *
151 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to set properties on
152 * @param Tx_Extbase_Persistence_RowInterface $row
153 * @return void
154 */
155 protected function thawProperties(Tx_Extbase_DomainObject_DomainObjectInterface $object, Tx_Extbase_Persistence_RowInterface $row) {
156 $className = get_class($object);
157 $dataMap = $this->getDataMap($className);
158 $properties = $object->_getProperties();
159 $object->_setProperty('uid', $row['uid']);
160 foreach ($properties as $propertyName => $propertyValue) {
161 if (!$dataMap->isPersistableProperty($propertyName)) continue;
162 $columnMap = $dataMap->getColumnMap($propertyName);
163 $columnName = $columnMap->getColumnName();
164 $propertyValue = NULL;
165 $propertyType = $columnMap->getPropertyType();
166 switch ($propertyType) {
167 case Tx_Extbase_Persistence_PropertyType::STRING;
168 case Tx_Extbase_Persistence_PropertyType::DATE;
169 case Tx_Extbase_Persistence_PropertyType::LONG;
170 case Tx_Extbase_Persistence_PropertyType::DOUBLE;
171 case Tx_Extbase_Persistence_PropertyType::BOOLEAN;
172 if (isset($row[$columnName])) {
173 $rawPropertyValue = $row[$columnName];
174 $propertyValue = $dataMap->convertFieldValueToPropertyValue($propertyType, $rawPropertyValue);
175 }
176 break;
177 case (Tx_Extbase_Persistence_PropertyType::REFERENCE):
178 if (!is_null($row[$columnName])) {
179 $propertyValue = $this->mapRelatedObjects($object, $propertyName, $row, $columnMap);
180 } else {
181 $propertyValue = NULL;
182 }
183 break;
184 // FIXME we have an object to handle... -> exception
185 default:
186 // SK: We should throw an exception as this point as there was an undefined propertyType we can not handle.
187 if (isset($row[$columnName])) {
188 $property = $row[$columnName];
189 if (is_object($property)) {
190 $propertyValue = $this->mapObject($property);
191 // SK: THIS case can not happen I think. At least $this->mapObject() is not available.
192 } else {
193 // SK: This case does not make sense either. $this-mapSingleRow has a different signature
194 $propertyValue = $this->mapSingleRow($className, $property);
195 }
196 }
197 break;
198 }
199
200 $object->_setProperty($propertyName, $propertyValue);
201 }
202 }
203
204 /**
205 * Maps related objects to an ObjectStorage
206 *
207 * @param object $parentObject The parent object for the mapping result
208 * @param string $propertyName The target property name for the mapping result
209 * @param Tx_Extbase_Persistence_RowInterface $row The actual database row
210 * @param int $loadingStrategy The loading strategy; one of Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_*
211 * @return array|Tx_Extbase_Persistence_ObjectStorage|Tx_Extbase_Persistence_LazyLoadingProxy|another implementation of a loading strategy
212 */
213 protected function mapRelatedObjects(Tx_Extbase_DomainObject_AbstractEntity $parentObject, $propertyName, Tx_Extbase_Persistence_RowInterface $row, Tx_Extbase_Persistence_Mapper_ColumnMap $columnMap) {
214 $dataMap = $this->getDataMap(get_class($parentObject));
215 $columnMap = $dataMap->getColumnMap($propertyName);
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, $dataMap);
219 } else {
220 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
221 $query = $this->queryFactory->create($columnMap->getChildClassName());
222 $result = current($query->matching($query->withUid($row[$columnMap->getColumnName()]))->execute());
223 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
224 $objectStorage = new Tx_Extbase_Persistence_ObjectStorage();
225 $query = $this->queryFactory->create($columnMap->getChildClassName());
226 $objects = $query->matching($query->equals($columnMap->getParentKeyFieldName(), $parentObject->getUid()))->execute();
227 foreach ($objects as $object) {
228 $objectStorage->attach($object);
229 }
230 $result = $objectStorage;
231 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
232 $objectStorage = new Tx_Extbase_Persistence_ObjectStorage();
233 $relationTableName = $columnMap->getRelationTableName();
234 $left = $this->QOMFactory->selector($relationTableName);
235 $childTableName = $columnMap->getChildTableName();
236 $right = $this->QOMFactory->selector($childTableName);
237 $joinCondition = $this->QOMFactory->equiJoinCondition($relationTableName, $columnMap->getChildKeyFieldName(), $childTableName, 'uid');
238 $source = $this->QOMFactory->join(
239 $left,
240 $right,
241 Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER,
242 $joinCondition
243 );
244 $query = $this->queryFactory->create($columnMap->getChildClassName());
245 $query->setSource($source);
246 $objects = $query->matching($query->equals($columnMap->getParentKeyFieldName(), $parentObject->getUid()))->execute();
247 foreach ($objects as $object) {
248 $objectStorage->attach($object);
249 }
250 $result = $objectStorage;
251 }
252 }
253
254 return $result;
255 }
256
257 /**
258 * Delegates the call to the Data Map.
259 * Returns TRUE if the property is persistable (configured in $TCA)
260 *
261 * @param string $className The property name
262 * @param string $propertyName The property name
263 * @return boolean TRUE if the property is persistable (configured in $TCA)
264 */
265 public function isPersistableProperty($className, $propertyName) {
266 $dataMap = $this->getDataMap($className);
267 return $dataMap->isPersistableProperty($propertyName);
268 }
269
270 /**
271 * Returns a data map for a given class name
272 *
273 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
274 */
275 public function getDataMap($className) {
276 global $TCA;
277 if (empty($this->dataMaps[$className])) {
278 // FIXME This is a costy for table name aliases -> implement a DataMapBuilder (knowing the aliases defined in $TCA)
279 $mapping = array();
280 $extbaseSettings = Tx_Extbase_Dispatcher::getSettings();
281 if (isset($extbaseSettings['classes'][$className]) && !empty($extbaseSettings['classes'][$className]['mapping']['tableName'])) {
282 $tableName = $extbaseSettings['classes'][$className]['mapping']['tableName'];
283 } else {
284 foreach (class_parents($className) as $parentClassName) {
285 if (isset($extbaseSettings['classes'][$parentClassName]) && !empty($extbaseSettings['classes'][$parentClassName]['mapping']['tableName'])) {
286 $tableName = $extbaseSettings['classes'][$parentClassName]['mapping']['tableName'];
287 $mapping = $extbaseSettings['classes'][$parentClassName]['mapping']['columns'];
288 break;
289 }
290 // TODO throw Exception
291 }
292 }
293
294 $dataMap = new Tx_Extbase_Persistence_Mapper_DataMap($className, $tableName, $mapping);
295 $this->dataMaps[$className] = $dataMap;
296 }
297 return $this->dataMaps[$className];
298 }
299
300 /**
301 * Returns the selector (table) name for a given class name.
302 *
303 * @param string $className
304 * @return string The selector name
305 */
306 public function convertClassNameToSelectorName($className) {
307 return $this->getDataMap($className)->getTableName();
308 }
309
310 }
311 ?>