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

@@ -0,0 +1,66 @@
<?php
use Dedoc\Scramble\GeneratorConfig;
use Dedoc\Scramble\OpenApiContext;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\TypeTransformer;
use Dedoc\Scramble\Support\InferExtensions\DateTimeMethodReturnTypeExtension;
use Dedoc\Scramble\Support\Type\ObjectType;
use Dedoc\Scramble\Tests\Files\SamplePostModel;
use Illuminate\Http\Resources\Json\JsonResource;
it('infers string format of date time method call', function (string $statement, ?string $format) {
$type = getStatementType($statement, [
new DateTimeMethodReturnTypeExtension,
]);
expect($type->toString())->toBe('string')
->and($type->getAttribute('format'))->toBe($format);
})->with([
['(new \Carbon\Carbon)->toDateString()', 'date'],
['(new \Carbon\Carbon)->toDateTimeString()', 'date-time'],
['(new \Carbon\Carbon)->toIso8601String()', 'date-time'],
["(new \Carbon\Carbon)->format('Y-m-d')", 'date'],
["(new \Carbon\Carbon)->format('Y-m-d H:i:s')", 'date-time'],
["(new \Carbon\Carbon)->format('d.m.Y')", null],
['(new \Carbon\CarbonImmutable)->toDateString()', 'date'],
['(new \Illuminate\Support\Carbon)->toDateTimeString()', 'date-time'],
["(new \DateTime)->format('Y-m-d')", 'date'],
["(new \DateTimeImmutable)->format('Y-m-d H:i:s')", 'date-time'],
]);
it('documents format of date time method calls in json resource', function () {
$context = new OpenApiContext(new OpenApi('3.1.0'), new GeneratorConfig);
$transformer = app()->make(TypeTransformer::class, ['context' => $context]);
$transformer->transform(new ObjectType(DateTimeMethodReturnTypeExtensionTest_Resource::class));
expect($context->openApi->components->getSchema(DateTimeMethodReturnTypeExtensionTest_Resource::class)->toArray()['properties'])->toBe([
'date' => ['type' => 'string', 'format' => 'date'],
'date_time' => ['type' => 'string', 'format' => 'date-time'],
'iso' => ['type' => 'string', 'format' => 'date-time'],
'formatted_date' => ['type' => 'string', 'format' => 'date'],
'formatted_date_time' => ['type' => 'string', 'format' => 'date-time'],
'formatted_custom' => ['type' => 'string'],
'nullable_date' => ['type' => ['string', 'null'], 'format' => 'date'],
]);
});
/**
* @property SamplePostModel $resource
*/
class DateTimeMethodReturnTypeExtensionTest_Resource extends JsonResource
{
public function toArray($request)
{
return [
'date' => $this->created_at->toDateString(),
'date_time' => $this->created_at->toDateTimeString(),
'iso' => $this->created_at->toIso8601String(),
'formatted_date' => $this->created_at->format('Y-m-d'),
'formatted_date_time' => $this->created_at->format('Y-m-d H:i:s'),
'formatted_custom' => $this->created_at->format('d.m.Y'),
'nullable_date' => $this->approved_at?->toDateString(),
];
}
}