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