Skip to content

Commit fa1a93e

Browse files
committed
added and tested duration
1 parent 7070e7d commit fa1a93e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/Formatter/Specialised/JoltHttpOGMTranslator.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use Closure;
1717
use const DATE_ATOM;
18+
use DateInterval;
1819
use DateTimeImmutable;
1920
use function is_array;
2021
use Laudis\Neo4j\Contracts\ConnectionInterface;
@@ -27,6 +28,7 @@
2728
use Laudis\Neo4j\Types\CypherMap;
2829
use Laudis\Neo4j\Types\Date;
2930
use Laudis\Neo4j\Types\DateTime;
31+
use Laudis\Neo4j\Types\Duration;
3032
use Laudis\Neo4j\Types\LocalDateTime;
3133
use Laudis\Neo4j\Types\LocalTime;
3234
use Laudis\Neo4j\Types\Node;
@@ -43,6 +45,8 @@
4345
use stdClass;
4446
use function str_pad;
4547
use const STR_PAD_RIGHT;
48+
use function str_replace;
49+
use function str_starts_with;
4650
use function strtolower;
4751
use UnexpectedValueException;
4852

@@ -359,6 +363,10 @@ private function translateDateTime(string $datetime)
359363
return new DateTime($seconds, $nanoseconds, $offset);
360364
}
361365

366+
if (str_starts_with($datetime, 'P')) {
367+
return $this->durationFromFormat($datetime, $matches);
368+
}
369+
362370
throw new UnexpectedValueException(sprintf('Could not handle date/time "%s"', $datetime));
363371
}
364372

@@ -420,4 +428,23 @@ private function addNanoSecondsToSeconds(int $nanoseconds, int $seconds): array
420428

421429
return [$seconds, $nanoseconds];
422430
}
431+
432+
private function durationFromFormat(string $datetime): Duration
433+
{
434+
$nanoseconds = 0;
435+
// PHP date interval does not understand fractions of a second.
436+
if (preg_match('/\.(?<nanoseconds>\d+)S/u', $datetime, $matches)) {
437+
/** @var array{0: string, nanoseconds: string} $matches */
438+
$nanoseconds = (int) str_pad($matches['nanoseconds'], 9, '0', STR_PAD_RIGHT);
439+
440+
$datetime = str_replace($matches[0], 'S', $datetime);
441+
}
442+
443+
$interval = new DateInterval($datetime);
444+
$months = (int) $interval->format('%y') * 12 + (int) $interval->format('%m');
445+
$days = (int) $interval->format('%d');
446+
$seconds = (int) $interval->format('%h') * 60 * 60 + (int) $interval->format('%i') * 60 + (int) $interval->format('%s');
447+
448+
return new Duration($months, $days, $seconds, $nanoseconds);
449+
}
423450
}

0 commit comments

Comments
 (0)