diff --git a/src/Centreon/Infrastructure/Serializer/Exception/SerializerException.php b/src/Centreon/Infrastructure/Serializer/Exception/SerializerException.php new file mode 100644 index 00000000000..2e05afdcc69 --- /dev/null +++ b/src/Centreon/Infrastructure/Serializer/Exception/SerializerException.php @@ -0,0 +1,50 @@ + $type + * @throws SerializerException + * @throws \ReflectionException + * @throws \Throwable */ public function construct( DeserializationVisitorInterface $visitor, @@ -45,6 +50,31 @@ public function construct( DeserializationContext $context ): ?object { $className = $metadata->name; - return new $className(); + if (!class_exists($className)) { + throw SerializerException::classNotFound($className); + } + $reflection = new \ReflectionClass($className); + $constructor = $reflection->getConstructor(); + if ($constructor !== null && $constructor->getNumberOfParameters() > 0) { + $parameters = $constructor->getParameters(); + $constructorParameters = []; + foreach ($parameters as $parameter) { + if (array_key_exists($parameter->getName(), $data)) { + $constructorParameters[$parameter->getPosition()] = $data[$parameter->getName()]; + } elseif ($parameter->isOptional() === true) { + $constructorParameters[$parameter->getPosition()] = $parameter->getDefaultValue(); + } + } + try { + return $reflection->newInstanceArgs($constructorParameters); + } catch (\Throwable $ex) { + if ($ex instanceof \ArgumentCountError) { + throw SerializerException::notEnoughConstructorArguments($className, $ex); + } + throw $ex; + } + } else { + return new $className(); + } } }