9c17525f019610067a9b4c0f8779a749e30ea6c0
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Property / PropertyMapper.php
1 <?php
2 namespace TYPO3\CMS\Extbase\Property;
3
4 /* *
5 * This script belongs to the Extbase framework *
6 * *
7 * It is free software; you can redistribute it and/or modify it under *
8 * the terms of the GNU Lesser General Public License as published by the *
9 * Free Software Foundation, either version 3 of the License, or (at your *
10 * option) any later version. *
11 * *
12 * This script is distributed in the hope that it will be useful, but *
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- *
14 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser *
15 * General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Lesser General Public *
18 * License along with the script. *
19 * If not, see http://www.gnu.org/licenses/lgpl.html *
20 * *
21 * The TYPO3 project - inspiring people to share! *
22 * */
23 /**
24 * The Property Mapper transforms simple types (arrays, strings, integers, floats, booleans) to objects or other simple types.
25 * It is used most prominently to map incoming HTTP arguments to objects.
26 *
27 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License, version 3 or later
28 * @api
29 */
30 class PropertyMapper implements \TYPO3\CMS\Core\SingletonInterface {
31
32 /**
33 * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
34 */
35 protected $objectManager;
36
37 /**
38 * @var \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationBuilder
39 */
40 protected $configurationBuilder;
41
42 /**
43 * @var \TYPO3\CMS\Extbase\Service\TypeHandlingService
44 */
45 protected $typeHandlingService;
46
47 /**
48 * A multi-dimensional array which stores the Type Converters available in the system.
49 * It has the following structure:
50 * 1. Dimension: Source Type
51 * 2. Dimension: Target Type
52 * 3. Dimension: Priority
53 * Value: Type Converter instance
54 *
55 * @var array
56 */
57 protected $typeConverters = array();
58
59 /**
60 * A list of property mapping messages (errors, warnings) which have occured on last mapping.
61 *
62 * @var \TYPO3\CMS\Extbase\Error\Result
63 */
64 protected $messages;
65
66 /**
67 * @param \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager
68 * @return void
69 */
70 public function injectObjectManager(\TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager) {
71 $this->objectManager = $objectManager;
72 }
73
74 /**
75 * @param \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationBuilder $propertyMappingConfigurationBuilder
76 * @return void
77 */
78 public function injectPropertyMappingConfigurationBuilder(\TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationBuilder $propertyMappingConfigurationBuilder) {
79 $this->configurationBuilder = $propertyMappingConfigurationBuilder;
80 }
81
82 /**
83 * @param \TYPO3\CMS\Extbase\Service\TypeHandlingService $typeHandlingService
84 * @return void
85 */
86 public function injectTypeHandlingService(\TYPO3\CMS\Extbase\Service\TypeHandlingService $typeHandlingService) {
87 $this->typeHandlingService = $typeHandlingService;
88 }
89
90 /**
91 * Lifecycle method, called after all dependencies have been injected.
92 * Here, the typeConverter array gets initialized.
93 *
94 * @throws Exception\DuplicateTypeConverterException
95 * @return void
96 */
97 public function initializeObject() {
98 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['extbase']['typeConverters'] as $typeConverterClassName) {
99 $typeConverter = $this->objectManager->get($typeConverterClassName);
100 foreach ($typeConverter->getSupportedSourceTypes() as $supportedSourceType) {
101 if (isset($this->typeConverters[$supportedSourceType][$typeConverter->getSupportedTargetType()][$typeConverter->getPriority()])) {
102 throw new \TYPO3\CMS\Extbase\Property\Exception\DuplicateTypeConverterException('There exist at least two converters which handle the conversion from "' . $supportedSourceType . '" to "' . $typeConverter->getSupportedTargetType() . '" with priority "' . $typeConverter->getPriority() . '": ' . get_class($this->typeConverters[$supportedSourceType][$typeConverter->getSupportedTargetType()][$typeConverter->getPriority()]) . ' and ' . get_class($typeConverter), 1297951378);
103 }
104 $this->typeConverters[$supportedSourceType][$typeConverter->getSupportedTargetType()][$typeConverter->getPriority()] = $typeConverter;
105 }
106 }
107 }
108
109 /**
110 * Map $source to $targetType, and return the result
111 *
112 * @param mixed $source the source data to map. MUST be a simple type, NO object allowed!
113 * @param string $targetType The type of the target; can be either a class name or a simple type.
114 * @param \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration Configuration for the property mapping. If NULL, the PropertyMappingConfigurationBuilder will create a default configuration.
115 * @throws Exception
116 * @return mixed an instance of $targetType
117 * @api
118 */
119 public function convert($source, $targetType, \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration = NULL) {
120 if ($configuration === NULL) {
121 $configuration = $this->configurationBuilder->build();
122 }
123 $currentPropertyPath = array();
124 $this->messages = new \TYPO3\CMS\Extbase\Error\Result();
125 try {
126 return $this->doMapping($source, $targetType, $configuration, $currentPropertyPath);
127 } catch (\Exception $e) {
128 throw new \TYPO3\CMS\Extbase\Property\Exception('Exception while property mapping at property path "' . implode('.', $currentPropertyPath) . '":' . $e->getMessage(), 1297759968, $e);
129 }
130 }
131
132 /**
133 * Get the messages of the last Property Mapping
134 *
135 * @return \TYPO3\CMS\Extbase\Error\Result
136 * @api
137 */
138 public function getMessages() {
139 return $this->messages;
140 }
141
142 /**
143 * Internal function which actually does the property mapping.
144 *
145 * @param mixed $source the source data to map. MUST be a simple type, NO object allowed!
146 * @param string $targetType The type of the target; can be either a class name or a simple type.
147 * @param \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration Configuration for the property mapping.
148 * @param array $currentPropertyPath The property path currently being mapped; used for knowing the context in case an exception is thrown.
149 * @throws Exception\TypeConverterException
150 * @return mixed an instance of $targetType
151 */
152 protected function doMapping($source, $targetType, \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration, &$currentPropertyPath) {
153 if ($source === NULL) {
154 $source = '';
155 }
156 // This is needed to correctly convert old class names to new ones
157 // This compatibility layer will be removed with 7.0
158 $targetType = \TYPO3\CMS\Core\Core\ClassLoader::getClassNameForAlias($targetType);
159 if (is_object($source)) {
160 $targetType = $this->parseCompositeType($targetType);
161 if ($source instanceof $targetType) {
162 return $source;
163 }
164 }
165 $typeConverter = $this->findTypeConverter($source, $targetType, $configuration);
166 if (!is_object($typeConverter) || !$typeConverter instanceof \TYPO3\CMS\Extbase\Property\TypeConverterInterface) {
167 throw new \TYPO3\CMS\Extbase\Property\Exception\TypeConverterException('Type converter for "' . $source . '" -> "' . $targetType . '" not found.');
168 }
169 $convertedChildProperties = array();
170 foreach ($typeConverter->getSourceChildPropertiesToBeConverted($source) as $sourcePropertyName => $sourcePropertyValue) {
171 $targetPropertyName = $configuration->getTargetPropertyName($sourcePropertyName);
172 if (!$configuration->shouldMap($targetPropertyName)) {
173 throw new \TYPO3\CMS\Extbase\Property\Exception\InvalidPropertyMappingConfigurationException('It is not allowed to map property "' . $targetPropertyName . '". You need to use $propertyMappingConfiguration->allowProperties(\'' . $targetPropertyName . '\') to enable mapping of this property.', 1355155913);
174 }
175 $targetPropertyType = $typeConverter->getTypeOfChildProperty($targetType, $targetPropertyName, $configuration);
176 $subConfiguration = $configuration->getConfigurationFor($targetPropertyName);
177 $currentPropertyPath[] = $targetPropertyName;
178 $targetPropertyValue = $this->doMapping($sourcePropertyValue, $targetPropertyType, $subConfiguration, $currentPropertyPath);
179 array_pop($currentPropertyPath);
180 if ($targetPropertyValue !== NULL) {
181 $convertedChildProperties[$targetPropertyName] = $targetPropertyValue;
182 }
183 }
184 $result = $typeConverter->convertFrom($source, $targetType, $convertedChildProperties, $configuration);
185 if ($result instanceof \TYPO3\CMS\Extbase\Error\Error) {
186 $this->messages->forProperty(implode('.', $currentPropertyPath))->addError($result);
187 $result = NULL;
188 }
189 return $result;
190 }
191
192 /**
193 * Determine the type converter to be used. If no converter has been found, an exception is raised.
194 *
195 * @param mixed $source
196 * @param string $targetType
197 * @param \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration
198 * @throws Exception\TypeConverterException
199 * @throws Exception\InvalidTargetException
200 * @return \TYPO3\CMS\Extbase\Property\TypeConverterInterface Type Converter which should be used to convert between $source and $targetType.
201 */
202 protected function findTypeConverter($source, $targetType, \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration) {
203 if ($configuration->getTypeConverter() !== NULL) {
204 return $configuration->getTypeConverter();
205 }
206 $sourceType = $this->determineSourceType($source);
207 if (!is_string($targetType)) {
208 throw new \TYPO3\CMS\Extbase\Property\Exception\InvalidTargetException('The target type was no string, but of type "' . gettype($targetType) . '"', 1297941727);
209 }
210 $targetType = $this->parseCompositeType($targetType);
211 $converter = NULL;
212 if ($this->typeHandlingService->isSimpleType($targetType)) {
213 if (isset($this->typeConverters[$sourceType][$targetType])) {
214 $converter = $this->findEligibleConverterWithHighestPriority($this->typeConverters[$sourceType][$targetType], $source, $targetType);
215 }
216 } else {
217 $converter = $this->findFirstEligibleTypeConverterInObjectHierarchy($source, $sourceType, $targetType);
218 }
219 if ($converter === NULL) {
220 throw new \TYPO3\CMS\Extbase\Property\Exception\TypeConverterException('No converter found which can be used to convert from "' . $sourceType . '" to "' . $targetType . '".');
221 }
222 return $converter;
223 }
224
225 /**
226 * Tries to find a suitable type converter for the given source and target type.
227 *
228 * @param string $source The actual source value
229 * @param string $sourceType Type of the source to convert from
230 * @param string $targetClass Name of the target class to find a type converter for
231 * @return mixed Either the matching object converter or NULL
232 * @throws Exception\InvalidTargetException
233 */
234 protected function findFirstEligibleTypeConverterInObjectHierarchy($source, $sourceType, $targetClass) {
235 if (!class_exists($targetClass) && !interface_exists($targetClass)) {
236 throw new \TYPO3\CMS\Extbase\Property\Exception\InvalidTargetException('Could not find a suitable type converter for "' . $targetClass . '" because no such class or interface exists.', 1297948764);
237 }
238 if (!isset($this->typeConverters[$sourceType])) {
239 return NULL;
240 }
241 $convertersForSource = $this->typeConverters[$sourceType];
242 if (isset($convertersForSource[$targetClass])) {
243 $converter = $this->findEligibleConverterWithHighestPriority($convertersForSource[$targetClass], $source, $targetClass);
244 if ($converter !== NULL) {
245 return $converter;
246 }
247 }
248 foreach (class_parents($targetClass) as $parentClass) {
249 if (!isset($convertersForSource[$parentClass])) {
250 continue;
251 }
252 $converter = $this->findEligibleConverterWithHighestPriority($convertersForSource[$parentClass], $source, $targetClass);
253 if ($converter !== NULL) {
254 return $converter;
255 }
256 }
257 $converters = $this->getConvertersForInterfaces($convertersForSource, class_implements($targetClass));
258 $converter = $this->findEligibleConverterWithHighestPriority($converters, $source, $targetClass);
259 if ($converter !== NULL) {
260 return $converter;
261 }
262 if (isset($convertersForSource['object'])) {
263 return $this->findEligibleConverterWithHighestPriority($convertersForSource['object'], $source, $targetClass);
264 } else {
265 return NULL;
266 }
267 }
268
269 /**
270 * @param mixed $converters
271 * @param mixed $source
272 * @param string $targetType
273 * @return mixed Either the matching object converter or NULL
274 */
275 protected function findEligibleConverterWithHighestPriority($converters, $source, $targetType) {
276 if (!is_array($converters)) {
277 return NULL;
278 }
279 krsort($converters);
280 reset($converters);
281 foreach ($converters as $converter) {
282 if ($converter->canConvertFrom($source, $targetType)) {
283 return $converter;
284 }
285 }
286 return NULL;
287 }
288
289 /**
290 * @param array $convertersForSource
291 * @param array $interfaceNames
292 * @return array
293 * @throws Exception\DuplicateTypeConverterException
294 */
295 protected function getConvertersForInterfaces(array $convertersForSource, array $interfaceNames) {
296 $convertersForInterface = array();
297 foreach ($interfaceNames as $implementedInterface) {
298 if (isset($convertersForSource[$implementedInterface])) {
299 foreach ($convertersForSource[$implementedInterface] as $priority => $converter) {
300 if (isset($convertersForInterface[$priority])) {
301 throw new \TYPO3\CMS\Extbase\Property\Exception\DuplicateTypeConverterException('There exist at least two converters which handle the conversion to an interface with priority "' . $priority . '". ' . get_class($convertersForInterface[$priority]) . ' and ' . get_class($converter), 1297951338);
302 }
303 $convertersForInterface[$priority] = $converter;
304 }
305 }
306 }
307 return $convertersForInterface;
308 }
309
310 /**
311 * Determine the type of the source data, or throw an exception if source was an unsupported format.
312 *
313 * @param mixed $source
314 * @throws Exception\InvalidSourceException
315 * @return string the type of $source
316 */
317 protected function determineSourceType($source) {
318 if (is_string($source)) {
319 return 'string';
320 } elseif (is_array($source)) {
321 return 'array';
322 } elseif (is_float($source)) {
323 return 'float';
324 } elseif (is_integer($source)) {
325 return 'integer';
326 } elseif (is_bool($source)) {
327 return 'boolean';
328 } else {
329 throw new \TYPO3\CMS\Extbase\Property\Exception\InvalidSourceException('The source is not of type string, array, float, integer or boolean, but of type "' . gettype($source) . '"', 1297773150);
330 }
331 }
332
333 /**
334 * Parse a composite type like \Foo\Collection<\Bar\Entity> into
335 * \Foo\Collection
336 *
337 * @param string $compositeType
338 * @return string
339 */
340 public function parseCompositeType($compositeType) {
341 if (strpos($compositeType, '<') !== FALSE) {
342 $compositeType = substr($compositeType, 0, strpos($compositeType, '<'));
343 }
344 return $compositeType;
345 }
346
347 }
348
349 ?>