[BUGFIX] Add domain model validators only once
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Validation / ValidatorResolver.php
1 <?php
2 namespace TYPO3\CMS\Extbase\Validation;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\ClassNamingUtility;
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19 use TYPO3\CMS\Extbase\Utility\TypeHandlingUtility;
20 use TYPO3\CMS\Extbase\Validation\Exception\NoSuchValidatorException;
21 use TYPO3\CMS\Extbase\Validation\Validator\ConjunctionValidator;
22
23 /**
24 * Validator resolver to automatically find a appropriate validator for a given subject
25 */
26 class ValidatorResolver implements \TYPO3\CMS\Core\SingletonInterface {
27
28 /**
29 * Match validator names and options
30 * @todo: adjust [a-z0-9_:.\\\\] once Tx_Extbase_Foo syntax is outdated.
31 *
32 * @var string
33 */
34 const PATTERN_MATCH_VALIDATORS = '/
35 (?:^|,\s*)
36 (?P<validatorName>[a-z0-9_:.\\\\]+)
37 \s*
38 (?:\(
39 (?P<validatorOptions>(?:\s*[a-z0-9]+\s*=\s*(?:
40 "(?:\\\\"|[^"])*"
41 |\'(?:\\\\\'|[^\'])*\'
42 |(?:\s|[^,"\']*)
43 )(?:\s|,)*)*)
44 \))?
45 /ixS';
46
47 /**
48 * Match validator options (to parse actual options)
49 * @var string
50 */
51 const PATTERN_MATCH_VALIDATOROPTIONS = '/
52 \s*
53 (?P<optionName>[a-z0-9]+)
54 \s*=\s*
55 (?P<optionValue>
56 "(?:\\\\"|[^"])*"
57 |\'(?:\\\\\'|[^\'])*\'
58 |(?:\s|[^,"\']*)
59 )
60 /ixS';
61
62 /**
63 * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
64 * @inject
65 */
66 protected $objectManager;
67
68 /**
69 * @var \TYPO3\CMS\Extbase\Reflection\ReflectionService
70 * @inject
71 */
72 protected $reflectionService;
73
74 /**
75 * @var array
76 */
77 protected $baseValidatorConjunctions = array();
78
79 /**
80 * Get a validator for a given data type. Returns a validator implementing
81 * the \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface or NULL if no validator
82 * could be resolved.
83 *
84 * @param string $validatorType Either one of the built-in data types or fully qualified validator class name
85 * @param array $validatorOptions Options to be passed to the validator
86 * @return \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface Validator or NULL if none found.
87 */
88 public function createValidator($validatorType, array $validatorOptions = array()) {
89 try {
90 /**
91 * @todo remove throwing Exceptions in resolveValidatorObjectName
92 */
93 $validatorObjectName = $this->resolveValidatorObjectName($validatorType);
94
95 $validator = $this->objectManager->get($validatorObjectName, $validatorOptions);
96
97 if (!($validator instanceof \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface)) {
98 throw new Exception\NoSuchValidatorException('The validator "' . $validatorObjectName . '" does not implement TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface!', 1300694875);
99 }
100
101 return $validator;
102 } catch (NoSuchValidatorException $e) {
103 GeneralUtility::devLog($e->getMessage(), 'extbase', GeneralUtility::SYSLOG_SEVERITY_INFO);
104 return NULL;
105 }
106 }
107
108 /**
109 * Resolves and returns the base validator conjunction for the given data type.
110 *
111 * If no validator could be resolved (which usually means that no validation is necessary),
112 * NULL is returned.
113 *
114 * @param string $targetClassName The data type to search a validator for. Usually the fully qualified object name
115 * @return ConjunctionValidator The validator conjunction or NULL
116 */
117 public function getBaseValidatorConjunction($targetClassName) {
118 if (!array_key_exists($targetClassName, $this->baseValidatorConjunctions)) {
119 $this->buildBaseValidatorConjunction($targetClassName, $targetClassName);
120 }
121
122 return $this->baseValidatorConjunctions[$targetClassName];
123 }
124
125 /**
126 * Detects and registers any validators for arguments:
127 * - by the data type specified in the param annotations
128 * - additional validators specified in the validate annotations of a method
129 *
130 * @param string $className
131 * @param string $methodName
132 * @param array $methodParameters Optional pre-compiled array of method parameters
133 * @param array $methodValidateAnnotations Optional pre-compiled array of validate annotations (as array)
134 * @return ConjunctionValidator[] An Array of ValidatorConjunctions for each method parameters.
135 * @throws \TYPO3\CMS\Extbase\Validation\Exception\InvalidValidationConfigurationException
136 * @throws \TYPO3\CMS\Extbase\Validation\Exception\NoSuchValidatorException
137 * @throws \TYPO3\CMS\Extbase\Validation\Exception\InvalidTypeHintException
138 */
139 public function buildMethodArgumentsValidatorConjunctions($className, $methodName, array $methodParameters = NULL, array $methodValidateAnnotations = NULL) {
140 /** @var ConjunctionValidator[] $validatorConjunctions */
141 $validatorConjunctions = array();
142
143 if ($methodParameters === NULL) {
144 $methodParameters = $this->reflectionService->getMethodParameters($className, $methodName);
145 }
146 if (count($methodParameters) === 0) {
147 return $validatorConjunctions;
148 }
149
150 foreach ($methodParameters as $parameterName => $methodParameter) {
151 /** @var ConjunctionValidator $validatorConjunction */
152 $validatorConjunction = $this->createValidator(ConjunctionValidator::class);
153
154 if (!array_key_exists('type', $methodParameter)) {
155 throw new Exception\InvalidTypeHintException('Missing type information, probably no @param annotation for parameter "$' . $parameterName . '" in ' . $className . '->' . $methodName . '()', 1281962564);
156 }
157
158 // @todo: remove check for old underscore model name syntax once it's possible
159 if (strpbrk($methodParameter['type'], '_\\') === FALSE) {
160 $typeValidator = $this->createValidator($methodParameter['type']);
161 } else {
162 $typeValidator = NULL;
163 }
164
165 if ($typeValidator !== NULL) {
166 $validatorConjunction->addValidator($typeValidator);
167 }
168 $validatorConjunctions[$parameterName] = $validatorConjunction;
169 }
170
171 if ($methodValidateAnnotations === NULL) {
172 $validateAnnotations = $this->getMethodValidateAnnotations($className, $methodName);
173 $methodValidateAnnotations = array_map(function($validateAnnotation) {
174 return array(
175 'type' => $validateAnnotation['validatorName'],
176 'options' => $validateAnnotation['validatorOptions'],
177 'argumentName' => $validateAnnotation['argumentName'],
178 );
179 }, $validateAnnotations);
180 }
181
182 foreach ($methodValidateAnnotations as $annotationParameters) {
183 $newValidator = $this->createValidator($annotationParameters['type'], $annotationParameters['options']);
184 if ($newValidator === NULL) {
185 throw new Exception\NoSuchValidatorException('Invalid validate annotation in ' . $className . '->' . $methodName . '(): Could not resolve class name for validator "' . $annotationParameters['type'] . '".', 1239853109);
186 }
187 if (isset($validatorConjunctions[$annotationParameters['argumentName']])) {
188 $validatorConjunctions[$annotationParameters['argumentName']]->addValidator($newValidator);
189 } elseif (strpos($annotationParameters['argumentName'], '.') !== FALSE) {
190 $objectPath = explode('.', $annotationParameters['argumentName']);
191 $argumentName = array_shift($objectPath);
192 $validatorConjunctions[$argumentName]->addValidator($this->buildSubObjectValidator($objectPath, $newValidator));
193 } else {
194 throw new Exception\InvalidValidationConfigurationException('Invalid validate annotation in ' . $className . '->' . $methodName . '(): Validator specified for argument name "' . $annotationParameters['argumentName'] . '", but this argument does not exist.', 1253172726);
195 }
196 }
197
198 return $validatorConjunctions;
199 }
200
201 /**
202 * Builds a chain of nested object validators by specification of the given
203 * object path.
204 *
205 * @param array $objectPath The object path
206 * @param \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface $propertyValidator The validator which should be added to the property specified by objectPath
207 * @return \TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator
208 */
209 protected function buildSubObjectValidator(array $objectPath, \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface $propertyValidator) {
210 $rootObjectValidator = $this->objectManager->get(\TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator::class, array());
211 $parentObjectValidator = $rootObjectValidator;
212
213 while (count($objectPath) > 1) {
214 $subObjectValidator = $this->objectManager->get(\TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator::class, array());
215 $subPropertyName = array_shift($objectPath);
216 $parentObjectValidator->addPropertyValidator($subPropertyName, $subObjectValidator);
217 $parentObjectValidator = $subObjectValidator;
218 }
219
220 $parentObjectValidator->addPropertyValidator(array_shift($objectPath), $propertyValidator);
221
222 return $rootObjectValidator;
223 }
224
225 /**
226 * Builds a base validator conjunction for the given data type.
227 *
228 * The base validation rules are those which were declared directly in a class (typically
229 * a model) through some validate annotations on properties.
230 *
231 * If a property holds a class for which a base validator exists, that property will be
232 * checked as well, regardless of a validate annotation
233 *
234 * Additionally, if a custom validator was defined for the class in question, it will be added
235 * to the end of the conjunction. A custom validator is found if it follows the naming convention
236 * "Replace '\Model\' by '\Validator\' and append 'Validator'".
237 *
238 * Example: $targetClassName is TYPO3\Foo\Domain\Model\Quux, then the validator will be found if it has the
239 * name TYPO3\Foo\Domain\Validator\QuuxValidator
240 *
241 * @param string $indexKey The key to use as index in $this->baseValidatorConjunctions; calculated from target class name and validation groups
242 * @param string $targetClassName The data type to build the validation conjunction for. Needs to be the fully qualified class name.
243 * @param array $validationGroups The validation groups to build the validator for
244 * @return void
245 * @throws \TYPO3\CMS\Extbase\Validation\Exception\NoSuchValidatorException
246 * @throws \InvalidArgumentException
247 */
248 protected function buildBaseValidatorConjunction($indexKey, $targetClassName, array $validationGroups = array()) {
249 $conjunctionValidator = new ConjunctionValidator();
250 $this->baseValidatorConjunctions[$indexKey] = $conjunctionValidator;
251
252 // note: the simpleType check reduces lookups to the class loader
253 if (!TypeHandlingUtility::isSimpleType($targetClassName) && class_exists($targetClassName)) {
254 // Model based validator
255 /** @var \TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator $objectValidator */
256 $objectValidator = $this->objectManager->get(\TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator::class, array());
257 foreach ($this->reflectionService->getClassPropertyNames($targetClassName) as $classPropertyName) {
258 $classPropertyTagsValues = $this->reflectionService->getPropertyTagsValues($targetClassName, $classPropertyName);
259
260 if (!isset($classPropertyTagsValues['var'])) {
261 throw new \InvalidArgumentException(sprintf('There is no @var annotation for property "%s" in class "%s".', $classPropertyName, $targetClassName), 1363778104);
262 }
263 try {
264 $parsedType = TypeHandlingUtility::parseType(trim(implode('', $classPropertyTagsValues['var']), ' \\'));
265 } catch (\TYPO3\CMS\Extbase\Utility\Exception\InvalidTypeException $exception) {
266 throw new \InvalidArgumentException(sprintf(' @var annotation of ' . $exception->getMessage(), 'class "' . $targetClassName . '", property "' . $classPropertyName . '"'), 1315564744, $exception);
267 }
268 $propertyTargetClassName = $parsedType['type'];
269 // note: the outer simpleType check reduces lookups to the class loader
270 if (!TypeHandlingUtility::isSimpleType($propertyTargetClassName)) {
271 if (TypeHandlingUtility::isCollectionType($propertyTargetClassName)) {
272 $collectionValidator = $this->createValidator(\TYPO3\CMS\Extbase\Validation\Validator\CollectionValidator::class, array('elementType' => $parsedType['elementType'], 'validationGroups' => $validationGroups));
273 $objectValidator->addPropertyValidator($classPropertyName, $collectionValidator);
274 } elseif (class_exists($propertyTargetClassName) && !TypeHandlingUtility::isCoreType($propertyTargetClassName) && $this->objectManager->isRegistered($propertyTargetClassName) && $this->objectManager->getScope($propertyTargetClassName) === \TYPO3\CMS\Extbase\Object\Container\Container::SCOPE_PROTOTYPE) {
275 $validatorForProperty = $this->getBaseValidatorConjunction($propertyTargetClassName, $validationGroups);
276 if (count($validatorForProperty) > 0) {
277 $objectValidator->addPropertyValidator($classPropertyName, $validatorForProperty);
278 }
279 }
280 }
281
282 $validateAnnotations = array();
283 // @todo: Resolve annotations via reflectionService once its available
284 if (isset($classPropertyTagsValues['validate']) && is_array($classPropertyTagsValues['validate'])) {
285 foreach ($classPropertyTagsValues['validate'] as $validateValue) {
286 $parsedAnnotations = $this->parseValidatorAnnotation($validateValue);
287
288 foreach ($parsedAnnotations['validators'] as $validator) {
289 array_push($validateAnnotations, array(
290 'argumentName' => $parsedAnnotations['argumentName'],
291 'validatorName' => $validator['validatorName'],
292 'validatorOptions' => $validator['validatorOptions']
293 ));
294 }
295 }
296 }
297
298 foreach ($validateAnnotations as $validateAnnotation) {
299 // @todo: Respect validationGroups
300 $newValidator = $this->createValidator($validateAnnotation['validatorName'], $validateAnnotation['validatorOptions']);
301 if ($newValidator === NULL) {
302 throw new Exception\NoSuchValidatorException('Invalid validate annotation in ' . $targetClassName . '::' . $classPropertyName . ': Could not resolve class name for validator "' . $validateAnnotation->type . '".', 1241098027);
303 }
304 $objectValidator->addPropertyValidator($classPropertyName, $newValidator);
305 }
306 }
307
308 if (count($objectValidator->getPropertyValidators()) > 0) {
309 $conjunctionValidator->addValidator($objectValidator);
310 }
311 }
312
313 $this->addCustomValidators($targetClassName, $conjunctionValidator);
314 }
315
316 /**
317 * This adds custom validators to the passed $conjunctionValidator.
318 *
319 * A custom validator is found if it follows the naming convention "Replace '\Model\' by '\Validator\' and
320 * append 'Validator'". If found, it will be added to the $conjunctionValidator.
321 *
322 * In addition canValidate() will be called on all implementations of the ObjectValidatorInterface to find
323 * all validators that could validate the target. The one with the highest priority will be added as well.
324 * If multiple validators have the same priority, which one will be added is not deterministic.
325 *
326 * @param string $targetClassName
327 * @param ConjunctionValidator $conjunctionValidator
328 * @return NULL|Validator\ObjectValidatorInterface
329 */
330 protected function addCustomValidators($targetClassName, ConjunctionValidator &$conjunctionValidator) {
331
332 $addedValidatorClassName = NULL;
333 // @todo: get rid of ClassNamingUtility usage once we dropped underscored class name support
334 $possibleValidatorClassName = ClassNamingUtility::translateModelNameToValidatorName($targetClassName);
335
336 $customValidator = $this->createValidator($possibleValidatorClassName);
337 if ($customValidator !== NULL) {
338 $conjunctionValidator->addValidator($customValidator);
339 $addedValidatorClassName = get_class($customValidator);
340 }
341
342 // @todo: find polytype validator for class
343 }
344
345 /**
346 * Parses the validator options given in @validate annotations.
347 *
348 * @param string $validateValue
349 * @return array
350 */
351 protected function parseValidatorAnnotation($validateValue) {
352 $matches = array();
353 if ($validateValue[0] === '$') {
354 $parts = explode(' ', $validateValue, 2);
355 $validatorConfiguration = array('argumentName' => ltrim($parts[0], '$'), 'validators' => array());
356 preg_match_all(self::PATTERN_MATCH_VALIDATORS, $parts[1], $matches, PREG_SET_ORDER);
357 } else {
358 $validatorConfiguration = array('validators' => array());
359 preg_match_all(self::PATTERN_MATCH_VALIDATORS, $validateValue, $matches, PREG_SET_ORDER);
360 }
361 foreach ($matches as $match) {
362 $validatorOptions = array();
363 if (isset($match['validatorOptions'])) {
364 $validatorOptions = $this->parseValidatorOptions($match['validatorOptions']);
365 }
366 $validatorConfiguration['validators'][] = array('validatorName' => $match['validatorName'], 'validatorOptions' => $validatorOptions);
367 }
368 return $validatorConfiguration;
369 }
370
371 /**
372 * Parses $rawValidatorOptions not containing quoted option values.
373 * $rawValidatorOptions will be an empty string afterwards (pass by ref!).
374 *
375 * @param string $rawValidatorOptions
376 * @return array An array of optionName/optionValue pairs
377 */
378 protected function parseValidatorOptions($rawValidatorOptions) {
379 $validatorOptions = array();
380 $parsedValidatorOptions = array();
381 preg_match_all(self::PATTERN_MATCH_VALIDATOROPTIONS, $rawValidatorOptions, $validatorOptions, PREG_SET_ORDER);
382 foreach ($validatorOptions as $validatorOption) {
383 $parsedValidatorOptions[trim($validatorOption['optionName'])] = trim($validatorOption['optionValue']);
384 }
385 array_walk($parsedValidatorOptions, array($this, 'unquoteString'));
386 return $parsedValidatorOptions;
387 }
388
389 /**
390 * Removes escapings from a given argument string and trims the outermost
391 * quotes.
392 *
393 * This method is meant as a helper for regular expression results.
394 *
395 * @param string &$quotedValue Value to unquote
396 * @return void
397 */
398 protected function unquoteString(&$quotedValue) {
399 switch ($quotedValue[0]) {
400 case '"':
401 $quotedValue = str_replace('\\"', '"', trim($quotedValue, '"'));
402 break;
403 case '\'':
404 $quotedValue = str_replace('\\\'', '\'', trim($quotedValue, '\''));
405 break;
406 }
407 $quotedValue = str_replace('\\\\', '\\', $quotedValue);
408 }
409
410 /**
411 * Returns an object of an appropriate validator for the given class. If no validator is available
412 * FALSE is returned
413 *
414 * @param string $validatorName Either the fully qualified class name of the validator or the short name of a built-in validator
415 *
416 * @throws Exception\NoSuchValidatorException
417 * @return string Name of the validator object
418 */
419 protected function resolveValidatorObjectName($validatorName) {
420 if (strpos($validatorName, ':') !== FALSE || strpbrk($validatorName, '_\\') === FALSE) {
421 // Found shorthand validator, either extbase or foreign extension
422 // NotEmpty or Acme.MyPck.Ext:MyValidator
423 list($extensionName, $extensionValidatorName) = explode(':', $validatorName);
424
425 if ($validatorName !== $extensionName && $extensionValidatorName !== '') {
426 // Shorthand custom
427 if (strpos($extensionName, '.') !== FALSE) {
428 $extensionNameParts = explode('.', $extensionName);
429 $extensionName = array_pop($extensionNameParts);
430 $vendorName = implode('\\', $extensionNameParts);
431 $possibleClassName = $vendorName . '\\' . $extensionName . '\\Validation\\Validator\\' . $extensionValidatorName;
432 } else {
433 $possibleClassName = 'Tx_' . $extensionName . '_Validation_Validator_' . $extensionValidatorName;
434 }
435 } else {
436 // Shorthand built in
437 $possibleClassName = 'TYPO3\\CMS\\Extbase\\Validation\\Validator\\' . $this->getValidatorType($validatorName);
438 }
439 } else {
440 // Full qualified
441 // Tx_MyExt_Validation_Validator_MyValidator or \Acme\Ext\Validation\Validator\FooValidator
442 $possibleClassName = $validatorName;
443 }
444
445 if (substr($possibleClassName, - strlen('Validator')) !== 'Validator') {
446 $possibleClassName .= 'Validator';
447 }
448
449 if (class_exists($possibleClassName)) {
450 $possibleClassNameInterfaces = class_implements($possibleClassName);
451 if (!in_array(\TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface::class, $possibleClassNameInterfaces)) {
452 // The guessed validatorname is a valid class name, but does not implement the ValidatorInterface
453 throw new NoSuchValidatorException('Validator class ' . $validatorName . ' must implement \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface', 1365776838);
454 }
455 $resolvedValidatorName = $possibleClassName;
456 } else {
457 throw new NoSuchValidatorException('Validator class ' . $validatorName . ' does not exist', 1365799920);
458 }
459
460 return $resolvedValidatorName;
461 }
462
463 /**
464 * Used to map PHP types to validator types.
465 *
466 * @param string $type Data type to unify
467 * @return string unified data type
468 */
469 protected function getValidatorType($type) {
470 switch ($type) {
471 case 'int':
472 $type = 'Integer';
473 break;
474 case 'bool':
475 $type = 'Boolean';
476 break;
477 case 'double':
478 $type = 'Float';
479 break;
480 case 'numeric':
481 $type = 'Number';
482 break;
483 case 'mixed':
484 $type = 'Raw';
485 break;
486 default:
487 $type = ucfirst($type);
488 }
489 return $type;
490 }
491
492 /**
493 * Temporary replacement for $this->reflectionService->getMethodAnnotations()
494 *
495 * @param string $className
496 * @param string $methodName
497 *
498 * @return array
499 */
500 public function getMethodValidateAnnotations($className, $methodName) {
501 $validateAnnotations = array();
502 $methodTagsValues = $this->reflectionService->getMethodTagsValues($className, $methodName);
503 if (isset($methodTagsValues['validate']) && is_array($methodTagsValues['validate'])) {
504 foreach ($methodTagsValues['validate'] as $validateValue) {
505 $parsedAnnotations = $this->parseValidatorAnnotation($validateValue);
506
507 foreach ($parsedAnnotations['validators'] as $validator) {
508 array_push($validateAnnotations, array(
509 'argumentName' => $parsedAnnotations['argumentName'],
510 'validatorName' => $validator['validatorName'],
511 'validatorOptions' => $validator['validatorOptions']
512 ));
513 }
514 }
515 }
516
517 return $validateAnnotations;
518 }
519
520 }