diff --git a/CHANGELOG.md b/CHANGELOG.md index ee3734ee..1d93b303 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. * [#398](https://github.com/cleverage/process-bundle/issues/398) Transformers edge cases. `trim`: a `charlist` with multibyte characters is applied with `mb_trim()` (it produced invalid UTF-8). `convert_value`: with `keep_missing` and `auto_cast`, the input itself is returned, as documented, not its value cast to string. `multi_replace`: the numeric keys of `replace_mapping` no longer throw a `TypeError`, and a replacement that is not a scalar is rejected with the configuration. Conditions (`filter`, `column_aggregator`, `array_filter`, `unset`): the list form of `empty` / `not_empty` (`not_empty: ['[email]']`), described by the documentation, and the numeric property paths no longer throw a `TypeError`. `hash`: an array or a non-`Stringable` object throws an `UnexpectedValueException` (an array was hashed as the string `Array`). The empty `delimiter` of `explode`, an invalid `format` of `sprintf` and an unknown `class` of `instantiate` are rejected with the configuration, not with the first value. Update documentation, add tests. * [#400](https://github.com/cleverage/process-bundle/issues/400) `slugify`: new `strip_tags` option (`true` by default) to keep a text containing a `<` that is not HTML (`strip_tags()` removed everything after it); the result is lowercased with `mb_strtolower()`; a scalar or `\Stringable` input is cast to string, `null`, an array or another object throws an `UnexpectedValueException` instead of a `TypeError`. Documentation: the default transliterator removes the letters that are not decomposed (`Cœur` becomes `c_ur`), `Any-Latin; Latin-ASCII` is recommended. 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. 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']); + } }