| Total Complexity | 58 |
| Total Lines | 300 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Complex classes like ApieObjectAccessNormalizer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ApieObjectAccessNormalizer, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 30 | class ApieObjectAccessNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface |
||
| 31 | { |
||
| 32 | use SerializerAwareTrait; |
||
| 33 | |||
| 34 | /** |
||
| 35 | * @var ObjectAccessInterface |
||
| 36 | */ |
||
| 37 | private $objectAccess; |
||
| 38 | |||
| 39 | /** |
||
| 40 | * @var NameConverterInterface|AdvancedNameConverterInterface |
||
| 41 | */ |
||
| 42 | private $nameConverter; |
||
| 43 | |||
| 44 | /** |
||
| 45 | * @var ClassMetadataFactoryInterface|null |
||
| 46 | */ |
||
| 47 | private $classMetadataFactory; |
||
| 48 | |||
| 49 | public function __construct( |
||
| 50 | ObjectAccessInterface $objectAccess = null, |
||
| 51 | NameConverterInterface $nameConverter = null, |
||
| 52 | ClassMetadataFactoryInterface $classMetadataFactory = null |
||
| 53 | ) { |
||
| 54 | $this->objectAccess = $objectAccess ?? new ObjectAccess(); |
||
| 55 | $this->nameConverter = $nameConverter ?? new NullNameConverter(); |
||
| 56 | $this->classMetadataFactory = $classMetadataFactory; |
||
| 57 | } |
||
| 58 | |||
| 59 | /** |
||
| 60 | * {@inheritDoc} |
||
| 61 | */ |
||
| 62 | public function denormalize($data, $type, $format = null, array $context = []) |
||
| 63 | { |
||
| 64 | if ($data instanceof stdClass) { |
||
| 65 | $data = json_decode(json_encode($data), true); |
||
| 66 | } |
||
| 67 | |||
| 68 | // initialize context. |
||
| 69 | $context = $this->sanitizeContext($context); |
||
| 70 | if (empty($context['object_to_populate'])) { |
||
| 71 | $object = $this->instantiate($data, $type, $context['object_access'], $format, $context); |
||
| 72 | } else { |
||
| 73 | $object = $context['object_to_populate']; |
||
| 74 | } |
||
| 75 | /** @var ObjectAccessInterface $objectAccess */ |
||
| 76 | $objectAccess = $context['object_access']; |
||
| 77 | if ($this->classMetadataFactory && isset($context['groups'])) { |
||
| 78 | $objectAccess = $this->filterObjectAccess($objectAccess, $type, $context['groups']); |
||
| 79 | } |
||
| 80 | $reflClass = new ReflectionClass($object); |
||
| 81 | $setterFields = $objectAccess->getSetterFields($reflClass); |
||
| 82 | $errors = new ErrorBag($context['key_prefix']); |
||
| 83 | // iterate over all fields that can be set and try to call them. |
||
| 84 | foreach ($setterFields as $denormalizedFieldName) { |
||
| 85 | try { |
||
| 86 | $fieldName = $this->nameConverter->normalize($denormalizedFieldName, $type, $format, $context); |
||
|
|
|||
| 87 | } catch (Throwable $throwable) { |
||
| 88 | // this means the actual field name can not be normalized, so is this a validation error or an internal error? |
||
| 89 | $errors->addThrowable($denormalizedFieldName, $throwable); |
||
| 90 | continue; |
||
| 91 | } |
||
| 92 | // actual field does not exist in the $data, so we do not need to call it. |
||
| 93 | if (!array_key_exists($fieldName, $data)) { |
||
| 94 | continue; |
||
| 95 | } |
||
| 96 | $succeeded = false; |
||
| 97 | $foundErrors = []; |
||
| 98 | // try all setters and see if we can call it. |
||
| 99 | foreach ($objectAccess->getSetterTypes($reflClass, $denormalizedFieldName) as $getterType) { |
||
| 100 | try { |
||
| 101 | $result = $this->denormalizeType($data, $denormalizedFieldName, $fieldName, $getterType, $format, $context); |
||
| 102 | $objectAccess->setValue($object, $denormalizedFieldName, $result); |
||
| 103 | $succeeded = true; |
||
| 104 | } catch (Throwable $throwable) { |
||
| 105 | $foundErrors[] = $throwable; |
||
| 106 | } |
||
| 107 | } |
||
| 108 | if (!$succeeded) { |
||
| 109 | if ($foundErrors) { |
||
| 110 | $errors->addThrowable($denormalizedFieldName, reset($foundErrors)); |
||
| 111 | } else { |
||
| 112 | // if no typehints exist we end up here. |
||
| 113 | try { |
||
| 114 | $objectAccess->setValue($object, $denormalizedFieldName, $data[$fieldName]); |
||
| 115 | } catch (Throwable $throwable) { |
||
| 116 | $errors->addThrowable($denormalizedFieldName, $throwable); |
||
| 117 | } |
||
| 118 | } |
||
| 119 | } |
||
| 120 | } |
||
| 121 | if ($errors->hasErrors()) { |
||
| 122 | throw new ValidationException($errors); |
||
| 123 | } |
||
| 124 | return $object; |
||
| 125 | } |
||
| 126 | |||
| 127 | /** |
||
| 128 | * Try to convert a field value to the wanted Type. |
||
| 129 | * |
||
| 130 | * @internal |
||
| 131 | * |
||
| 132 | * @param array $data |
||
| 133 | * @param string $denormalizedFieldName |
||
| 134 | * @param string $fieldName |
||
| 135 | * @param Type $type |
||
| 136 | * @param string|null $format |
||
| 137 | * @param array $context |
||
| 138 | * @return array|bool|float|int|string|null |
||
| 139 | */ |
||
| 140 | public function denormalizeType(array $data, string $denormalizedFieldName, string $fieldName, Type $type, ?string $format = null, array $context = []) |
||
| 141 | { |
||
| 142 | if (null === ($data[$fieldName] ?? null) && $type->isNullable()) { |
||
| 143 | return null; |
||
| 144 | } |
||
| 145 | switch ($type->getBuiltinType()) { |
||
| 146 | case Type::BUILTIN_TYPE_INT: |
||
| 147 | return Utils::toInt($data[$fieldName]); |
||
| 148 | case Type::BUILTIN_TYPE_FLOAT: |
||
| 149 | return Utils::toFloat($data[$fieldName]); |
||
| 150 | case Type::BUILTIN_TYPE_STRING: |
||
| 151 | return Utils::toString($data[$fieldName]); |
||
| 152 | case Type::BUILTIN_TYPE_BOOL: |
||
| 153 | return Utils::toBool($data[$fieldName]); |
||
| 154 | case Type::BUILTIN_TYPE_OBJECT: |
||
| 155 | $newContext = $context; |
||
| 156 | $newContext['key_prefix'] = $context['key_prefix'] ? ($context['key_prefix'] . '.' . $denormalizedFieldName) : $denormalizedFieldName; |
||
| 157 | return $this->serializer->denormalize( |
||
| 158 | $data[$fieldName], |
||
| 159 | $type->getClassName() ?? 'stdClass', |
||
| 160 | $format, |
||
| 161 | $newContext |
||
| 162 | ); |
||
| 163 | case Type::BUILTIN_TYPE_ARRAY: |
||
| 164 | $subType = $type->getCollectionValueType(); |
||
| 165 | if ($subType && $subType->getClassName()) { |
||
| 166 | $newContext = $context; |
||
| 167 | $newContext['key_prefix'] = $context['key_prefix'] ? ($context['key_prefix'] . '.' . $denormalizedFieldName) : $denormalizedFieldName; |
||
| 168 | return $this->serializer->denormalize( |
||
| 169 | $data[$fieldName], |
||
| 170 | $subType->getClassName() . '[]', |
||
| 171 | $format, |
||
| 172 | $newContext |
||
| 173 | ); |
||
| 174 | } |
||
| 175 | return (array) $data[$fieldName]; |
||
| 176 | default: |
||
| 177 | throw new CouldNotConvertException('int, float, string, bool, object, array', $type->getBuiltinType()); |
||
| 178 | } |
||
| 179 | } |
||
| 180 | |||
| 181 | /** |
||
| 182 | * Try to get create a new instance of this class from the input $data we retrieve. |
||
| 183 | * |
||
| 184 | * @param array $data |
||
| 185 | * @param string $type |
||
| 186 | * @param ObjectAccessInterface $objectAccess |
||
| 187 | * @param string|null $format |
||
| 188 | * @param array $context |
||
| 189 | * @return object |
||
| 190 | */ |
||
| 191 | private function instantiate(array $data, string $type, ObjectAccessInterface $objectAccess, ?string $format = null, array $context = []) |
||
| 192 | { |
||
| 193 | $reflectionClass = new ReflectionClass($type); |
||
| 194 | $argumentTypes = $objectAccess->getConstructorArguments($reflectionClass); |
||
| 195 | $errors = new ErrorBag($context['key_prefix']); |
||
| 196 | $parsedArguments = []; |
||
| 197 | foreach ($argumentTypes as $denormalizedFieldName => $argumentType) { |
||
| 198 | try { |
||
| 199 | $fieldName = $this->nameConverter->normalize($denormalizedFieldName, $type, $format, $context); |
||
| 200 | if (!array_key_exists($fieldName, $data)) { |
||
| 201 | $constructor = $reflectionClass->getConstructor(); |
||
| 202 | foreach ($constructor->getParameters() as $parameter) { |
||
| 203 | if ($parameter->name === $denormalizedFieldName && $parameter->isDefaultValueAvailable()) { |
||
| 204 | $parsedArguments[] = $parameter->getDefaultValue(); |
||
| 205 | continue(2); |
||
| 206 | } |
||
| 207 | } |
||
| 208 | throw new MissingConstructorArgumentsException($fieldName . ' is required'); |
||
| 209 | } |
||
| 210 | if ($argumentType) { |
||
| 211 | $parsedArguments[] = $this->denormalizeType($data, $denormalizedFieldName, $fieldName, $argumentType, $format, $context); |
||
| 212 | } else { |
||
| 213 | $parsedArguments[] = $data[$fieldName]; |
||
| 214 | |||
| 215 | } |
||
| 216 | } catch (Throwable $throwable) { |
||
| 217 | $errors->addThrowable($denormalizedFieldName, $throwable); |
||
| 218 | } |
||
| 219 | } |
||
| 220 | if ($errors->hasErrors()) { |
||
| 221 | throw new ValidationException($errors); |
||
| 222 | } |
||
| 223 | return $objectAccess->instantiate($reflectionClass, $parsedArguments); |
||
| 224 | } |
||
| 225 | |||
| 226 | /** |
||
| 227 | * {@inheritDoc} |
||
| 228 | */ |
||
| 229 | public function supportsDenormalization($data, $type, $format = null) |
||
| 230 | { |
||
| 231 | return (is_array($data) || $data instanceof stdClass) && class_exists($type); |
||
| 232 | } |
||
| 233 | |||
| 234 | /** |
||
| 235 | * {@inheritDoc} |
||
| 236 | */ |
||
| 237 | public function normalize($object, $format = null, array $context = []) |
||
| 238 | { |
||
| 239 | $context = $this->sanitizeContext($context); |
||
| 240 | /** @var ObjectAccessInterface $objectAccess */ |
||
| 241 | $objectAccess = $context['object_access']; |
||
| 242 | $reflectionClass = new ReflectionClass($object); |
||
| 243 | if ($this->classMetadataFactory && isset($context['groups'])) { |
||
| 244 | $objectAccess = $this->filterObjectAccess($objectAccess, $reflectionClass->name, $context['groups']); |
||
| 245 | } |
||
| 246 | $result = []; |
||
| 247 | foreach ($objectAccess->getGetterFields($reflectionClass) as $denormalizedFieldName) { |
||
| 248 | $fieldName = $this->nameConverter->normalize($denormalizedFieldName, $reflectionClass->name, $format, $context); |
||
| 249 | $result[$fieldName] = $this->toPrimitive($objectAccess->getValue($object, $denormalizedFieldName), $fieldName, $format, $context); |
||
| 250 | } |
||
| 251 | return $result; |
||
| 252 | } |
||
| 253 | |||
| 254 | /** |
||
| 255 | * Adds FilteredObjectAccess decorator around the Object Access by reading the class metadata needed for the serializer. |
||
| 256 | */ |
||
| 257 | private function filterObjectAccess(ObjectAccessInterface $objectAccess, string $className, array $groups): ObjectAccessInterface |
||
| 269 | } |
||
| 270 | |||
| 271 | /** |
||
| 272 | * Try to convert any object or array to a native php type by calling the serializer again. |
||
| 273 | * |
||
| 274 | * @param $input |
||
| 275 | * @param string $fieldName |
||
| 276 | * @param string|null $format |
||
| 277 | * @param array $context |
||
| 278 | * @return array |
||
| 279 | */ |
||
| 280 | private function toPrimitive($input, string $fieldName, ?string $format = null, array $context = []) |
||
| 299 | } |
||
| 300 | |||
| 301 | /** |
||
| 302 | * {@inheritDoc} |
||
| 303 | */ |
||
| 304 | public function supportsNormalization($data, $format = null) |
||
| 307 | } |
||
| 308 | |||
| 309 | /** |
||
| 310 | * Adds default context array values if they are missing. |
||
| 311 | * |
||
| 312 | * @param array $context |
||
| 313 | * @return array |
||
| 314 | */ |
||
| 315 | private function sanitizeContext(array $context): array |
||
| 332 |
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.