diff options
Diffstat (limited to 'vendor/ipl/orm/src/Behavior/MillisecondTimestamp.php')
-rw-r--r-- | vendor/ipl/orm/src/Behavior/MillisecondTimestamp.php | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/vendor/ipl/orm/src/Behavior/MillisecondTimestamp.php b/vendor/ipl/orm/src/Behavior/MillisecondTimestamp.php new file mode 100644 index 0000000..65d8033 --- /dev/null +++ b/vendor/ipl/orm/src/Behavior/MillisecondTimestamp.php @@ -0,0 +1,41 @@ +<?php + +namespace ipl\Orm\Behavior; + +use DateTime; +use DateTimeZone; +use Exception; +use ipl\Orm\Contract\PropertyBehavior; +use ipl\Orm\Exception\ValueConversionException; + +class MillisecondTimestamp extends PropertyBehavior +{ + public function fromDb($value, $key, $context) + { + if ($value === null) { + return null; + } + + $datetime = DateTime::createFromFormat('U.u', sprintf('%F', $value / 1000.0)); + $datetime->setTimezone(new DateTimeZone(date_default_timezone_get())); + + return $datetime; + } + + public function toDb($value, $key, $context) + { + if (is_numeric($value)) { + return (int) ($value * 1000.0); + } + + if (! $value instanceof DateTime) { + try { + $value = new DateTime($value); + } catch (Exception $err) { + throw new ValueConversionException(sprintf('Invalid date time format provided: %s', $value)); + } + } + + return (int) ($value->format('U.u') * 1000.0); + } +} |