2 namespace TYPO3\CMS\Extbase\Validation
;
5 * This file is part of the TYPO3 CMS project.
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.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
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
;
24 * Validator resolver to automatically find an appropriate validator for a given subject
26 class ValidatorResolver
implements \TYPO3\CMS\Core\SingletonInterface
29 * Match validator names and options
30 * @todo: adjust [a-z0-9_:.\\\\] once Tx_Extbase_Foo syntax is outdated.
34 const PATTERN_MATCH_VALIDATORS
= '/
36 (?P<validatorName>[a-z0-9_:.\\\\]+)
39 (?P<validatorOptions>(?:\s*[a-z0-9]+\s*=\s*(?:
41 |\'(?:\\\\\'|[^\'])*\'
48 * Match validator options (to parse actual options)
51 const PATTERN_MATCH_VALIDATOROPTIONS
= '/
53 (?P<optionName>[a-z0-9]+)
57 |\'(?:\\\\\'|[^\'])*\'
63 * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
65 protected $objectManager;
68 * @var \TYPO3\CMS\Extbase\Reflection\ReflectionService
70 protected $reflectionService;
75 protected $baseValidatorConjunctions = [];
78 * @param \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager
80 public function injectObjectManager(\TYPO3\CMS\Extbase\
Object\ObjectManagerInterface
$objectManager)
82 $this->objectManager
= $objectManager;
86 * @param \TYPO3\CMS\Extbase\Reflection\ReflectionService $reflectionService
88 public function injectReflectionService(\TYPO3\CMS\Extbase\Reflection\ReflectionService
$reflectionService)
90 $this->reflectionService
= $reflectionService;
94 * Get a validator for a given data type. Returns a validator implementing
95 * the \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface or NULL if no validator
98 * @param string $validatorType Either one of the built-in data types or fully qualified validator class name
99 * @param array $validatorOptions Options to be passed to the validator
100 * @return \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface Validator or NULL if none found.
102 public function createValidator($validatorType, array $validatorOptions = [])
106 * @todo remove throwing Exceptions in resolveValidatorObjectName
108 $validatorObjectName = $this->resolveValidatorObjectName($validatorType);
110 $validator = $this->objectManager
->get($validatorObjectName, $validatorOptions);
112 if (!($validator instanceof \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface
)) {
113 throw new Exception\
NoSuchValidatorException('The validator "' . $validatorObjectName . '" does not implement TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface!', 1300694875);
117 } catch (NoSuchValidatorException
$e) {
118 GeneralUtility
::devLog($e->getMessage(), 'extbase', GeneralUtility
::SYSLOG_SEVERITY_INFO
);
124 * Resolves and returns the base validator conjunction for the given data type.
126 * If no validator could be resolved (which usually means that no validation is necessary),
129 * @param string $targetClassName The data type to search a validator for. Usually the fully qualified object name
130 * @return ConjunctionValidator The validator conjunction or NULL
132 public function getBaseValidatorConjunction($targetClassName)
134 if (!array_key_exists($targetClassName, $this->baseValidatorConjunctions
)) {
135 $this->buildBaseValidatorConjunction($targetClassName, $targetClassName);
138 return $this->baseValidatorConjunctions
[$targetClassName];
142 * Detects and registers any validators for arguments:
143 * - by the data type specified in the param annotations
144 * - additional validators specified in the validate annotations of a method
146 * @param string $className
147 * @param string $methodName
148 * @param array $methodParameters Optional pre-compiled array of method parameters
149 * @param array $methodValidateAnnotations Optional pre-compiled array of validate annotations (as array)
150 * @return ConjunctionValidator[] An Array of ValidatorConjunctions for each method parameters.
151 * @throws \TYPO3\CMS\Extbase\Validation\Exception\InvalidValidationConfigurationException
152 * @throws \TYPO3\CMS\Extbase\Validation\Exception\NoSuchValidatorException
153 * @throws \TYPO3\CMS\Extbase\Validation\Exception\InvalidTypeHintException
155 public function buildMethodArgumentsValidatorConjunctions($className, $methodName, array $methodParameters = null
, array $methodValidateAnnotations = null
)
157 /** @var ConjunctionValidator[] $validatorConjunctions */
158 $validatorConjunctions = [];
160 if ($methodParameters === null
) {
161 $methodParameters = $this->reflectionService
->getMethodParameters($className, $methodName);
163 if (empty($methodParameters)) {
164 return $validatorConjunctions;
167 foreach ($methodParameters as $parameterName => $methodParameter) {
168 /** @var ConjunctionValidator $validatorConjunction */
169 $validatorConjunction = $this->createValidator(ConjunctionValidator
::class);
171 if (!array_key_exists('type', $methodParameter)) {
172 throw new Exception\
InvalidTypeHintException('Missing type information, probably no @param annotation for parameter "$' . $parameterName . '" in ' . $className . '->' . $methodName . '()', 1281962564);
175 // @todo: remove check for old underscore model name syntax once it's possible
176 if (strpbrk($methodParameter['type'], '_\\') === false
) {
177 $typeValidator = $this->createValidator($methodParameter['type']);
179 $typeValidator = null
;
182 if ($typeValidator !== null
) {
183 $validatorConjunction->addValidator($typeValidator);
185 $validatorConjunctions[$parameterName] = $validatorConjunction;
188 if ($methodValidateAnnotations === null
) {
189 $validateAnnotations = $this->getMethodValidateAnnotations($className, $methodName);
190 $methodValidateAnnotations = array_map(function ($validateAnnotation) {
192 'type' => $validateAnnotation['validatorName'],
193 'options' => $validateAnnotation['validatorOptions'],
194 'argumentName' => $validateAnnotation['argumentName'],
196 }, $validateAnnotations);
199 foreach ($methodValidateAnnotations as $annotationParameters) {
200 $newValidator = $this->createValidator($annotationParameters['type'], $annotationParameters['options']);
201 if ($newValidator === null
) {
202 throw new Exception\
NoSuchValidatorException('Invalid validate annotation in ' . $className . '->' . $methodName . '(): Could not resolve class name for validator "' . $annotationParameters['type'] . '".', 1239853109);
204 if (isset($validatorConjunctions[$annotationParameters['argumentName']])) {
205 $validatorConjunctions[$annotationParameters['argumentName']]->addValidator($newValidator);
206 } elseif (strpos($annotationParameters['argumentName'], '.') !== false
) {
207 $objectPath = explode('.', $annotationParameters['argumentName']);
208 $argumentName = array_shift($objectPath);
209 $validatorConjunctions[$argumentName]->addValidator($this->buildSubObjectValidator($objectPath, $newValidator));
211 throw new Exception\
InvalidValidationConfigurationException('Invalid validate annotation in ' . $className . '->' . $methodName . '(): Validator specified for argument name "' . $annotationParameters['argumentName'] . '", but this argument does not exist.', 1253172726);
215 return $validatorConjunctions;
219 * Builds a chain of nested object validators by specification of the given
222 * @param array $objectPath The object path
223 * @param \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface $propertyValidator The validator which should be added to the property specified by objectPath
224 * @return \TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator
226 protected function buildSubObjectValidator(array $objectPath, \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface
$propertyValidator)
228 $rootObjectValidator = $this->objectManager
->get(\TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator
::class, []);
229 $parentObjectValidator = $rootObjectValidator;
231 while (count($objectPath) > 1) {
232 $subObjectValidator = $this->objectManager
->get(\TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator
::class, []);
233 $subPropertyName = array_shift($objectPath);
234 $parentObjectValidator->addPropertyValidator($subPropertyName, $subObjectValidator);
235 $parentObjectValidator = $subObjectValidator;
238 $parentObjectValidator->addPropertyValidator(array_shift($objectPath), $propertyValidator);
240 return $rootObjectValidator;
244 * Builds a base validator conjunction for the given data type.
246 * The base validation rules are those which were declared directly in a class (typically
247 * a model) through some validate annotations on properties.
249 * If a property holds a class for which a base validator exists, that property will be
250 * checked as well, regardless of a validate annotation
252 * Additionally, if a custom validator was defined for the class in question, it will be added
253 * to the end of the conjunction. A custom validator is found if it follows the naming convention
254 * "Replace '\Model\' by '\Validator\' and append 'Validator'".
256 * Example: $targetClassName is TYPO3\Foo\Domain\Model\Quux, then the validator will be found if it has the
257 * name TYPO3\Foo\Domain\Validator\QuuxValidator
259 * @param string $indexKey The key to use as index in $this->baseValidatorConjunctions; calculated from target class name and validation groups
260 * @param string $targetClassName The data type to build the validation conjunction for. Needs to be the fully qualified class name.
261 * @param array $validationGroups The validation groups to build the validator for
262 * @throws \TYPO3\CMS\Extbase\Validation\Exception\NoSuchValidatorException
263 * @throws \InvalidArgumentException
265 protected function buildBaseValidatorConjunction($indexKey, $targetClassName, array $validationGroups = [])
267 $conjunctionValidator = new ConjunctionValidator();
268 $this->baseValidatorConjunctions
[$indexKey] = $conjunctionValidator;
270 // note: the simpleType check reduces lookups to the class loader
271 if (!TypeHandlingUtility
::isSimpleType($targetClassName) && class_exists($targetClassName)) {
272 // Model based validator
273 /** @var \TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator $objectValidator */
274 $objectValidator = $this->objectManager
->get(\TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator
::class, []);
275 foreach ($this->reflectionService
->getClassPropertyNames($targetClassName) as $classPropertyName) {
276 $classPropertyTagsValues = $this->reflectionService
->getPropertyTagsValues($targetClassName, $classPropertyName);
278 if (!isset($classPropertyTagsValues['var'])) {
279 throw new \
InvalidArgumentException(sprintf('There is no @var annotation for property "%s" in class "%s".', $classPropertyName, $targetClassName), 1363778104);
282 $parsedType = TypeHandlingUtility
::parseType(trim(implode('', $classPropertyTagsValues['var']), ' \\'));
283 } catch (\TYPO3\CMS\Extbase\Utility\Exception\InvalidTypeException
$exception) {
284 throw new \
InvalidArgumentException(sprintf(' @var annotation of ' . $exception->getMessage(), 'class "' . $targetClassName . '", property "' . $classPropertyName . '"'), 1315564744, $exception);
286 $propertyTargetClassName = $parsedType['type'];
287 // note: the outer simpleType check reduces lookups to the class loader
288 if (!TypeHandlingUtility
::isSimpleType($propertyTargetClassName)) {
289 if (TypeHandlingUtility
::isCollectionType($propertyTargetClassName)) {
290 $collectionValidator = $this->createValidator(\TYPO3\CMS\Extbase\Validation\Validator\CollectionValidator
::class, ['elementType' => $parsedType['elementType'], 'validationGroups' => $validationGroups]);
291 $objectValidator->addPropertyValidator($classPropertyName, $collectionValidator);
292 } elseif (class_exists($propertyTargetClassName) && !TypeHandlingUtility
::isCoreType($propertyTargetClassName) && $this->objectManager
->isRegistered($propertyTargetClassName) && $this->objectManager
->getScope($propertyTargetClassName) === \TYPO3\CMS\Extbase\
Object\Container\Container
::SCOPE_PROTOTYPE
) {
293 $validatorForProperty = $this->getBaseValidatorConjunction($propertyTargetClassName);
294 if ($validatorForProperty !== null
&& $validatorForProperty->count() > 0) {
295 $objectValidator->addPropertyValidator($classPropertyName, $validatorForProperty);
300 $validateAnnotations = [];
301 // @todo: Resolve annotations via reflectionService once its available
302 if (isset($classPropertyTagsValues['validate']) && is_array($classPropertyTagsValues['validate'])) {
303 foreach ($classPropertyTagsValues['validate'] as $validateValue) {
304 $parsedAnnotations = $this->parseValidatorAnnotation($validateValue);
306 foreach ($parsedAnnotations['validators'] as $validator) {
307 array_push($validateAnnotations, [
308 'argumentName' => $parsedAnnotations['argumentName'],
309 'validatorName' => $validator['validatorName'],
310 'validatorOptions' => $validator['validatorOptions']
316 foreach ($validateAnnotations as $validateAnnotation) {
317 // @todo: Respect validationGroups
318 $newValidator = $this->createValidator($validateAnnotation['validatorName'], $validateAnnotation['validatorOptions']);
319 if ($newValidator === null
) {
320 throw new Exception\
NoSuchValidatorException('Invalid validate annotation in ' . $targetClassName . '::' . $classPropertyName . ': Could not resolve class name for validator "' . $validateAnnotation->type
. '".', 1241098027);
322 $objectValidator->addPropertyValidator($classPropertyName, $newValidator);
326 if (!empty($objectValidator->getPropertyValidators())) {
327 $conjunctionValidator->addValidator($objectValidator);
331 $this->addCustomValidators($targetClassName, $conjunctionValidator);
335 * This adds custom validators to the passed $conjunctionValidator.
337 * A custom validator is found if it follows the naming convention "Replace '\Model\' by '\Validator\' and
338 * append 'Validator'". If found, it will be added to the $conjunctionValidator.
340 * In addition canValidate() will be called on all implementations of the ObjectValidatorInterface to find
341 * all validators that could validate the target. The one with the highest priority will be added as well.
342 * If multiple validators have the same priority, which one will be added is not deterministic.
344 * @param string $targetClassName
345 * @param ConjunctionValidator $conjunctionValidator
346 * @return null|Validator\ObjectValidatorInterface
348 protected function addCustomValidators($targetClassName, ConjunctionValidator
&$conjunctionValidator)
350 // @todo: get rid of ClassNamingUtility usage once we dropped underscored class name support
351 $possibleValidatorClassName = ClassNamingUtility
::translateModelNameToValidatorName($targetClassName);
353 $customValidator = $this->createValidator($possibleValidatorClassName);
354 if ($customValidator !== null
) {
355 $conjunctionValidator->addValidator($customValidator);
358 // @todo: find polytype validator for class
362 * Parses the validator options given in @validate annotations.
364 * @param string $validateValue
367 protected function parseValidatorAnnotation($validateValue)
370 if ($validateValue[0] === '$') {
371 $parts = explode(' ', $validateValue, 2);
372 $validatorConfiguration = ['argumentName' => ltrim($parts[0], '$'), 'validators' => []];
373 preg_match_all(self
::PATTERN_MATCH_VALIDATORS
, $parts[1], $matches, PREG_SET_ORDER
);
375 $validatorConfiguration = ['validators' => []];
376 preg_match_all(self
::PATTERN_MATCH_VALIDATORS
, $validateValue, $matches, PREG_SET_ORDER
);
378 foreach ($matches as $match) {
379 $validatorOptions = [];
380 if (isset($match['validatorOptions'])) {
381 $validatorOptions = $this->parseValidatorOptions($match['validatorOptions']);
383 $validatorConfiguration['validators'][] = ['validatorName' => $match['validatorName'], 'validatorOptions' => $validatorOptions];
385 return $validatorConfiguration;
389 * Parses $rawValidatorOptions not containing quoted option values.
390 * $rawValidatorOptions will be an empty string afterwards (pass by ref!).
392 * @param string $rawValidatorOptions
393 * @return array An array of optionName/optionValue pairs
395 protected function parseValidatorOptions($rawValidatorOptions)
397 $validatorOptions = [];
398 $parsedValidatorOptions = [];
399 preg_match_all(self
::PATTERN_MATCH_VALIDATOROPTIONS
, $rawValidatorOptions, $validatorOptions, PREG_SET_ORDER
);
400 foreach ($validatorOptions as $validatorOption) {
401 $parsedValidatorOptions[trim($validatorOption['optionName'])] = trim($validatorOption['optionValue']);
403 array_walk($parsedValidatorOptions, [$this, 'unquoteString']);
404 return $parsedValidatorOptions;
408 * Removes escapings from a given argument string and trims the outermost
411 * This method is meant as a helper for regular expression results.
413 * @param string &$quotedValue Value to unquote
415 protected function unquoteString(&$quotedValue)
417 switch ($quotedValue[0]) {
419 $quotedValue = str_replace('\\"', '"', trim($quotedValue, '"'));
422 $quotedValue = str_replace('\\\'', '\'', trim($quotedValue, '\''));
425 $quotedValue = str_replace('\\\\', '\\', $quotedValue);
429 * Returns an object of an appropriate validator for the given class. If no validator is available
432 * @param string $validatorName Either the fully qualified class name of the validator or the short name of a built-in validator
434 * @throws Exception\NoSuchValidatorException
435 * @return string Name of the validator object
437 protected function resolveValidatorObjectName($validatorName)
439 if (strpos($validatorName, ':') !== false ||
strpbrk($validatorName, '_\\') === false
) {
440 // Found shorthand validator, either extbase or foreign extension
441 // NotEmpty or Acme.MyPck.Ext:MyValidator
442 list($extensionName, $extensionValidatorName) = explode(':', $validatorName);
444 if ($validatorName !== $extensionName && $extensionValidatorName !== '') {
446 if (strpos($extensionName, '.') !== false
) {
447 $extensionNameParts = explode('.', $extensionName);
448 $extensionName = array_pop($extensionNameParts);
449 $vendorName = implode('\\', $extensionNameParts);
450 $possibleClassName = $vendorName . '\\' . $extensionName . '\\Validation\\Validator\\' . $extensionValidatorName;
452 $possibleClassName = 'Tx_' . $extensionName . '_Validation_Validator_' . $extensionValidatorName;
455 // Shorthand built in
456 $possibleClassName = 'TYPO3\\CMS\\Extbase\\Validation\\Validator\\' . $this->getValidatorType($validatorName);
460 // Tx_MyExt_Validation_Validator_MyValidator or \Acme\Ext\Validation\Validator\FooValidator
461 $possibleClassName = $validatorName;
462 if (!empty($possibleClassName) && $possibleClassName[0] === '\\') {
463 $possibleClassName = substr($possibleClassName, 1);
467 if (substr($possibleClassName, - strlen('Validator')) !== 'Validator') {
468 $possibleClassName .= 'Validator';
471 if (class_exists($possibleClassName)) {
472 $possibleClassNameInterfaces = class_implements($possibleClassName);
473 if (!in_array(\TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface
::class, $possibleClassNameInterfaces)) {
474 // The guessed validatorname is a valid class name, but does not implement the ValidatorInterface
475 throw new NoSuchValidatorException('Validator class ' . $validatorName . ' must implement \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface', 1365776838);
477 $resolvedValidatorName = $possibleClassName;
479 throw new NoSuchValidatorException('Validator class ' . $validatorName . ' does not exist', 1365799920);
482 return $resolvedValidatorName;
486 * Used to map PHP types to validator types.
488 * @param string $type Data type to unify
489 * @return string unified data type
491 protected function getValidatorType($type)
510 $type = ucfirst($type);
516 * Temporary replacement for $this->reflectionService->getMethodAnnotations()
518 * @param string $className
519 * @param string $methodName
523 public function getMethodValidateAnnotations($className, $methodName)
525 $validateAnnotations = [];
526 $methodTagsValues = $this->reflectionService
->getMethodTagsValues($className, $methodName);
527 if (isset($methodTagsValues['validate']) && is_array($methodTagsValues['validate'])) {
528 foreach ($methodTagsValues['validate'] as $validateValue) {
529 $parsedAnnotations = $this->parseValidatorAnnotation($validateValue);
531 foreach ($parsedAnnotations['validators'] as $validator) {
532 array_push($validateAnnotations, [
533 'argumentName' => $parsedAnnotations['argumentName'],
534 'validatorName' => $validator['validatorName'],
535 'validatorOptions' => $validator['validatorOptions']
541 return $validateAnnotations;