7e0d5a58e27e2667a481dbb45c82413430ff45b6
[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 $validateAnnotation = $validator;
309 $validateAnnotation['argumentName'] = $parsedAnnotations['argumentName'] ?? null;
310 $validateAnnotations[] = $validateAnnotation;
311 }
312 }
313 }
314
315 foreach ($validateAnnotations as $validateAnnotation) {
316 // @todo: Respect validationGroups
317 $newValidator = $this->createValidator($validateAnnotation['validatorName'], $validateAnnotation['validatorOptions']);
318 if ($newValidator === null) {
319 throw new Exception\NoSuchValidatorException('Invalid validate annotation in ' . $targetClassName . '::' . $classPropertyName . ': Could not resolve class name for validator "' . $validateAnnotation->type . '".', 1241098027);
320 }
321 $objectValidator->addPropertyValidator($classPropertyName, $newValidator);
322 }
323 }
324
325 if (!empty($objectValidator->getPropertyValidators())) {
326 $conjunctionValidator->addValidator($objectValidator);
327 }
328 }
329
330 $this->addCustomValidators($targetClassName, $conjunctionValidator);
331 }
332
333 /**
334 * This adds custom validators to the passed $conjunctionValidator.
335 *
336 * A custom validator is found if it follows the naming convention "Replace '\Model\' by '\Validator\' and
337 * append 'Validator'". If found, it will be added to the $conjunctionValidator.
338 *
339 * In addition canValidate() will be called on all implementations of the ObjectValidatorInterface to find
340 * all validators that could validate the target. The one with the highest priority will be added as well.
341 * If multiple validators have the same priority, which one will be added is not deterministic.
342 *
343 * @param string $targetClassName
344 * @param ConjunctionValidator $conjunctionValidator
345 * @return Validator\ObjectValidatorInterface|null
346 */
347 protected function addCustomValidators($targetClassName, ConjunctionValidator &$conjunctionValidator)
348 {
349 // @todo: get rid of ClassNamingUtility usage once we dropped underscored class name support
350 $possibleValidatorClassName = ClassNamingUtility::translateModelNameToValidatorName($targetClassName);
351
352 $customValidator = $this->createValidator($possibleValidatorClassName);
353 if ($customValidator !== null) {
354 $conjunctionValidator->addValidator($customValidator);
355 }
356
357 // @todo: find polytype validator for class
358 }
359
360 /**
361 * Parses the validator options given in @validate annotations.
362 *
363 * @param string $validateValue
364 * @return array
365 */
366 protected function parseValidatorAnnotation($validateValue)
367 {
368 $matches = [];
369 if ($validateValue[0] === '$') {
370 $parts = explode(' ', $validateValue, 2);
371 $validatorConfiguration = ['argumentName' => ltrim($parts[0], '$'), 'validators' => []];
372 preg_match_all(self::PATTERN_MATCH_VALIDATORS, $parts[1], $matches, PREG_SET_ORDER);
373 } else {
374 $validatorConfiguration = ['validators' => []];
375 preg_match_all(self::PATTERN_MATCH_VALIDATORS, $validateValue, $matches, PREG_SET_ORDER);
376 }
377 foreach ($matches as $match) {
378 $validatorOptions = [];
379 if (isset($match['validatorOptions'])) {
380 $validatorOptions = $this->parseValidatorOptions($match['validatorOptions']);
381 }
382 $validatorConfiguration['validators'][] = ['validatorName' => $match['validatorName'], 'validatorOptions' => $validatorOptions];
383 }
384 return $validatorConfiguration;
385 }
386
387 /**
388 * Parses $rawValidatorOptions not containing quoted option values.
389 * $rawValidatorOptions will be an empty string afterwards (pass by ref!).
390 *
391 * @param string $rawValidatorOptions
392 * @return array An array of optionName/optionValue pairs
393 */
394 protected function parseValidatorOptions($rawValidatorOptions)
395 {
396 $validatorOptions = [];
397 $parsedValidatorOptions = [];
398 preg_match_all(self::PATTERN_MATCH_VALIDATOROPTIONS, $rawValidatorOptions, $validatorOptions, PREG_SET_ORDER);
399 foreach ($validatorOptions as $validatorOption) {
400 $parsedValidatorOptions[trim($validatorOption['optionName'])] = trim($validatorOption['optionValue']);
401 }
402 array_walk($parsedValidatorOptions, [$this, 'unquoteString']);
403 return $parsedValidatorOptions;
404 }
405
406 /**
407 * Removes escapings from a given argument string and trims the outermost
408 * quotes.
409 *
410 * This method is meant as a helper for regular expression results.
411 *
412 * @param string &$quotedValue Value to unquote
413 */
414 protected function unquoteString(&$quotedValue)
415 {
416 switch ($quotedValue[0]) {
417 case '"':
418 $quotedValue = str_replace('\\"', '"', trim($quotedValue, '"'));
419 break;
420 case '\'':
421 $quotedValue = str_replace('\\\'', '\'', trim($quotedValue, '\''));
422 break;
423 }
424 $quotedValue = str_replace('\\\\', '\\', $quotedValue);
425 }
426
427 /**
428 * Returns an object of an appropriate validator for the given class. If no validator is available
429 * FALSE is returned
430 *
431 * @param string $validatorName Either the fully qualified class name of the validator or the short name of a built-in validator
432 *
433 * @throws Exception\NoSuchValidatorException
434 * @return string Name of the validator object
435 */
436 protected function resolveValidatorObjectName($validatorName)
437 {
438 if (strpos($validatorName, ':') !== false) {
439 // Found shorthand validator, either extbase or foreign extension
440 // NotEmpty or Acme.MyPck.Ext:MyValidator
441 list($extensionName, $extensionValidatorName) = explode(':', $validatorName);
442
443 if ($validatorName !== $extensionName && $extensionValidatorName !== '') {
444 // Shorthand custom
445 if (strpos($extensionName, '.') !== false) {
446 $extensionNameParts = explode('.', $extensionName);
447 $extensionName = array_pop($extensionNameParts);
448 $vendorName = implode('\\', $extensionNameParts);
449 $possibleClassName = $vendorName . '\\' . $extensionName . '\\Validation\\Validator\\' . $extensionValidatorName;
450 } else {
451 $possibleClassName = 'Tx_' . $extensionName . '_Validation_Validator_' . $extensionValidatorName;
452 }
453 } else {
454 // Shorthand built in
455 $possibleClassName = 'TYPO3\\CMS\\Extbase\\Validation\\Validator\\' . $this->getValidatorType($validatorName);
456 }
457 } elseif (strpbrk($validatorName, '_\\') === false) {
458 // Shorthand built in
459 $possibleClassName = 'TYPO3\\CMS\\Extbase\\Validation\\Validator\\' . $this->getValidatorType($validatorName);
460 } else {
461 // Full qualified
462 // Tx_MyExt_Validation_Validator_MyValidator or \Acme\Ext\Validation\Validator\FooValidator
463 $possibleClassName = $validatorName;
464 if (!empty($possibleClassName) && $possibleClassName[0] === '\\') {
465 $possibleClassName = substr($possibleClassName, 1);
466 }
467 }
468
469 if (substr($possibleClassName, - strlen('Validator')) !== 'Validator') {
470 $possibleClassName .= 'Validator';
471 }
472
473 if (class_exists($possibleClassName)) {
474 $possibleClassNameInterfaces = class_implements($possibleClassName);
475 if (!in_array(\TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface::class, $possibleClassNameInterfaces)) {
476 // The guessed validatorname is a valid class name, but does not implement the ValidatorInterface
477 throw new NoSuchValidatorException('Validator class ' . $validatorName . ' must implement \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface', 1365776838);
478 }
479 $resolvedValidatorName = $possibleClassName;
480 } else {
481 throw new NoSuchValidatorException('Validator class ' . $validatorName . ' does not exist', 1365799920);
482 }
483
484 return $resolvedValidatorName;
485 }
486
487 /**
488 * Used to map PHP types to validator types.
489 *
490 * @param string $type Data type to unify
491 * @return string unified data type
492 */
493 protected function getValidatorType($type)
494 {
495 switch ($type) {
496 case 'int':
497 $type = 'Integer';
498 break;
499 case 'bool':
500 $type = 'Boolean';
501 break;
502 case 'double':
503 $type = 'Float';
504 break;
505 case 'numeric':
506 $type = 'Number';
507 break;
508 case 'mixed':
509 $type = 'Raw';
510 break;
511 default:
512 $type = ucfirst($type);
513 }
514 return $type;
515 }
516
517 /**
518 * Temporary replacement for $this->reflectionService->getMethodAnnotations()
519 *
520 * @param string $className
521 * @param string $methodName
522 *
523 * @return array
524 */
525 public function getMethodValidateAnnotations($className, $methodName)
526 {
527 $validateAnnotations = [];
528 $methodTagsValues = $this->reflectionService->getMethodTagsValues($className, $methodName);
529 if (isset($methodTagsValues['validate']) && is_array($methodTagsValues['validate'])) {
530 foreach ($methodTagsValues['validate'] as $validateValue) {
531 $parsedAnnotations = $this->parseValidatorAnnotation($validateValue);
532
533 foreach ($parsedAnnotations['validators'] as $validator) {
534 array_push($validateAnnotations, [
535 'argumentName' => $parsedAnnotations['argumentName'],
536 'validatorName' => $validator['validatorName'],
537 'validatorOptions' => $validator['validatorOptions']
538 ]);
539 }
540 }
541 }
542
543 return $validateAnnotations;
544 }
545 }