Set date and date-time formats on Carbon and DateTime string method calls

This commit is contained in:
dualfroz committed 2026-10-11 23:27:48 +02:00
1 parent 185af03608
commit ca00c351b5
3 files changed
+121

No files matched your search

+2
View File
@@ -47,6 +47,7 @@ use Dedoc\Scramble\Support\InferExtensions\AfterResourceCollectionDefinitionCrea
use Dedoc\Scramble\Support\InferExtensions\AfterResponseDefinitionCreatedExtension;
use Dedoc\Scramble\Support\InferExtensions\ArrayMergeReturnTypeExtension;
use Dedoc\Scramble\Support\InferExtensions\ArrStaticMethodReturnTypeExtension;
use Dedoc\Scramble\Support\InferExtensions\DateTimeMethodReturnTypeExtension;
use Dedoc\Scramble\Support\InferExtensions\EloquentBuilderExtension;
use Dedoc\Scramble\Support\InferExtensions\FacadeStaticMethodReturnTypeExtension;
use Dedoc\Scramble\Support\InferExtensions\JsonApiResourceCollectionMethodReturnTypeExtension;
@@ -213,6 +214,7 @@ class ScrambleServiceProvider extends PackageServiceProvider
new PaginateMethodsReturnTypeExtension,
new FacadeStaticMethodReturnTypeExtension,
new ArrStaticMethodReturnTypeExtension,
new DateTimeMethodReturnTypeExtension,
new ValidatorTypeInfer,
new ResourceCollectionTypeInfer,
@@ -0,0 +1,53 @@
<?php
namespace Dedoc\Scramble\Support\InferExtensions;
use DateTimeInterface;
use Dedoc\Scramble\Infer\Extensions\Event\MethodCallEvent;
use Dedoc\Scramble\Infer\Extensions\MethodReturnTypeExtension;
use Dedoc\Scramble\Support\Type\Literal\LiteralStringType;
use Dedoc\Scramble\Support\Type\ObjectType;
use Dedoc\Scramble\Support\Type\StringType;
use Dedoc\Scramble\Support\Type\Type;
class DateTimeMethodReturnTypeExtension implements MethodReturnTypeExtension
{
public function shouldHandle(ObjectType $type): bool
{
return $type->isInstanceOf(DateTimeInterface::class);
}
public function getMethodReturnType(MethodCallEvent $event): ?Type
{
return match ($event->name) {
'toDateString' => $this->makeStringType('date'),
'toDateTimeString', 'toIso8601String' => $this->makeStringType('date-time'),
'format' => $this->makeStringType($this->getFormatMethodSchemaFormat($event->getArg('format', 0))),
default => null,
};
}
private function getFormatMethodSchemaFormat(Type $format): ?string
{
if (! $format instanceof LiteralStringType) {
return null;
}
return match ($format->value) {
'Y-m-d' => 'date',
'Y-m-d H:i:s' => 'date-time',
default => null,
};
}
private function makeStringType(?string $format): StringType
{
$type = new StringType;
if ($format) {
$type->setAttribute('format', $format);
}
return $type;
}
}