Created
November 30, 2022 12:28
-
-
Save Gummibeer/d1234f93d33051dae013d4289c4dbf15 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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