DateTimeType.php 1004 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. namespace PhpDevCommunity\PaperORM\Types;
  3. use DateTime;
  4. use DateTimeInterface;
  5. use LogicException;
  6. final class DateTimeType extends Type
  7. {
  8. public function convertToDatabase($value): ?string
  9. {
  10. if ($value === null) {
  11. return null;
  12. }
  13. if ($value instanceof DateTimeInterface) {
  14. return $value->format($this->getSchema()->getDateTimeFormatString());
  15. }
  16. throw new LogicException('Could not convert PHP value "' . $value . '" to ' . self::class);
  17. }
  18. public function convertToPHP($value): ?DateTimeInterface
  19. {
  20. if ($value === null || $value instanceof DateTimeInterface) {
  21. return $value;
  22. }
  23. $date = DateTime::createFromFormat($this->getSchema()->getDateTimeFormatString(), $value);
  24. if (!$date instanceof DateTimeInterface) {
  25. throw new LogicException('Could not convert database value "' . $value . '" to ' . self::class);
  26. }
  27. return $date;
  28. }
  29. }