2 /***************************************************************
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
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.
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
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.
22 * This copyright notice MUST APPEAR in all copies of the script!
23 ***************************************************************/
26 * A mapper to map database tables configured in $TCA on domain objects.
29 * @subpackage Persistence\Mapper
32 class Tx_Extbase_Persistence_Mapper_DataMapper
implements t3lib_Singleton
{
35 * @var Tx_Extbase_Persistence_IdentityMap
37 protected $identityMap;
40 * @var Tx_Extbase_Persistence_QOM_QueryObjectModelFactory
42 protected $QOMFactory;
45 * A reference to the page select object providing methods to perform language and work space overlays
47 * @var t3lib_pageSelect
49 protected $pageSelectObject;
56 protected $dataMaps = array();
59 * @var Tx_Extbase_Persistence_QueryFactoryInterface
61 protected $queryFactory;
64 * The TYPO3 reference index object
68 protected $referenceIndex;
71 * Constructs a new mapper
74 public function __construct() {
75 $this->queryFactory
= t3lib_div
::makeInstance('Tx_Extbase_Persistence_QueryFactory');
79 * Injects the identity map
81 * @param Tx_Extbase_Persistence_IdentityMap $identityMap
84 public function injectIdentityMap(Tx_Extbase_Persistence_IdentityMap
$identityMap) {
85 $this->identityMap
= $identityMap;
89 * Injects the persistence manager
91 * @param Tx_Extbase_Persistence_ManagerInterface $persistenceManager
94 public function injectPersistenceManager(Tx_Extbase_Persistence_ManagerInterface
$persistenceManager) {
95 $this->QOMFactory
= $persistenceManager->getBackend()->getQOMFactory();
99 * Maps the (aggregate root) rows and registers them as reconstituted
102 * @param Tx_Extbase_Persistence_RowIteratorInterface $rows
105 public function map($className, Tx_Extbase_Persistence_RowIteratorInterface
$rows) {
107 foreach ($rows as $row) {
108 $objects[] = $this->mapSingleRow($className, $row);
114 * Maps a single node into the object it represents
116 * @param Tx_Extbase_Persistence_RowInterface $node
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']);
123 $object = $this->createEmptyObject($className);
124 $this->thawProperties($object, $row);
125 $this->identityMap
->registerObject($object, $object->getUid());
126 $object->_memorizeCleanState();
132 * Creates a skeleton of the specified object
134 * @param string $className Name of the class to create a skeleton for
135 * @return object The object skeleton
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:{};');
147 * Sets the given properties on the object.
149 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to set properties on
150 * @param Tx_Extbase_Persistence_RowInterface $row
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);
175 case (Tx_Extbase_Persistence_PropertyType
::REFERENCE
):
176 if (!is_null($row[$columnName])) {
177 $propertyValue = $this->mapRelatedObjects($object, $propertyName, $row, $columnMap);
179 $propertyValue = NULL;
182 // FIXME we have an object to handle... -> exception
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.
191 // SK: This case does not make sense either. $this-mapSingleRow has a different signature
192 $propertyValue = $this->mapSingleRow($className, $property);
198 $object->_setProperty($propertyName, $propertyValue);
203 * Maps related objects to an ObjectStorage
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
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);
220 $result = $this->fetchRelatedObjects( $parentObject, $propertyName, $fieldValue, $columnMap);
227 * Fetches a collection of objects related to a property of a parent object
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
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();
250 // TODO Is it necessary to "normalize" and intval the list?
251 $uids = t3lib_div
::trimExplode(',', $fieldValue);
253 foreach ($uids as $uid) {
254 $uidArray[] = (int)$uid;
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();
260 foreach ($objects as $object) {
261 $objectStorage->attach($object);
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(
275 Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_JOIN_TYPE_INNER
,
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);
284 $result = $objectStorage;
291 * Delegates the call to the Data Map.
292 * Returns TRUE if the property is persistable (configured in $TCA)
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)
298 public function isPersistableProperty($className, $propertyName) {
299 $dataMap = $this->getDataMap($className);
300 return $dataMap->isPersistableProperty($propertyName);
304 * Returns a data map for a given class name
306 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
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)
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'];
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'];
322 // TODO throw Exception
325 if (is_array($extbaseSettings['persistence']['classes'][$parentClassName]['mapping']['columns'])) {
326 $mapping = $extbaseSettings['persistence']['classes'][$parentClassName]['mapping']['columns'];
329 $dataMap = new Tx_Extbase_Persistence_Mapper_DataMap($className, $tableName, $mapping);
330 $this->dataMaps
[$className] = $dataMap;
332 return $this->dataMaps
[$className];
339 * Returns the selector (table) name for a given class name.
341 * @param string $className
342 * @return string The selector name
344 public function convertClassNameToTableName($className) {
346 return $this->getDataMap($className)->getTableName();
350 * Returns the column name for a given property name of the specified class.
352 * @param string $className
353 * @param string $propertyName
354 * @return string The column name
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();
366 return Tx_Extbase_Utility_Plugin
::convertCamelCaseToLowerCaseUnderscored($propertyName);