From 363320a514c108f6f9c127c773dd53a5efd6d1b0 Mon Sep 17 00:00:00 2001 From: DimanKuskov Date: Thu, 12 Mar 2020 13:50:30 +0300 Subject: [PATCH] Fixed wrong datetime assignment (#52) Co-authored-by: Dimannn --- src/Mapper/DtoMapper.php | 21 +++++++++++++++++ src/Mapper/NotADateTimeValue.php | 39 ++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 src/Mapper/NotADateTimeValue.php diff --git a/src/Mapper/DtoMapper.php b/src/Mapper/DtoMapper.php index 8d8f698..dd48d61 100644 --- a/src/Mapper/DtoMapper.php +++ b/src/Mapper/DtoMapper.php @@ -7,6 +7,7 @@ use ArrayAccess; use ArrayObject; use BadMethodCallException; +use DateTime; use OnMoon\OpenApiServerBundle\CodeGenerator\Factory\OperationDefinitionFactory; use OnMoon\OpenApiServerBundle\CodeGenerator\Naming\NamingStrategy; use OnMoon\OpenApiServerBundle\Exception\CannotMapToDto; @@ -55,6 +56,7 @@ public function __construct(NamingStrategy $namingStrategy) * @throws UnexpectedScalarValue * @throws ReflectionException * @throws StringsException + * @throws NotADateTimeValue */ public function map($from, string $toDTO, ?callable $propertyMapper = null) { @@ -146,6 +148,17 @@ public function map($from, string $toDTO, ?callable $propertyMapper = null) /** @psalm-suppress MixedAssignment */ $value[] = $this->map($item, $fullClass, $nextMapper); } + } elseif ($shortClassName === 'DateTime') { + /** @var mixed $item */ + foreach ($rawValue as $item) { + if ($item instanceof DateTime) { + $value[] = $item; + } elseif (is_string($item)) { + $value[] = new \Safe\DateTime($item); + } else { + throw new NotADateTimeValue($property->getName(), $toDTO, $item); + } + } } else { /** @var mixed $item */ foreach ($rawValue as $item) { @@ -156,6 +169,14 @@ public function map($from, string $toDTO, ?callable $propertyMapper = null) } } } + } elseif ($typeName === 'DateTime') { + if ($rawValue instanceof DateTime) { + $value = $rawValue; + } elseif (is_string($rawValue)) { + $value = new \Safe\DateTime($rawValue); + } else { + throw new NotADateTimeValue($property->getName(), $toDTO, $rawValue); + } } elseif ($type->isBuiltin()) { /** phpcs:disable Generic.PHP.ForbiddenFunctions.Found */ settype($rawValue, $typeName); diff --git a/src/Mapper/NotADateTimeValue.php b/src/Mapper/NotADateTimeValue.php new file mode 100644 index 0000000..bcfdc35 --- /dev/null +++ b/src/Mapper/NotADateTimeValue.php @@ -0,0 +1,39 @@ +value = $value; + parent::__construct($message); + } + + /** + * @return mixed + */ + public function getValue() + { + return $this->value; + } +}