Debian Codegraph @

vendor/ipl/orm/src/Behavior/MillisecondTimestamp.php

raw
1 <?php
2
3 namespace ipl\Orm\Behavior;
4
5 use DateTime;
6 use DateTimeZone;
7 use Exception;
8 use ipl\Orm\Contract\PropertyBehavior;
9 use ipl\Orm\Exception\ValueConversionException;
10
11 class MillisecondTimestamp extends PropertyBehavior
12 {
13 public function fromDb($value, $key, $context)
14 {
15 if ($value === null) {
16 return null;
17 }
18
19 $datetime = DateTime::createFromFormat('U.u', sprintf('%F', $value / 1000.0));
20 $datetime->setTimezone(new DateTimeZone(date_default_timezone_get()));
21
22 return $datetime;
23 }
24
25 public function toDb($value, $key, $context)
26 {
27 if (is_numeric($value)) {
28 return (int) ($value * 1000.0);
29 }
30
31 if (! $value instanceof DateTime) {
32 try {
33 $value = new DateTime($value);
34 } catch (Exception $err) {
35 throw new ValueConversionException(sprintf('Invalid date time format provided: %s', $value));
36 }
37 }
38
39 return (int) ($value->format('U.u') * 1000.0);
40 }
41 }