Skip to content

Instantly share code, notes, and snippets.

@Gummibeer
Created November 30, 2022 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gummibeer/d1234f93d33051dae013d4289c4dbf15 to your computer and use it in GitHub Desktop.
Save Gummibeer/d1234f93d33051dae013d4289c4dbf15 to your computer and use it in GitHub Desktop.
<?php
namespace Hospitable\Avalara\Casts;
use Carbon\CarbonInterface;
use DateTimeZone;
use Spatie\LaravelData\Casts\DateTimeInterfaceCast;
use Spatie\LaravelData\Casts\Uncastable;
use Spatie\LaravelData\Exceptions\CannotCastDate;
use Spatie\LaravelData\Support\DataProperty;
class CarbonInterfaceCast extends DateTimeInterfaceCast
{
public function cast(DataProperty $property, mixed $value, array $context): CarbonInterface|Uncastable
{
$type = $this->type ?? $property->type->findAcceptedTypeForBaseType(CarbonInterface::class);
if ($type === null) {
return Uncastable::create();
}
/** @var CarbonInterface|null $datetime */
$datetime = rescue(fn () => $type::parse($value), report: false);
if (! $datetime) {
throw CannotCastDate::create(['*'], $type, $value);
}
if ($this->setTimeZone) {
return $datetime->setTimezone(new DateTimeZone($this->setTimeZone));
}
return $datetime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment