5 Commits

Author SHA1 Message Date
Sebastian 0f05494cf3 chore(deps): update dependency vite-plugin-static-copy to v4.1.1
Build Test / build (pull_request) Successful in 13s
PHP Unit Tests / test (pull_request) Failing after 15m5s
JS Unit Tests / test (pull_request) Failing after 15m9s
2026-07-05 03:02:25 +00:00
Sebastian 502be95d7d feat: implement event end calculator
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-04 19:02:36 -04:00
Sebastian ef3d19db9a feat: implement now epoch
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-04 19:02:07 -04:00
Sebastian 58a9c4351d refactor: use epoch timestamp
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-04 18:21:10 -04:00
Sebastian fe78426a5d feat: add deserilazation
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-03 21:33:28 -04:00
9 changed files with 559 additions and 27 deletions
@@ -0,0 +1,397 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXF\Chrono\Entity;
use DateTimeImmutable;
use DateTimeInterface;
use KTXF\Utile\Timestamp;
final class EventRangeMetadata {
public static function fromStoreDocument(array $document): array {
$entity = $document['data'] ?? null;
if (!is_array($entity) || !isset($entity['startsOn'])) {
return [];
}
try {
$startsOn = new DateTimeImmutable($entity['startsOn']);
$endsOn = isset($entity['endsOn']) ? new DateTimeImmutable($entity['endsOn']) : null;
} catch (\Exception) {
return [];
}
$rangeStart = $startsOn;
$rangeEnd = $endsOn;
$pattern = $entity['pattern'] ?? null;
if (is_array($pattern)) {
$rangeEnd = self::constructRecurringRangeEnd($startsOn, $endsOn, $pattern);
}
foreach (($entity['mutations'] ?? []) as $mutation) {
if (!is_array($mutation) || ($mutation['mutationExclusion'] ?? false)) {
continue;
}
try {
if (isset($mutation['startsOn'])) {
$mutationStart = new DateTimeImmutable($mutation['startsOn']);
if ($mutationStart < $rangeStart) {
$rangeStart = $mutationStart;
}
}
if ($rangeEnd !== null && isset($mutation['endsOn'])) {
$mutationEnd = new DateTimeImmutable($mutation['endsOn']);
if ($mutationEnd > $rangeEnd) {
$rangeEnd = $mutationEnd;
}
}
} catch (\Exception) {
continue;
}
}
return [
'startsOn' => Timestamp::toEpoch($rangeStart),
'endsOn' => $rangeEnd !== null ? Timestamp::toEpoch($rangeEnd) : null,
];
}
private static function parseRangeDateTime(mixed $value): ?DateTimeImmutable {
if (!is_string($value) || trim($value) === '') {
return null;
}
try {
return new DateTimeImmutable($value);
} catch (\Exception) {
return null;
}
}
private static function parseConclusionBoundary(mixed $value, DateTimeImmutable $reference): ?DateTimeImmutable {
if (!is_string($value) || trim($value) === '') {
return null;
}
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1) {
return DateTimeImmutable::createFromFormat(
'!Y-m-d H:i:s.u',
sprintf('%s 23:59:59.999000', $value),
$reference->getTimezone()
) ?: null;
}
return self::parseRangeDateTime($value);
}
private static function recurringDuration(DateTimeImmutable $startsOn, ?DateTimeImmutable $endsOn): ?\DateInterval {
if ($endsOn === null || $endsOn <= $startsOn) {
return null;
}
return $startsOn->diff($endsOn);
}
private static function positiveIntegerList(mixed $value): array {
if (!is_array($value)) {
return [];
}
$list = [];
foreach ($value as $entry) {
if (!is_numeric($entry)) {
continue;
}
$integer = (int)$entry;
if ($integer > 0) {
$list[$integer] = $integer;
}
}
ksort($list);
return array_values($list);
}
private static function signedIntegerList(mixed $value): array {
if (!is_array($value)) {
return [];
}
$list = [];
foreach ($value as $entry) {
if (!is_numeric($entry)) {
continue;
}
$integer = (int)$entry;
if ($integer !== 0) {
$list[$integer] = $integer;
}
}
ksort($list);
return array_values($list);
}
private static function recurrenceWeekdays(array $pattern, DateTimeImmutable $startsOn): array {
$weekdays = self::positiveIntegerList($pattern['onDayOfWeek'] ?? null);
if ($weekdays === []) {
$weekdays = [(int)$startsOn->format('N')];
}
return array_values(array_filter($weekdays, static fn(int $value): bool => $value >= 1 && $value <= 7));
}
private static function recurrenceMonths(array $pattern, DateTimeImmutable $startsOn): array {
$months = self::positiveIntegerList($pattern['onMonthOfYear'] ?? null);
if ($months === []) {
$months = [(int)$startsOn->format('n')];
}
return array_values(array_filter($months, static fn(int $value): bool => $value >= 1 && $value <= 12));
}
private static function monthCandidatesAbsolute(DateTimeImmutable $periodStart, array $days, DateTimeImmutable $startsOn): array {
$days = $days !== [] ? $days : [(int)$startsOn->format('j')];
$lastDay = (int)$periodStart->format('t');
$candidates = [];
foreach ($days as $day) {
if ($day < 1 || $day > $lastDay) {
continue;
}
$candidates[] = $periodStart->setDate(
(int)$periodStart->format('Y'),
(int)$periodStart->format('n'),
$day
);
}
usort($candidates, static fn(DateTimeImmutable $left, DateTimeImmutable $right): int => $left <=> $right);
return $candidates;
}
private static function nthWeekdayOfMonth(DateTimeImmutable $periodStart, int $weekday, int $position): ?DateTimeImmutable {
if ($weekday < 1 || $weekday > 7 || $position === 0) {
return null;
}
$year = (int)$periodStart->format('Y');
$month = (int)$periodStart->format('n');
$lastDay = (int)$periodStart->format('t');
if ($position > 0) {
$firstDayWeekday = (int)$periodStart->format('N');
$offset = ($weekday - $firstDayWeekday + 7) % 7;
$day = 1 + $offset + (($position - 1) * 7);
if ($day > $lastDay) {
return null;
}
return $periodStart->setDate($year, $month, $day);
}
$lastDayDate = $periodStart->setDate($year, $month, $lastDay);
$lastWeekday = (int)$lastDayDate->format('N');
$offset = ($lastWeekday - $weekday + 7) % 7;
$day = $lastDay - $offset;
$steps = abs($position) - 1;
$day -= $steps * 7;
if ($day < 1) {
return null;
}
return $periodStart->setDate($year, $month, $day);
}
private static function monthCandidatesRelative(DateTimeImmutable $periodStart, array $weekdays, array $positions, DateTimeImmutable $startsOn): array {
$weekdays = $weekdays !== [] ? $weekdays : [(int)$startsOn->format('N')];
$positions = $positions !== [] ? $positions : [self::positionInMonth($startsOn)];
$candidates = [];
foreach ($positions as $position) {
foreach ($weekdays as $weekday) {
$candidate = self::nthWeekdayOfMonth($periodStart, $weekday, $position);
if ($candidate !== null) {
$candidates[$candidate->format(DateTimeInterface::ATOM)] = $candidate;
}
}
}
$candidates = array_values($candidates);
usort($candidates, static fn(DateTimeImmutable $left, DateTimeImmutable $right): int => $left <=> $right);
return $candidates;
}
private static function positionInMonth(DateTimeImmutable $date): int {
$day = (int)$date->format('j');
$lastDay = (int)$date->format('t');
return ($day + 7 > $lastDay) ? -1 : (int)ceil($day / 7);
}
private static function recurringCandidateStarts(DateTimeImmutable $startsOn, array $pattern, ?DateTimeImmutable $concludes, ?int $iterations): array {
$precision = is_string($pattern['precision'] ?? null) ? strtolower((string)$pattern['precision']) : '';
$interval = max(1, (int)($pattern['interval'] ?? 1));
$occurrences = [];
$limit = $iterations ?? 512;
$append = function (DateTimeImmutable $candidate) use (&$occurrences, $startsOn, $concludes, $iterations): bool {
if ($candidate < $startsOn) {
return true;
}
if ($concludes !== null && $candidate > $concludes) {
return false;
}
$occurrences[] = $candidate;
return $iterations === null || count($occurrences) < $iterations;
};
switch ($precision) {
case 'secondly':
case 'minutely':
case 'hourly':
case 'daily':
$step = 0;
$weekdays = $precision === 'daily' && !empty($pattern['onDayOfWeek'])
? self::recurrenceWeekdays($pattern, $startsOn)
: [];
while (count($occurrences) < $limit) {
$candidate = match ($precision) {
'secondly' => $startsOn->modify(sprintf('+%d seconds', $step * $interval)),
'minutely' => $startsOn->modify(sprintf('+%d minutes', $step * $interval)),
'hourly' => $startsOn->modify(sprintf('+%d hours', $step * $interval)),
default => $startsOn->modify(sprintf('+%d days', $step * $interval)),
};
if ($candidate === false) {
break;
}
if ($precision === 'daily' && $weekdays !== [] && !in_array((int)$candidate->format('N'), $weekdays, true)) {
$step++;
if ($concludes !== null && $candidate > $concludes) {
break;
}
continue;
}
if (!$append($candidate)) {
break;
}
$step++;
}
break;
case 'weekly':
$weekdays = self::recurrenceWeekdays($pattern, $startsOn);
$weekStart = $startsOn->modify(sprintf('-%d days', ((int)$startsOn->format('N')) - 1));
if ($weekStart === false) {
break;
}
for ($week = 0; count($occurrences) < $limit; $week++) {
$periodStart = $weekStart->modify(sprintf('+%d days', $week * $interval * 7));
if ($periodStart === false) {
break;
}
foreach ($weekdays as $weekday) {
$candidate = $periodStart->modify(sprintf('+%d days', $weekday - 1));
if ($candidate === false) {
continue;
}
if (!$append($candidate)) {
break 2;
}
}
if ($concludes !== null && $periodStart > $concludes) {
break;
}
}
break;
case 'monthly':
$isRelative = strtolower((string)($pattern['pattern'] ?? 'absolute')) === 'relative';
$days = self::positiveIntegerList($pattern['onDayOfMonth'] ?? null);
$weekdays = self::recurrenceWeekdays($pattern, $startsOn);
$positions = self::signedIntegerList($pattern['onPosition'] ?? null);
$monthAnchor = $startsOn->setDate((int)$startsOn->format('Y'), (int)$startsOn->format('n'), 1);
for ($month = 0; count($occurrences) < $limit; $month++) {
$periodStart = $monthAnchor->modify(sprintf('+%d months', $month * $interval));
if ($periodStart === false) {
break;
}
$candidates = $isRelative
? self::monthCandidatesRelative($periodStart, $weekdays, $positions, $startsOn)
: self::monthCandidatesAbsolute($periodStart, $days, $startsOn);
foreach ($candidates as $candidate) {
if (!$append($candidate)) {
break 2;
}
}
if ($concludes !== null && $periodStart > $concludes) {
break;
}
}
break;
case 'yearly':
$isRelative = strtolower((string)($pattern['pattern'] ?? 'absolute')) === 'relative';
$months = self::recurrenceMonths($pattern, $startsOn);
$days = self::positiveIntegerList($pattern['onDayOfMonth'] ?? null);
$weekdays = self::recurrenceWeekdays($pattern, $startsOn);
$positions = self::signedIntegerList($pattern['onPosition'] ?? null);
$yearAnchor = $startsOn->setDate((int)$startsOn->format('Y'), 1, 1);
for ($year = 0; count($occurrences) < $limit; $year++) {
$periodYear = $yearAnchor->modify(sprintf('+%d years', $year * $interval));
if ($periodYear === false) {
break;
}
$candidates = [];
foreach ($months as $month) {
$periodStart = $periodYear->setDate((int)$periodYear->format('Y'), $month, 1);
foreach (
$isRelative
? self::monthCandidatesRelative($periodStart, $weekdays, $positions, $startsOn)
: self::monthCandidatesAbsolute($periodStart, $days, $startsOn)
as $candidate
) {
$candidates[$candidate->format(DateTimeInterface::ATOM)] = $candidate;
}
}
$candidates = array_values($candidates);
usort($candidates, static fn(DateTimeImmutable $left, DateTimeImmutable $right): int => $left <=> $right);
foreach ($candidates as $candidate) {
if (!$append($candidate)) {
break 2;
}
}
if ($concludes !== null && $periodYear > $concludes) {
break;
}
}
break;
}
return $occurrences;
}
private static function constructRecurringRangeEnd(DateTimeImmutable $startsOn, ?DateTimeImmutable $endsOn, array $pattern): ?DateTimeImmutable {
$iterations = isset($pattern['iterations']) && is_numeric($pattern['iterations']) && (int)$pattern['iterations'] > 0
? (int)$pattern['iterations']
: null;
$concludes = self::parseConclusionBoundary($pattern['concludes'] ?? null, $startsOn);
if ($iterations === null && $concludes === null) {
return null;
}
$occurrences = self::recurringCandidateStarts($startsOn, $pattern, $concludes, $iterations);
$lastStart = $occurrences !== [] ? end($occurrences) : $startsOn;
if (!$lastStart instanceof DateTimeImmutable) {
return null;
}
$duration = self::recurringDuration($startsOn, $endsOn);
return $duration !== null ? $lastStart->add($duration) : $lastStart;
}
}
@@ -15,6 +15,7 @@ use KTXF\Resource\Identifier\CollectionIdentifierInterface;
use KTXF\Resource\Identifier\EntityIdentifierInterface;
use KTXF\Resource\Identifier\ResourceIdentifier;
use KTXF\Resource\Identifier\ServiceIdentifier;
use KTXF\Utile\Timestamp;
/**
* Abstract Node Base Class
@@ -119,18 +120,14 @@ abstract class NodeBaseAbstract implements NodeBaseInterface {
* @inheritDoc
*/
public function created(): DateTimeImmutable|null {
return isset($this->data[static::PROPERTY_CREATED])
? new DateTimeImmutable($this->data[static::PROPERTY_CREATED])
: null;
return Timestamp::toDateTime($this->data[static::PROPERTY_CREATED] ?? null);
}
/**
* @inheritDoc
*/
public function modified(): DateTimeImmutable|null {
return isset($this->data[static::PROPERTY_MODIFIED])
? new DateTimeImmutable($this->data[static::PROPERTY_MODIFIED])
: null;
return Timestamp::toDateTime($this->data[static::PROPERTY_MODIFIED] ?? null);
}
/**
@@ -9,6 +9,8 @@ declare(strict_types=1);
namespace KTXF\Resource\Provider\Node;
use KTXF\Utile\Timestamp;
/**
* Abstract Node Mutable Class
*
@@ -56,19 +58,21 @@ abstract class NodeMutableAbstract extends NodeBaseAbstract implements NodeMutab
}
if (isset($data[static::PROPERTY_CREATED])) {
if (!is_string($data[static::PROPERTY_CREATED])) {
throw new \InvalidArgumentException("Created date must be a string in ISO 8601 format");
$created = Timestamp::normalize($data[static::PROPERTY_CREATED]);
if ($created === null) {
throw new \InvalidArgumentException("Created date must be a valid epoch millisecond or ISO 8601 date");
}
$this->data[static::PROPERTY_CREATED] = $data[static::PROPERTY_CREATED];
$this->data[static::PROPERTY_CREATED] = $created;
} else {
$this->data[static::PROPERTY_CREATED] = null;
}
if (isset($data[static::PROPERTY_MODIFIED])) {
if (!is_string($data[static::PROPERTY_MODIFIED])) {
throw new \InvalidArgumentException("Modified date must be a string in ISO 8601 format");
$modified = Timestamp::normalize($data[static::PROPERTY_MODIFIED]);
if ($modified === null) {
throw new \InvalidArgumentException("Modified date must be a valid epoch millisecond or ISO 8601 date");
}
$this->data[static::PROPERTY_MODIFIED] = $data[static::PROPERTY_MODIFIED];
$this->data[static::PROPERTY_MODIFIED] = $modified;
} else {
$this->data[static::PROPERTY_MODIFIED] = null;
}
+3 -1
View File
@@ -9,7 +9,9 @@ declare(strict_types=1);
namespace KTXF\Resource\Range;
interface IRange {
use KTXF\Json\JsonDeserializable;
interface IRange extends JsonDeserializable {
/**
* Gets the type of this range
+4 -6
View File
@@ -9,32 +9,30 @@ declare(strict_types=1);
namespace KTXF\Resource\Range;
use DateTimeInterface;
interface IRangeDate extends IRange {
/**
*
* @since 1.0.0
*/
public function getStart(): DateTimeInterface;
public function getStart(): int;
/**
*
* @since 1.0.0
*/
public function setStart(DateTimeInterface $value): void;
public function setStart(int $value): void;
/**
*
* @since 1.0.0
*/
public function getEnd(): DateTimeInterface;
public function getEnd(): int;
/**
*
* @since 1.0.0
*/
public function setEnd(DateTimeInterface $value): void;
public function setEnd(int $value): void;
}
+4
View File
@@ -11,6 +11,10 @@ namespace KTXF\Resource\Range;
class Range implements IRange {
public function jsonDeserialize(array|string $data): static {
return $this;
}
/**
* Returns the type of the range
*
+28 -8
View File
@@ -9,13 +9,33 @@ declare(strict_types=1);
namespace KTXF\Resource\Range;
use DateTime;
use DateTimeInterface;
use KTXF\Utile\Timestamp;
class RangeDate extends Range implements IRangeDate {
protected DateTimeInterface $start;
protected DateTimeInterface $end;
protected int $start;
protected int $end;
public function jsonDeserialize(array|string $data): static {
if (is_string($data)) {
$data = json_decode($data, true, flags: JSON_THROW_ON_ERROR);
}
if (isset($data['start'])) {
$start = Timestamp::normalize($data['start']);
if ($start !== null) {
$this->setStart($start);
}
}
if (isset($data['end'])) {
$end = Timestamp::normalize($data['end']);
if ($end !== null) {
$this->setEnd($end);
}
}
return $this;
}
/**
* Returns the type of the range
@@ -31,7 +51,7 @@ class RangeDate extends Range implements IRangeDate {
*
* @since 1.0.0
*/
public function getStart(): DateTimeInterface {
public function getStart(): int {
return $this->start;
}
@@ -40,7 +60,7 @@ class RangeDate extends Range implements IRangeDate {
*
* @since 1.0.0
*/
public function setStart(DateTimeInterface $value): void {
public function setStart(int $value): void {
$this->start = $value;
}
@@ -49,7 +69,7 @@ class RangeDate extends Range implements IRangeDate {
*
* @since 1.0.0
*/
public function getEnd(): DateTimeInterface {
public function getEnd(): int {
return $this->end;
}
@@ -58,7 +78,7 @@ class RangeDate extends Range implements IRangeDate {
*
* @since 1.0.0
*/
public function setEnd(DateTimeInterface $value): void {
public function setEnd(int $value): void {
$this->end = $value;
}
+18
View File
@@ -15,6 +15,24 @@ class RangeTally extends Range implements IRangeTally {
protected string|int $position = 0;
protected int $tally = 32;
public function jsonDeserialize(array|string $data): static {
if (is_string($data)) {
$data = json_decode($data, true, flags: JSON_THROW_ON_ERROR);
}
if (isset($data['anchor'])) {
$this->setAnchor(RangeAnchorType::from($data['anchor']));
}
if (isset($data['position'])) {
$this->setPosition($data['position']);
}
if (isset($data['tally'])) {
$this->setTally($data['tally']);
}
return $this;
}
/**
* Returns the type of the range
*
+92
View File
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXF\Utile;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
final class Timestamp {
public static function now(): int {
return self::toEpoch(new DateTimeImmutable('now'));
}
public static function normalize(mixed $value): ?int {
if ($value instanceof DateTimeInterface) {
return self::toEpoch($value);
}
if (is_int($value)) {
return $value;
}
if (is_float($value)) {
return (int)$value;
}
if (is_string($value)) {
if (is_numeric($value)) {
return (int)$value;
}
try {
return self::toEpoch(new DateTimeImmutable($value));
} catch (\Exception) {
return null;
}
}
return null;
}
public static function toEpoch(DateTimeInterface $moment): int {
$utcMoment = DateTimeImmutable::createFromInterface($moment)
->setTimezone(new DateTimeZone('UTC'));
return ((int)$utcMoment->format('U') * 1000) + (int)$utcMoment->format('v');
}
public static function toDateTime(mixed $value): ?DateTimeImmutable {
if ($value instanceof DateTimeImmutable) {
return $value;
}
if ($value instanceof DateTimeInterface) {
return DateTimeImmutable::createFromInterface($value);
}
if (is_int($value) || is_float($value) || (is_string($value) && is_numeric($value))) {
$milliseconds = (int)$value;
$seconds = intdiv($milliseconds, 1000);
$microseconds = ($milliseconds % 1000) * 1000;
return DateTimeImmutable::createFromFormat(
'U u',
sprintf('%d %06d', $seconds, $microseconds),
new DateTimeZone('UTC')
) ?: null;
}
if (is_string($value) && trim($value) !== '') {
try {
return new DateTimeImmutable($value);
} catch (\Exception) {
return null;
}
}
return null;
}
public static function toIso8601(int $value): ?string {
$moment = self::toDateTime($value);
return $moment?->format('Y-m-d\TH:i:s.v\Z');
}
}