Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ Added new attributes to support the new composition based syntax.

* Support for unserializable constraints (closures) via runtime resolution.

* Added optional `time` argument to `#[Format]` to normalize the time-of-day of a
parsed date. Accepts a `Time` enum case (`StartOfDay`, `Midday`, `EndOfDay`) or any
valid `H:i:s` string; invalid strings are rejected at metadata warm-up. Non-breaking:
defaults to `null`, preserving the previous behavior.

## 2.x -> 3.0

* Variables being coerced no longer validate constraints from type properties, unless
Expand Down
36 changes: 36 additions & 0 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,42 @@ class AdvancedFilterDto extends AbstractDto
}
```

### Time normalization with `#[Format]`

`\DateTimeImmutable::createFromFormat()` does **not** zero out missing time
components — a date-only format inherits the server's current time
(e.g. `2005-04-12 14:37:22` instead of a clean date). The optional `time`
argument sets the time-of-day deterministically after a successful parse.
It defaults to `null`, which leaves the parsed time untouched, so existing
code is unaffected.

Pass a `Time` enum case for the common presets, or any valid `H:i:s` string.
Invalid time strings are rejected at metadata warm-up, not at request time.

```php
use DualMedia\DtoRequestBundle\Dto\AbstractDto;
use DualMedia\DtoRequestBundle\Dto\Attribute\Format;
use DualMedia\DtoRequestBundle\Dto\Enum\Time;

class DateRangeDto extends AbstractDto
{
#[Format('Y-m-d', time: Time::StartOfDay)] // -> 00:00:00
public \DateTimeImmutable|null $from = null;

#[Format('Y-m-d', time: Time::EndOfDay)] // -> 23:59:59
public \DateTimeImmutable|null $to = null;

#[Format('Y-m-d', time: Time::Midday)] // -> 12:00:00
public \DateTimeImmutable|null $on = null;

#[Format('Y-m-d', time: '06:30:00')] // -> 06:30:00 (custom H:i:s)
public \DateTimeImmutable|null $at = null;

#[Format('Y-m-d')] // -> unchanged (legacy behavior)
public \DateTimeImmutable|null $raw = null;
}
```

## Nested DTOs

```php
Expand Down
10 changes: 9 additions & 1 deletion src/Coercer/DateTimeCoercer.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ static function (mixed $val) use ($format): mixed {
if (null !== $format) {
$result = \DateTimeImmutable::createFromFormat($format->format, $val);

return false !== $result ? $result : $val;
if (false === $result) {
return $val;
}

if (null !== $format->time) {
$result = $result->modify($format->time);
}

return $result;
}

try {
Expand Down
9 changes: 7 additions & 2 deletions src/Dto/Attribute/Format.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,22 @@

namespace DualMedia\DtoRequestBundle\Dto\Attribute;

use DualMedia\DtoRequestBundle\Dto\Enum\Time;

/**
* DateTime format specifier for date parsing.
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
readonly class Format
{
/**
* @param non-empty-string $format
* @param non-empty-string $format
* @param Time|string|null $time optional time-of-day (`H:i:s`) applied after a successful parse;
* `null` leaves the parsed time untouched
*/
public function __construct(
public string $format
public string $format,
public Time|string|null $time = null
) {
}
}
19 changes: 19 additions & 0 deletions src/Dto/Enum/Time.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace DualMedia\DtoRequestBundle\Dto\Enum;

/**
* Convenience presets for the optional time normalization of #[Format].
*
* The backed value is an `H:i:s` time-of-day applied to a parsed date. Any
* other valid `H:i:s` string may be passed to #[Format] directly instead of
* one of these cases.
*/
enum Time: string
{
case StartOfDay = '00:00:00';
case Midday = '12:00:00';
case EndOfDay = '23:59:59';
}
19 changes: 18 additions & 1 deletion src/Metadata/Model/Format.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,26 @@
{
/**
* @param non-empty-string $format
* @param string|null $time normalized `H:i:s` time-of-day, or `null` to leave the parsed time untouched
*
* @throws \InvalidArgumentException when `$time` is not a valid `H:i:s` value
*/
public function __construct(
public string $format
public string $format,
public string|null $time = null
) {
if (null !== $time) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

raczej w miejscu tworzenia modelu (przed)

$parsed = \DateTimeImmutable::createFromFormat('!H:i:s', $time);
$errors = \DateTimeImmutable::getLastErrors();

if (false === $parsed
|| (false !== $errors && ($errors['warning_count'] > 0 || $errors['error_count'] > 0))
) {
throw new \InvalidArgumentException(sprintf(
'Invalid time "%s" passed to #[Format], expected an "H:i:s" time-of-day.',
$time
));
}
}
}
}
6 changes: 5 additions & 1 deletion src/Reflection/MetaReflector.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use DualMedia\DtoRequestBundle\Dto\Attribute\WithErrorPath as WithErrorPathAttribute;
use DualMedia\DtoRequestBundle\Dto\Attribute\WithLabelProcessor as WithLabelProcessorAttribute;
use DualMedia\DtoRequestBundle\Dto\Attribute\WithObjectProvider as WithObjectProviderAttribute;
use DualMedia\DtoRequestBundle\Dto\Enum\Time;
use DualMedia\DtoRequestBundle\Metadata\Model\Action;
use DualMedia\DtoRequestBundle\Metadata\Model\AllowedEnum;
use DualMedia\DtoRequestBundle\Metadata\Model\AsDoctrineReference;
Expand Down Expand Up @@ -47,7 +48,10 @@ public function meta(
foreach ($attributes as $attribute) {
$item = match (true) {
$attribute instanceof FindByAttribute => new FindBy(!$attribute instanceof FindOneByAttribute),
$attribute instanceof FormatAttribute => new Format($attribute->format),
$attribute instanceof FormatAttribute => new Format(
$attribute->format,
$attribute->time instanceof Time ? $attribute->time->value : $attribute->time
),
$attribute instanceof FromKeyAttribute => new FromKey(),
$attribute instanceof LimitAttribute => new Limit($attribute->count),
$attribute instanceof OffsetAttribute => new Offset($attribute->count),
Expand Down
61 changes: 61 additions & 0 deletions tests/Unit/Coercer/DateTimeCoercerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use DualMedia\DtoRequestBundle\Coercer\DateTimeCoercer;
use DualMedia\DtoRequestBundle\Coercer\StringCoercer;
use DualMedia\DtoRequestBundle\Dto\Enum\Time;
use DualMedia\DtoRequestBundle\Metadata\Model\Format;
use DualMedia\DtoRequestBundle\Metadata\Model\Property;
use PHPUnit\Framework\Attributes\CoversClass;
Expand Down Expand Up @@ -42,6 +43,66 @@ public function testCoercesWithFormat(): void
static::assertSame('2024-01-15', $coerced->format('Y-m-d'));
}

public function testNoTimeLeavesParsedTimeUntouched(): void
{
// Without a time value, behavior must be identical to a raw createFromFormat:
// the parsed date inherits the current time components, unchanged.
$expected = \DateTimeImmutable::createFromFormat('Y-m-d', '2024-01-15');
static::assertNotFalse($expected);

$result = $this->coercer->coerce($this->property([new Format('Y-m-d')]));
$coerced = ($result->coerce)('2024-01-15');

static::assertInstanceOf(\DateTimeImmutable::class, $coerced);
static::assertSame('2024-01-15', $coerced->format('Y-m-d'));
static::assertSame($expected->format('H:i'), $coerced->format('H:i'));
}

public function testTimeStartOfDay(): void
{
$result = $this->coercer->coerce($this->property([new Format('Y-m-d', Time::StartOfDay->value)]));
$coerced = ($result->coerce)('2024-01-15');

static::assertInstanceOf(\DateTimeImmutable::class, $coerced);
static::assertSame('2024-01-15 00:00:00', $coerced->format('Y-m-d H:i:s'));
}

public function testTimeMidday(): void
{
$result = $this->coercer->coerce($this->property([new Format('Y-m-d', Time::Midday->value)]));
$coerced = ($result->coerce)('2024-01-15');

static::assertInstanceOf(\DateTimeImmutable::class, $coerced);
static::assertSame('2024-01-15 12:00:00', $coerced->format('Y-m-d H:i:s'));
}

public function testTimeEndOfDay(): void
{
$result = $this->coercer->coerce($this->property([new Format('Y-m-d', Time::EndOfDay->value)]));
$coerced = ($result->coerce)('2024-01-15');

static::assertInstanceOf(\DateTimeImmutable::class, $coerced);
static::assertSame('2024-01-15 23:59:59', $coerced->format('Y-m-d H:i:s'));
}

public function testCustomTimeString(): void
{
$result = $this->coercer->coerce($this->property([new Format('Y-m-d', '06:30:15')]));
$coerced = ($result->coerce)('2024-01-15');

static::assertInstanceOf(\DateTimeImmutable::class, $coerced);
static::assertSame('2024-01-15 06:30:15', $coerced->format('Y-m-d H:i:s'));
}

public function testTimeNotAppliedOnInvalidParse(): void
{
// Failed parse must return the original string regardless of the time value.
$result = $this->coercer->coerce($this->property([new Format('Y-m-d', Time::Midday->value)]));
$coerced = ($result->coerce)('not-a-date');

static::assertSame('not-a-date', $coerced);
}

public function testInvalidFormatReturnsOriginal(): void
{
$result = $this->coercer->coerce($this->property([new Format('Y-m-d')]));
Expand Down
63 changes: 63 additions & 0 deletions tests/Unit/Metadata/Model/FormatTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

declare(strict_types=1);

namespace DualMedia\DtoRequestBundle\Tests\Unit\Metadata\Model;

use DualMedia\DtoRequestBundle\Dto\Enum\Time;
use DualMedia\DtoRequestBundle\Metadata\Model\Format;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;

#[CoversClass(Format::class)]
#[Group('unit')]
class FormatTest extends TestCase
{
public function testNullTimeIsAllowed(): void
{
$format = new Format('Y-m-d');
static::assertNull($format->time);
}

/**
* @return iterable<string, array{string}>
*/
public static function provideValidTimeIsAcceptedCases(): iterable
{
yield 'start of day' => [Time::StartOfDay->value];
yield 'midday' => [Time::Midday->value];
yield 'end of day' => [Time::EndOfDay->value];
yield 'custom' => ['06:30:15'];
}

#[DataProvider('provideValidTimeIsAcceptedCases')]
public function testValidTimeIsAccepted(
string $time
): void {
$format = new Format('Y-m-d', $time);
static::assertSame($time, $format->time);
}

/**
* @return iterable<string, array{string}>
*/
public static function provideInvalidTimeThrowsCases(): iterable
{
yield 'out of range hour' => ['25:00:00'];
yield 'out of range minute' => ['10:99:00'];
yield 'missing seconds' => ['10:30'];
yield 'not a time' => ['nonsense'];
yield 'empty' => [''];
}

#[DataProvider('provideInvalidTimeThrowsCases')]
public function testInvalidTimeThrows(
string $time
): void {
$this->expectException(\InvalidArgumentException::class);

new Format('Y-m-d', $time);
}
}
19 changes: 19 additions & 0 deletions tests/Unit/Reflection/MetaReflectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use DualMedia\DtoRequestBundle\Dto\Attribute\Offset as OffsetAttribute;
use DualMedia\DtoRequestBundle\Dto\Attribute\OrderBy as OrderByAttribute;
use DualMedia\DtoRequestBundle\Dto\Enum\ActionCondition;
use DualMedia\DtoRequestBundle\Dto\Enum\Time;
use DualMedia\DtoRequestBundle\Metadata\Model\Action;
use DualMedia\DtoRequestBundle\Metadata\Model\AsDoctrineReference;
use DualMedia\DtoRequestBundle\Metadata\Model\FindBy;
Expand Down Expand Up @@ -62,6 +63,24 @@ public function testFormatAttribute(): void
static::assertCount(1, $result);
static::assertInstanceOf(Format::class, $result[0]);
static::assertSame('Y-m-d', $result[0]->format);
static::assertNull($result[0]->time);
}

public function testFormatAttributeNormalizesTimeEnumToStringValue(): void
{
$result = $this->reflector->meta([new FormatAttribute('Y-m-d', Time::EndOfDay)]);
static::assertCount(1, $result);
static::assertInstanceOf(Format::class, $result[0]);
static::assertSame('Y-m-d', $result[0]->format);
static::assertSame('23:59:59', $result[0]->time);
}

public function testFormatAttributeKeepsCustomTimeString(): void
{
$result = $this->reflector->meta([new FormatAttribute('Y-m-d', '06:30:00')]);
static::assertCount(1, $result);
static::assertInstanceOf(Format::class, $result[0]);
static::assertSame('06:30:00', $result[0]->time);
}

public function testFromKeyAttribute(): void
Expand Down
Loading