[BUGFIX] Fix several typos in php comments
[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\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 an appropriate validator for a given subject
25 * @internal only to be used within Extbase, not part of TYPO3 Core API.
26 */
27 class ValidatorResolver implements \TYPO3\CMS\Core\SingletonInterface
28 {
29 /**
30 * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
31 */
32 protected $objectManager;
33
34 /**
35 * @var \TYPO3\CMS\Extbase\Reflection\ReflectionService
36 */
37 protected $reflectionService;
38
39 /**
40 * @var array
41 */
42 protected $baseValidatorConjunctions = [];
43
44 /**
45 * @param \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager
46 */
47 public function injectObjectManager(\TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager)
48 {
49 $this->objectManager = $objectManager;
50 }
51
52 /**
53 * @param \TYPO3\CMS\Extbase\Reflection\ReflectionService $reflectionService
54 */
55 public function injectReflectionService(\TYPO3\CMS\Extbase\Reflection\ReflectionService $reflectionService)
56 {
57 $this->reflectionService = $reflectionService;
58 }
59
60 /**
61 * Get a validator for a given data type. Returns a validator implementing
62 * the \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface or NULL if no validator
63 * could be resolved.
64 *
65 * @param string $validatorType Either one of the built-in data types or fully qualified validator class name
66 * @param array $validatorOptions Options to be passed to the validator
67 * @return \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface Validator or NULL if none found.
68 */
69 public function createValidator($validatorType, array $validatorOptions = [])
70 {
71 // todo: ValidatorResolver should not take care of creating validator instances.
72 // todo: Instead, a factory should be used.
73 try {
74 /**
75 * @todo remove throwing Exceptions in resolveValidatorObjectName
76 */
77 $validatorObjectName = ValidatorClassNameResolver::resolve($validatorType);
78
79 $validator = $this->objectManager->get($validatorObjectName, $validatorOptions);
80
81 // Move this check into ClassSchema
82 if (!($validator instanceof \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface)) {
83 throw new Exception\NoSuchValidatorException('The validator "' . $validatorObjectName . '" does not implement TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface!', 1300694875);
84 }
85
86 return $validator;
87 } catch (NoSuchValidatorException $e) {
88 GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__)->debug($e->getMessage());
89 return null;
90 }
91 }
92
93 /**
94 * Resolves and returns the base validator conjunction for the given data type.
95 *
96 * If no validator could be resolved (which usually means that no validation is necessary),
97 * NULL is returned.
98 *
99 * @param string $targetClassName The data type to search a validator for. Usually the fully qualified object name
100 * @return ConjunctionValidator The validator conjunction or NULL
101 */
102 public function getBaseValidatorConjunction($targetClassName)
103 {
104 if (!array_key_exists($targetClassName, $this->baseValidatorConjunctions)) {
105 $this->buildBaseValidatorConjunction($targetClassName, $targetClassName);
106 }
107
108 return $this->baseValidatorConjunctions[$targetClassName];
109 }
110
111 /**
112 * Builds a base validator conjunction for the given data type.
113 *
114 * The base validation rules are those which were declared directly in a class (typically
115 * a model) through some validate annotations on properties.
116 *
117 * If a property holds a class for which a base validator exists, that property will be
118 * checked as well, regardless of a validate annotation
119 *
120 * Additionally, if a custom validator was defined for the class in question, it will be added
121 * to the end of the conjunction. A custom validator is found if it follows the naming convention
122 * "Replace '\Model\' by '\Validator\' and append 'Validator'".
123 *
124 * Example: $targetClassName is TYPO3\Foo\Domain\Model\Quux, then the validator will be found if it has the
125 * name TYPO3\Foo\Domain\Validator\QuuxValidator
126 *
127 * @param string $indexKey The key to use as index in $this->baseValidatorConjunctions; calculated from target class name and validation groups
128 * @param string $targetClassName The data type to build the validation conjunction for. Needs to be the fully qualified class name.
129 * @param array $validationGroups The validation groups to build the validator for
130 * @throws \TYPO3\CMS\Extbase\Validation\Exception\NoSuchValidatorException
131 * @throws \InvalidArgumentException
132 */
133 protected function buildBaseValidatorConjunction($indexKey, $targetClassName, array $validationGroups = [])
134 {
135 $conjunctionValidator = new ConjunctionValidator();
136 $this->baseValidatorConjunctions[$indexKey] = $conjunctionValidator;
137
138 // note: the simpleType check reduces lookups to the class loader
139 if (!TypeHandlingUtility::isSimpleType($targetClassName) && class_exists($targetClassName)) {
140 $classSchema = $this->reflectionService->getClassSchema($targetClassName);
141
142 // Model based validator
143 /** @var \TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator $objectValidator */
144 $objectValidator = $this->objectManager->get(\TYPO3\CMS\Extbase\Validation\Validator\GenericObjectValidator::class, []);
145 foreach ($classSchema->getProperties() as $property) {
146 if ($property->getType() === null) {
147 // todo: The type is only necessary here for further analyzations whether it's a simple type or
148 // todo: a collection. If this is evaluated in the ClassSchema, this whole code part is not needed
149 // todo: any longer and can be removed.
150 throw new \InvalidArgumentException(sprintf('There is no @var annotation for property "%s" in class "%s".', $property->getName(), $targetClassName), 1363778104);
151 }
152
153 $propertyTargetClassName = $property->getType();
154 // note: the outer simpleType check reduces lookups to the class loader
155
156 // todo: whether the property holds a simple type or not and whether it holds a collection is known in
157 // todo: in the ClassSchema. The information could be made available and not evaluated here again.
158 if (!TypeHandlingUtility::isSimpleType($propertyTargetClassName)) {
159 if (TypeHandlingUtility::isCollectionType($propertyTargetClassName)) {
160 $collectionValidator = $this->createValidator(
161 \TYPO3\CMS\Extbase\Validation\Validator\CollectionValidator::class,
162 [
163 'elementType' => $property->getElementType(),
164 'validationGroups' => $validationGroups
165 ]
166 );
167 $objectValidator->addPropertyValidator($property->getName(), $collectionValidator);
168 } elseif (class_exists($propertyTargetClassName) && !TypeHandlingUtility::isCoreType($propertyTargetClassName) && $this->objectManager->isRegistered($propertyTargetClassName) && $this->objectManager->getScope($propertyTargetClassName) === \TYPO3\CMS\Extbase\Object\Container\Container::SCOPE_PROTOTYPE) {
169 /*
170 * class_exists($propertyTargetClassName) checks, if the type of the property is an object
171 * instead of a simple type. Like DateTime or another model.
172 *
173 * !TypeHandlingUtility::isCoreType($propertyTargetClassName) checks if the type of the property
174 * is not a core type, which are Enums and File objects for example.
175 * todo: check why these types should not be validated
176 *
177 * $this->objectManager->isRegistered($propertyTargetClassName) checks if the type is a class
178 * which can be loaded.
179 * todo: this could be dropped as it's the same check as the first one.
180 *
181 * $this->objectManager->getScope($propertyTargetClassName) ===
182 * \TYPO3\CMS\Extbase\Object\Container\Container::SCOPE_PROTOTYPE checks, if the type of the
183 * property is a prototype, meaning that it's a class which does not implement the
184 * SingletonInterface
185 * todo: check why Singletons shouldn't be validated.
186 */
187
188 /*
189 * (Alexander Schnitzler) By looking at this code I assume that this is the path for 1:1
190 * relations in models. Still, the question remains why it excludes core types and singletons.
191 * It makes sense on a theoretical level but I don't see a technical issue allowing these as
192 * well.
193 */
194 $validatorForProperty = $this->getBaseValidatorConjunction($propertyTargetClassName);
195 if ($validatorForProperty !== null && $validatorForProperty->count() > 0) {
196 $objectValidator->addPropertyValidator($property->getName(), $validatorForProperty);
197 }
198 }
199 }
200
201 foreach ($property->getValidators() as $validatorDefinition) {
202 // @todo: Respect validationGroups
203
204 // @todo: At this point we already have the class name of the validator, thus there is not need
205 // @todo: calling \TYPO3\CMS\Extbase\Validation\ValidatorResolver::resolveValidatorObjectName inside
206 // @todo: \TYPO3\CMS\Extbase\Validation\ValidatorResolver::createValidator once again. However, to
207 // @todo: keep things simple for now, we still use the method createValidator here. In the future,
208 // @todo: createValidator must only accept FQCN's.
209 $newValidator = $this->createValidator($validatorDefinition['className'], $validatorDefinition['options']);
210 if ($newValidator === null) {
211 throw new Exception\NoSuchValidatorException('Invalid validate annotation in ' . $targetClassName . '::' . $property->getName() . ': Could not resolve class name for validator "' . $validatorDefinition['className'] . '".', 1241098027);
212 }
213 $objectValidator->addPropertyValidator($property->getName(), $newValidator);
214 }
215 }
216
217 if (!empty($objectValidator->getPropertyValidators())) {
218 $conjunctionValidator->addValidator($objectValidator);
219 }
220 }
221 }
222 }