Skip to content

Commit 2acc9f2

Browse files
committed
Fallback dates
1 parent 4cb7a0e commit 2acc9f2

1 file changed

Lines changed: 60 additions & 1 deletion

File tree

src/Migration/Destinations/Appwrite.php

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use Appwrite\Services\Users;
1515
use Override;
1616
use Utopia\Database\Database as UtopiaDatabase;
17+
use Utopia\Database\DateTime;
1718
use Utopia\Database\Document as UtopiaDocument;
1819
use Utopia\Database\Exception as DatabaseException;
1920
use Utopia\Database\Exception\Authorization as AuthorizationException;
@@ -942,10 +943,37 @@ protected function createRow(Row $resource, bool $isLast): bool
942943
return false;
943944
}
944945

946+
$data = $resource->getData();
947+
948+
$hasCreatedAt = !empty($data['$createdAt']);
949+
$hasUpdatedAt = !empty($data['$updatedAt']);
950+
951+
if (! $hasCreatedAt) {
952+
$createdAt = $resource->getCreatedAt();
953+
if (empty($createdAt)) {
954+
$createdAt = $data['created_at'] ?? $data['createdAt'] ?? null;
955+
}
956+
957+
$data['$createdAt'] = $this->normalizeDateTime($createdAt);
958+
}
959+
960+
if (! $hasUpdatedAt) {
961+
$updatedAt = $resource->getUpdatedAt();
962+
if (empty($updatedAt)) {
963+
$updatedAt = $data['updated_at'] ?? $data['updatedAt'] ?? null;
964+
}
965+
966+
if (empty($updatedAt)) {
967+
$data['$updatedAt'] = (string) $data['$createdAt'];
968+
} else {
969+
$data['$updatedAt'] = $this->normalizeDateTime($updatedAt, $data['$createdAt']);
970+
}
971+
}
972+
945973
$this->rowBuffer[] = new UtopiaDocument(\array_merge([
946974
'$id' => $resource->getId(),
947975
'$permissions' => $resource->getPermissions(),
948-
], $resource->getData()));
976+
], $data));
949977

950978
if ($isLast) {
951979
try {
@@ -1001,6 +1029,37 @@ protected function createRow(Row $resource, bool $isLast): bool
10011029
return true;
10021030
}
10031031

1032+
/**
1033+
* @throws \Exception
1034+
*/
1035+
private function normalizeDateTime(mixed $value, mixed $fallback = null): string
1036+
{
1037+
$resolved = $this->stringifyDateValue($value)
1038+
?? $this->stringifyDateValue($fallback);
1039+
1040+
if (empty($resolved)) {
1041+
return DateTime::format(new \DateTime());
1042+
}
1043+
1044+
if (\is_numeric($resolved) && \strlen($resolved) === 10 && (int) $resolved > 0) { // Unix timestamp
1045+
$resolved = '@' . $resolved;
1046+
}
1047+
1048+
return DateTime::format(new \DateTime($resolved));
1049+
}
1050+
1051+
private function stringifyDateValue(mixed $value): ?string
1052+
{
1053+
if (\is_string($value)) {
1054+
return $value;
1055+
}
1056+
if (\is_int($value) || \is_float($value)) {
1057+
return (string) $value;
1058+
}
1059+
1060+
return null;
1061+
}
1062+
10041063
/**
10051064
* @throws AppwriteException
10061065
*/

0 commit comments

Comments
 (0)