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 * @var Tx_Extbase_Persistence_Session
47 protected $persistenceSession;
50 * A reference to the page select object providing methods to perform language and work space overlays
52 * @var t3lib_pageSelect
54 protected $pageSelectObject;
61 protected $dataMaps = array();
64 * @var Tx_Extbase_Persistence_QueryFactoryInterface
66 protected $queryFactory;
69 * The TYPO3 reference index object
73 protected $referenceIndex;
76 * Constructs a new mapper
79 public function __construct() {
80 $this->queryFactory
= t3lib_div
::makeInstance('Tx_Extbase_Persistence_QueryFactory');
84 * Injects the identity map
86 * @param Tx_Extbase_Persistence_IdentityMap $identityMap
89 public function injectIdentityMap(Tx_Extbase_Persistence_IdentityMap
$identityMap) {
90 $this->identityMap
= $identityMap;
94 * Injects the persistence manager
96 * @param Tx_Extbase_Persistence_ManagerInterface $persistenceManager
99 public function injectPersistenceManager(Tx_Extbase_Persistence_ManagerInterface
$persistenceManager) {
100 $this->QOMFactory
= $persistenceManager->getBackend()->getQOMFactory();
101 $this->persistenceSession
= $persistenceManager->getSession();
105 * Maps the (aggregate root) rows and registers them as reconstituted
108 * @param Tx_Extbase_Persistence_RowIteratorInterface $rows
111 public function map($className, Tx_Extbase_Persistence_RowIteratorInterface
$rows) {
113 foreach ($rows as $row) {
114 $objects[] = $this->mapSingleRow($className, $row);
120 * Maps a single node into the object it represents
122 * @param Tx_Extbase_Persistence_RowInterface $node
125 protected function mapSingleRow($className, Tx_Extbase_Persistence_RowInterface
$row) {
126 if ($this->identityMap
->hasIdentifier($row['uid'], $className)) {
127 $object = $this->identityMap
->getObjectByIdentifier($row['uid'], $className);
129 $object = $this->createEmptyObject($className);
130 $this->thawProperties($object, $row);
131 $this->identityMap
->registerObject($object, $object->getUid());
132 $object->_memorizeCleanState();
133 $this->persistenceSession
->registerReconstitutedObject($object);
139 * Creates a skeleton of the specified object
141 * @param string $className Name of the class to create a skeleton for
142 * @return object The object skeleton
144 protected function createEmptyObject($className) {
145 // Note: The class_implements() function also invokes autoload to assure that the interfaces
146 // and the class are loaded. Would end up with __PHP_Incomplete_Class without it.
147 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);
148 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
153 * Sets the given properties on the object.
155 * @param Tx_Extbase_DomainObject_DomainObjectInterface $object The object to set properties on
156 * @param Tx_Extbase_Persistence_RowInterface $row
159 protected function thawProperties(Tx_Extbase_DomainObject_DomainObjectInterface
$object, Tx_Extbase_Persistence_RowInterface
$row) {
160 $className = get_class($object);
161 $dataMap = $this->getDataMap($className);
162 $properties = $object->_getProperties();
163 $object->_setProperty('uid', $row['uid']);
164 foreach ($properties as $propertyName => $propertyValue) {
165 if (!$dataMap->isPersistableProperty($propertyName)) continue;
166 $columnMap = $dataMap->getColumnMap($propertyName);
167 $columnName = $columnMap->getColumnName();
168 $propertyValue = NULL;
169 $propertyType = $columnMap->getPropertyType();
170 switch ($propertyType) {
171 case Tx_Extbase_Persistence_PropertyType
::STRING;
172 case Tx_Extbase_Persistence_PropertyType
::DATE
;
173 case Tx_Extbase_Persistence_PropertyType
::LONG
;
174 case Tx_Extbase_Persistence_PropertyType
::DOUBLE;
175 case Tx_Extbase_Persistence_PropertyType
::BOOLEAN
;
176 if (isset($row[$columnName])) {
177 $rawPropertyValue = $row[$columnName];
178 $propertyValue = $dataMap->convertFieldValueToPropertyValue($propertyType, $rawPropertyValue);
181 case (Tx_Extbase_Persistence_PropertyType
::REFERENCE
):
182 if (!is_null($row[$columnName])) {
183 $propertyValue = $this->mapRelatedObjects($object, $propertyName, $row, $columnMap);
185 $propertyValue = NULL;
188 // FIXME we have an object to handle... -> exception
190 // SK: We should throw an exception as this point as there was an undefined propertyType we can not handle.
191 if (isset($row[$columnName])) {
192 $property = $row[$columnName];
193 if (is_object($property)) {
194 $propertyValue = $this->mapObject($property);
195 // SK: THIS case can not happen I think. At least $this->mapObject() is not available.
197 // SK: This case does not make sense either. $this-mapSingleRow has a different signature
198 $propertyValue = $this->mapSingleRow($className, $property);
204 $object->_setProperty($propertyName, $propertyValue);
209 * Maps related objects to an ObjectStorage
211 * @param object $parentObject The parent object for the mapping result
212 * @param string $propertyName The target property name for the mapping result
213 * @param Tx_Extbase_Persistence_RowInterface $row The actual database row
214 * @param int $loadingStrategy The loading strategy; one of Tx_Extbase_Persistence_Mapper_ColumnMap::STRATEGY_*
215 * @return array|Tx_Extbase_Persistence_ObjectStorage|Tx_Extbase_Persistence_LazyLoadingProxy|another implementation of a loading strategy
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_LAZY_PROXY
) {
222 $result = t3lib_div
::makeInstance('Tx_Extbase_Persistence_LazyLoadingProxy', $parentObject, $propertyName, $fieldValue, $columnMap);
224 $queryFactory = t3lib_div
::makeInstance('Tx_Extbase_Persistence_QueryFactory');
225 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_ONE
) {
226 $query = $queryFactory->create($columnMap->getChildClassName());
227 // 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
228 // enableFields and storage page settings.
229 $query->getQuerySettings()->setRespectStoragePage(FALSE);
230 $result = current($query->matching($query->withUid((int)$fieldValue))->execute());
231 } elseif (($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) ||
($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
)) {
232 if ($columnMap->getLoadingStrategy() === Tx_Extbase_Persistence_Mapper_ColumnMap
::STRATEGY_LAZY_STORAGE
) {
233 $objectStorage = new Tx_Extbase_Persistence_LazyObjectStorage($parentObject, $propertyName, $fieldValue, $columnMap);
235 $objectStorage = new Tx_Extbase_Persistence_ObjectStorage();
236 if (!empty($fieldValue)) {
237 $objects = $this->fetchRelatedObjects($parentObject, $propertyName, $fieldValue, $columnMap);
238 foreach ($objects as $object) {
239 $objectStorage->attach($object);
243 $result = $objectStorage;
250 * Fetches a collection of objects related to a property of a parent object
252 * @param Tx_Extbase_DomainObject_AbstractEntity $parentObject The object instance this proxy is part of
253 * @param string $propertyName The name of the proxied property in it's parent
254 * @param mixed $fieldValue The raw field value.
255 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The corresponding Data Map of the property
256 * @return Tx_Extbase_Persistence_ObjectStorage An Object Storage containing the related objects
258 public function fetchRelatedObjects(Tx_Extbase_DomainObject_AbstractEntity
$parentObject, $propertyName, $fieldValue, Tx_Extbase_Persistence_Mapper_ColumnMap
$columnMap) {
259 $queryFactory = t3lib_div
::makeInstance('Tx_Extbase_Persistence_QueryFactory');
261 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) {
262 $query = $queryFactory->create($columnMap->getChildClassName());
263 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
264 if (isset($parentKeyFieldName)) {
265 $objects = $query->matching($query->equals($columnMap->getParentKeyFieldName(), $parentObject->getUid()))->execute();
267 $uidArray = t3lib_div
::intExplode(',', $fieldValue);
268 $uids = implode(',', $uidArray);
269 // FIXME Using statement() is only a preliminary solution
270 $objects = $query->statement('SELECT * FROM ' . $columnMap->getChildTableName() . ' WHERE uid IN (' . $uids . ')')->execute();
272 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
273 $relationTableName = $columnMap->getRelationTableName();
274 $left = $this->QOMFactory
->selector(NULL, $relationTableName);
275 $childClassName = $columnMap->getChildClassName();
276 $childTableName = $columnMap->getChildTableName();
277 $right = $this->QOMFactory
->selector($childClassName, $childTableName);
278 $joinCondition = $this->QOMFactory
->equiJoinCondition($relationTableName, $columnMap->getChildKeyFieldName(), $childTableName, 'uid');
279 $source = $this->QOMFactory
->join(
282 Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_JOIN_TYPE_INNER
,
285 $query = $queryFactory->create($columnMap->getChildClassName());
286 $query->setSource($source);
287 $query->setOrderings(array($columnMap->getChildSortByFieldName() => Tx_Extbase_Persistence_QueryInterface
::ORDER_ASCENDING
));
288 $objects = $query->matching($query->equals($columnMap->getParentKeyFieldName(), $parentObject->getUid()))->execute();
290 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
296 * Delegates the call to the Data Map.
297 * Returns TRUE if the property is persistable (configured in $TCA)
299 * @param string $className The property name
300 * @param string $propertyName The property name
301 * @return boolean TRUE if the property is persistable (configured in $TCA)
303 public function isPersistableProperty($className, $propertyName) {
304 $dataMap = $this->getDataMap($className);
305 return $dataMap->isPersistableProperty($propertyName);
309 * Returns a data map for a given class name
311 * @return Tx_Extbase_Persistence_Mapper_DataMap The data map
313 public function getDataMap($className) {
314 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);
315 if (!isset($this->dataMaps
[$className])) {
316 // FIXME This is too expensive for table name aliases -> implement a DataMapBuilder (knowing the aliases defined in $TCA)
317 $columnMapping = array();
318 $extbaseSettings = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
319 if (is_array($extbaseSettings['persistence']['classes'][$className])) {
320 $persistenceSettings = $extbaseSettings['persistence']['classes'][$className];
321 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
322 $tableName = $persistenceSettings['mapping']['tableName'];
324 if (is_array($persistenceSettings['mapping']['columns'])) {
325 $columnMapping = $persistenceSettings['mapping']['columns'];
328 foreach (class_parents($className) as $parentClassName) {
329 $persistenceSettings = $extbaseSettings['persistence']['classes'][$parentClassName];
330 if (is_array($persistenceSettings)) {
331 if (is_string($persistenceSettings['mapping']['tableName']) && strlen($persistenceSettings['mapping']['tableName']) > 0) {
332 $tableName = $persistenceSettings['mapping']['tableName'];
334 if (is_array($persistenceSettings['mapping']['columns'])) {
335 $columnMapping = $persistenceSettings['mapping']['columns'];
342 $dataMap = new Tx_Extbase_Persistence_Mapper_DataMap($className, $tableName, $columnMapping);
343 $this->dataMaps
[$className] = $dataMap;
345 return $this->dataMaps
[$className];
349 * Returns the selector (table) name for a given class name.
351 * @param string $className
352 * @return string The selector name
354 public function convertClassNameToTableName($className) {
355 return $this->getDataMap($className)->getTableName();
359 * Returns the column name for a given property name of the specified class.
361 * @param string $className
362 * @param string $propertyName
363 * @return string The column name
365 public function convertPropertyNameToColumnName($propertyName, $className = '') {
366 if (!empty($className)) {
367 $dataMap = $this->getDataMap($className);
368 if ($dataMap !== NULL) {
369 $columnMap = $dataMap->getColumnMap($propertyName);
370 if ($columnMap !== NULL) {
371 return $columnMap->getColumnName();
375 return Tx_Extbase_Utility_Extension
::convertCamelCaseToLowerCaseUnderscored($propertyName);