From c46128ed3eba4867d84a1f243d59550976bed645 Mon Sep 17 00:00:00 2001 From: Hide_D Date: Thu, 26 May 2022 03:23:58 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20DTO=EC=97=90=20DateTimeConveter=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/sammo/DTO/Converter/DateTimeConverter.php | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/sammo/DTO/Converter/DateTimeConverter.php diff --git a/src/sammo/DTO/Converter/DateTimeConverter.php b/src/sammo/DTO/Converter/DateTimeConverter.php new file mode 100644 index 00000000..187782d8 --- /dev/null +++ b/src/sammo/DTO/Converter/DateTimeConverter.php @@ -0,0 +1,46 @@ + 0) { + if(!is_bool($args[0])) { + throw new \Exception('DateTimeConverter constructor argument must be boolean'); + } + $this->useFraction = $args[0]; + } else { + $this->useFraction = false; + } + } + + public function convertFrom(string|array|int|float|bool|null $raw): mixed + { + if ($raw === null && array_search('null', $this->types, true) !== false) { + return null; + } + if (!is_string($raw)){ + throw new \Exception('DateTimeConverter can not convert non-string'); + } + if (array_search('DateTime', $this->types, true) === false) { + return new \DateTime($raw); + } + return new \DateTimeImmutable($raw); + } + + public function convertTo(mixed $data): string|array|int|float|bool|null + { + if ($data === null && array_search('null', $this->types, true) !== false) { + return null; + } + if (!$data instanceof \DateTimeInterface) { + throw new \Exception('DateTimeConverter can not convert non-DateTimeInterface'); + } + return TimeUtil::format($data, $this->useFraction); + } +}