From 9af5ede33e59fe021b55e124fdf054768d745d3a Mon Sep 17 00:00:00 2001 From: Nicolas Joubert Date: Tue, 3 Nov 2026 10:44:49 +0100 Subject: [PATCH] #402 - date_parser: reject the out-of-range dates, cast the scalar inputs, explicit error on the other inputs Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../transformers/date_parser_transformer.md | 5 +- .../Date/DateParserTransformer.php | 12 ++++ .../Date/DateParserTransformerTest.php | 60 +++++++++++++++++++ 4 files changed, 77 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 73519523..d589484f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Latest * [#392](https://github.com/cleverage/process-bundle/issues/392) Documentation: reset of the process configurations between two messages of a worker (`kernel.reset`, #355), permissions of the JSON buffer of `process_launcher`, `ProcessManager` subclasses in `UPGRADE.md` (v5.5), broken link in the CHANGELOG. ## Fixes +* [#402](https://github.com/cleverage/process-bundle/issues/402) `date_parser`: a date or a time out of range (`2024-02-31`, `25:61`), parsed by `\DateTime::createFromFormat()` with a warning and overflowing to the next month or day, throws an `UnexpectedValueException`, as documented for a value that cannot be parsed. A scalar (e.g. an `int` timestamp with the `U` format) or `\Stringable` input is cast to string, an array or another object throws an `UnexpectedValueException` instead of a `TypeError`. Update documentation, add tests. * [#396](https://github.com/cleverage/process-bundle/issues/396) A failure of `finalize()` on a process that has succeeded makes the process fail with a `ProcessFailedException`, once every task is finalized: the process was flagged and logged as failed, but ended successfully (`cleverage_process.end` event, the command exiting with `0`, a parent process going on). `ProcessLauncherTask` is finalizable: the sub-processes still running when the process fails or is stopped are stopped (a warning is logged) and the JSON buffers not output yet are removed, instead of going on with their side effects after the end of the process. Update documentation, add tests. * [#394](https://github.com/cleverage/process-bundle/issues/394) `ProcessManager::execute()`: an exception thrown by a listener of `cleverage_process.fail` (`ProcessEvent::EVENT_PROCESS_FAILED`) is logged as an error and no longer replaces the error of the process, which is rethrown to the command, the parent process or Messenger. The debug message "has error outputs but it's error strategy 'stop' implies they will never be reached" is removed: the error branch of a task with the `stop` strategy is executed before the process stops. Update documentation, add tests. * [#388](https://github.com/cleverage/process-bundle/issues/388) The temporary files of `file_splitter`, `csv_splitter` and of the JSON buffer of `process_launcher` (#343) are created with the `0077` umask: they are no longer readable by other users before their permissions are set to `0600`. Add tests. diff --git a/docs/reference/transformers/date_parser_transformer.md b/docs/reference/transformers/date_parser_transformer.md index f83e1333..e950ab5f 100644 --- a/docs/reference/transformers/date_parser_transformer.md +++ b/docs/reference/transformers/date_parser_transformer.md @@ -13,11 +13,14 @@ Accepted inputs --------------- * `string`: a date matching the configured `format` +* another scalar (e.g. an `int` timestamp with the `U` format) or a `\Stringable`, cast to string * `\DateTime`, returned unchanged * `\DateTimeImmutable`, converted to a `\DateTime` (same date, time and timezone) * Any falsy value (`null`, `''`, `false`…), returned unchanged -A string that cannot be parsed with the given format throws an `UnexpectedValueException`. +A string that cannot be parsed with the given format throws an `UnexpectedValueException`, and so does a date or a +time out of range (e.g. `2024-02-31` or `25:61`, that `\DateTime::createFromFormat()` parses with a warning, the date +overflowing to `2024-03-02`). An array or another object throws an `UnexpectedValueException`. Possible outputs ---------------- diff --git a/src/Transformer/Date/DateParserTransformer.php b/src/Transformer/Date/DateParserTransformer.php index 4cc9a7e7..fe276a08 100644 --- a/src/Transformer/Date/DateParserTransformer.php +++ b/src/Transformer/Date/DateParserTransformer.php @@ -42,11 +42,23 @@ public function transform(mixed $value, array $options = []): mixed return \DateTime::createFromImmutable($value); } + if (\is_int($value) || \is_float($value) || \is_bool($value) || $value instanceof \Stringable) { + $value = (string) $value; + } elseif (!\is_string($value)) { + throw new UnexpectedValueException(\sprintf('The date_parser transformer expects a string, %s given.', get_debug_type($value))); + } + $date = \DateTime::createFromFormat($options['format'], $value); if (!$date) { throw new UnexpectedValueException('Given value cannot be parsed into a date'); } + // An out-of-range value (e.g. "2024-02-31", "25:61") is parsed with a warning, the date overflowing to the next + // month or day + $errors = \DateTime::getLastErrors(); + if (\is_array($errors) && [] !== $errors['warnings']) { + throw new UnexpectedValueException(\sprintf('Given value "%s" is not a valid date: %s', $value, implode(', ', $errors['warnings']))); + } return $date; } diff --git a/tests/Transformer/Date/DateParserTransformerTest.php b/tests/Transformer/Date/DateParserTransformerTest.php index e07dab2b..cee7cd97 100644 --- a/tests/Transformer/Date/DateParserTransformerTest.php +++ b/tests/Transformer/Date/DateParserTransformerTest.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Tests\Transformer\Date; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\Date\DateParserTransformer; use PHPUnit\Framework\TestCase; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -104,4 +105,63 @@ public function testConfigureOptions(): void $resolvedOptions = $resolver->resolve(); $this->assertEquals(['format'], array_keys($resolvedOptions)); } + + /** + * @return iterable + */ + public static function provideOutOfRangeDates(): iterable + { + yield 'day' => ['2024-02-31', 'Y-m-d', 'The parsed date was invalid']; + yield 'month' => ['2024-13-01', 'Y-m-d', 'The parsed date was invalid']; + yield 'time' => ['2024-02-01 25:61', 'Y-m-d H:i', 'The parsed time was invalid']; + } + + /** + * Parsed with a warning, the date overflowing: "2024-02-31" gave 2024-03-02. + */ + #[\PHPUnit\Framework\Attributes\DataProvider('provideOutOfRangeDates')] + public function testTransformOutOfRangeDate(string $value, string $format, string $warning): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage("Given value \"{$value}\" is not a valid date: {$warning}"); + + (new DateParserTransformer())->transform($value, ['format' => $format]); + } + + public function testTransformLeapDay(): void + { + $date = (new DateParserTransformer())->transform('2024-02-29', ['format' => '!Y-m-d']); + + $this->assertInstanceOf(\DateTime::class, $date); + $this->assertSame('2024-02-29', $date->format('Y-m-d')); + } + + public function testTransformScalarAndStringable(): void + { + $transformer = new DateParserTransformer(); + $stringable = new class implements \Stringable { + public function __toString(): string + { + return '2024-02-29'; + } + }; + + $timestamp = $transformer->transform(1709164800, ['format' => 'U']); + $this->assertInstanceOf(\DateTime::class, $timestamp); + $this->assertSame('2024-02-29', $timestamp->format('Y-m-d')); + $fromStringable = $transformer->transform($stringable, ['format' => 'Y-m-d']); + $this->assertInstanceOf(\DateTime::class, $fromStringable); + $this->assertSame('2024-02-29', $fromStringable->format('Y-m-d')); + } + + /** + * A raw TypeError was thrown. + */ + public function testTransformInvalidType(): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage('The date_parser transformer expects a string, array given.'); + + (new DateParserTransformer())->transform(['2024-02-29'], ['format' => 'Y-m-d']); + } }