ldc-cocotte/app/Casts/UtcDatetimeCast.php

59 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Date;
/**
* Enforces UTC normalization when writing and reading datetime/timestamp attributes.
*
* @implements CastsAttributes<\Illuminate\Support\Carbon, \DateTimeInterface | string | int | null>
*/
class UtcDatetimeCast implements CastsAttributes
{
public bool $withoutObjectCaching = true;
/** @param array<string, mixed> $attributes */
#[\Override]
public function get(Model $model, string $key, mixed $value, array $attributes): ?Carbon
{
if ($value === null || $value === '') {
return null;
}
return $this->toUtcCarbon($value);
}
/** @param array<string, mixed> $attributes */
#[\Override]
public function set(Model $model, string $key, mixed $value, array $attributes): ?string
{
if ($value === null || $value === '') {
return null;
}
return $this->toUtcCarbon($value)->format($model->getDateFormat());
}
private function toUtcCarbon(mixed $value): Carbon
{
if ($value instanceof \DateTimeInterface) {
return Date::instance($value)->setTimezone('UTC');
}
if (is_int($value)) {
return Date::createFromTimestamp($value, 'UTC');
}
if (is_string($value)) {
return Date::parse($value, 'UTC')->setTimezone('UTC');
}
throw new \InvalidArgumentException('The given value cannot be cast to a UTC datetime.');
}
}