From 34d268d3860aef3842435e26cb1374d1a5de45b9 Mon Sep 17 00:00:00 2001 From: Nicolas Joubert Date: Thu, 3 Dec 2026 11:45:37 +0100 Subject: [PATCH] #405 - Transformers: a common policy for null, array and object inputs Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + UPGRADE.md | 43 ++++ docs/reference/transformers/_template.md | 4 +- .../transformers/array_element_transformer.md | 2 +- .../transformers/array_last_transformer.md | 2 +- .../transformers/array_unset_transformer.md | 2 +- .../transformers/convert_value_transformer.md | 5 +- .../transformers/date_parser_transformer.md | 5 +- .../transformers/explode_transformer.md | 6 +- .../transformers/hash_transformer.md | 8 +- .../transformers/implode_transformer.md | 3 +- .../transformers/instantiate_transformer.md | 2 +- .../transformers/multi_replace_transformer.md | 7 +- .../transformers/preg_filter_transformer.md | 5 +- .../transformers/preg_match_transformer.md | 3 +- .../transformers/slugify_transformer.md | 7 +- .../transformers/sprintf_transformer.md | 2 + .../transformers/trim_transformer.md | 3 +- .../transformers/unset_transformer.md | 4 +- .../Array/ArrayElementTransformer.php | 2 + .../Array/ArrayLastTransformer.php | 3 + .../Array/ArrayUnsetTransformer.php | 6 +- src/Transformer/ConvertValueTransformer.php | 8 +- .../Date/DateParserTransformer.php | 10 +- src/Transformer/InputPolicy.php | 60 +++++ src/Transformer/MultiReplaceTransformer.php | 8 +- .../Object/InstantiateTransformer.php | 8 +- src/Transformer/PregFilterTransformer.php | 5 +- src/Transformer/String/ExplodeTransformer.php | 14 +- src/Transformer/String/HashTransformer.php | 13 +- src/Transformer/String/ImplodeTransformer.php | 9 +- .../String/PregMatchTransformer.php | 11 +- src/Transformer/String/SlugifyTransformer.php | 10 +- src/Transformer/String/SprintfTransformer.php | 7 + src/Transformer/String/TrimTransformer.php | 6 +- src/Transformer/UnsetTransformer.php | 4 +- tests/Exception/SplExceptionsTest.php | 1 + tests/Fixtures/InputPolicyEnum.php | 22 ++ .../Functional/TransformerInputPolicyTest.php | 218 ++++++++++++++++++ tests/Task/TransformerTaskTest.php | 1 + .../Array/ArrayElementTransformerTest.php | 1 + .../Array/ArrayLastTransformerTest.php | 6 +- .../Array/ArrayUnsetTransformerTest.php | 3 +- .../ConvertValueTransformerTest.php | 9 +- .../Date/DateParserTransformerTest.php | 1 + tests/Transformer/InputPolicyTest.php | 81 +++++++ .../MultiReplaceTransformerTest.php | 3 +- .../Object/InstantiateTransformerTest.php | 3 +- .../Transformer/PregFilterTransformerTest.php | 1 + .../String/ExplodeTransformerTest.php | 6 +- .../String/HashTransformerTest.php | 4 +- .../String/ImplodeTransformerTest.php | 26 +++ .../String/PregMatchTransformerTest.php | 1 + .../String/SlugifyTransformerTest.php | 9 +- .../String/SprintfTransformerTest.php | 25 ++ .../String/TrimTransformerTest.php | 1 + tests/Transformer/TransformerTraitTest.php | 1 + tests/Transformer/UnsetTransformerTest.php | 3 +- 58 files changed, 634 insertions(+), 90 deletions(-) create mode 100644 src/Transformer/InputPolicy.php create mode 100644 tests/Fixtures/InputPolicyEnum.php create mode 100644 tests/Functional/TransformerInputPolicyTest.php create mode 100644 tests/Transformer/InputPolicyTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 87d69d54..c82a6395 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ Latest * [#505](https://github.com/cleverage/process-bundle/issues/505) Consistent names for the equivalent options of the tasks: `filename` is renamed `file_path` (`file_reader`, `file_writer`, `line_reader`) and `base_folder_path` is renamed `base_path` (`input_folder_browser`), without deprecation in 5.x; `input_folder_browser` adds a single `/` between a non-empty `base_path` and the input, as `input_csv_reader` does (see `UPGRADE.md`). Update documentation and tests. * [#380](https://github.com/cleverage/process-bundle/issues/380) Executing a process while it is already running, by itself or through its sub-processes (`A → B → A` with `process_executor`), throws a `RecursiveProcessExecutionException` naming the chain of processes, before any event is dispatched for the rejected execution (deprecated since 5.6, it reset the states of the running process). The `error_strategy` of the `process_executor` task applies (see `UPGRADE.md`). Update documentation and tests. * [#404](https://github.com/cleverage/process-bundle/issues/404) `slugify`: the default `transliterator` is `Any-Latin; Latin-ASCII` (instead of `NFD; [:Nonspacing Mark:] Remove; NFC`), which transliterates the letters that are not decomposed (`Cœur` gives `coeur` instead of `c_ur`) and the other scripts; `strip_tags` is `false` by default (a `<` truncated the value). The slugs of existing data change, set both options to keep the 5.x slugs (see `UPGRADE.md`). Update documentation and tests. +* [#405](https://github.com/cleverage/process-bundle/issues/405) Transformers: one policy for the inputs they do not expect. A string transformer (`convert_value` with `auto_cast`, `date_parser`, `explode`, `hash`, `multi_replace`, `preg_filter`, `preg_match`, `slugify`, `trim`) gives `null` for `null` (`hash` gave the hash of an empty string, `slugify` threw an `UnexpectedValueException`, `explode` gave `[]`, `multi_replace` `''`), casts a scalar or a `\Stringable` to a string, and throws an `UnexpectedValueException` for an array (cast to `'Array'` with a warning) or another object (raw `Error`); an array transformer (`array_element`, `array_last`, `array_unset`, `implode`, `instantiate`, `unset`) throws an `UnexpectedValueException` for anything but an array (`array_element` and `array_last` threw a `TypeError`); `sprintf` and `implode` reject an array or an object argument or item, `date_parser` an empty array (returned unchanged). New exception messages (see `UPGRADE.md`). Update documentation, add tests. ## Changes * [#428](https://github.com/cleverage/process-bundle/issues/428) Tests on PHPUnit 12.5 and 13 (PHPUnit 10 and 11 dropped), with the lowest dependencies on PHP 8.3 and 8.5. diff --git a/UPGRADE.md b/UPGRADE.md index 51ce9272..0546a8d9 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -88,6 +88,49 @@ slugify: strip_tags: true ``` +### Inputs of the transformers + +The transformers share one policy for the inputs they do not expect, documented in the "Accepted inputs" section of +their reference page: + +* a string transformer (`convert_value` with `auto_cast`, `date_parser`, `explode`, `hash`, `multi_replace`, + `preg_filter`, `preg_match`, `slugify`, `trim`) gives `null` for `null`, casts a scalar or a `\Stringable` to a + string, and throws an `UnexpectedValueException` for an array or another object (a `\BackedEnum` included); +* an array transformer (`array_element`, `array_last`, `array_unset`, `implode`, `instantiate`, `unset`) throws an + `UnexpectedValueException` for anything but an array, `null` included; +* the other transformers keep their own contract, unchanged (`callback`, `cast`, `default`, `mapping`, `rules`..., + the arguments of `sprintf`, a date for `date_format`...): see their reference page. + +The results change for these inputs: + +| Transformer | Input | 5.x | 6.0 | +|----------------------------------|------------------------------------|----------------------------------------|----------------------------| +| `hash` | `null` | hash of `''` | `null` | +| `slugify` | `null` | `UnexpectedValueException` | `null` | +| `explode` | `null` | `[]` | `null` | +| `multi_replace` | `null` | `''` (`null` if `replace_mapping` is empty) | `null` | +| `preg_filter` | `null` | `null` or the replaced `''` | `null` | +| `multi_replace` | scalar, empty `replace_mapping` | returned unchanged | cast to a string | +| `multi_replace` | array, empty `replace_mapping` | returned unchanged | `UnexpectedValueException` | +| `trim`, `explode`, `multi_replace`, `preg_filter`, `preg_match` | array | `'Array'` (a warning, an exception only when the PHP warnings are thrown) | `UnexpectedValueException` | +| same, and `convert_value` with `auto_cast` | object without `__toString()`, enum | `Error` | `UnexpectedValueException` | +| `sprintf`, `implode` | array or object without `__toString()` as an argument or an item | `'Array'` with a warning, or `Error` | `UnexpectedValueException` | +| `array_element`, `array_last` | anything but an array | `TypeError` | `UnexpectedValueException` | +| `date_parser` | `[]` | returned unchanged | `UnexpectedValueException` | +| `explode` | `false` | `['']` | `[]` (as `''`) | +| `preg_match` | `false` | the matches of `''` | `null` (as `''`) | + +The messages of the exceptions change too: `The transformer expects a string, given.`, +`The transformer expects an array, given.`, `The sprintf transformer expects strings, given.` and +`The implode transformer expects an array of strings, item given.`; `convert_value` without `auto_cast` gives +the type with `get_debug_type()` (`float`, `bool`, `stdClass` instead of `double`, `boolean`, `object`). +Within a process, these exceptions are wrapped in a `TransformerException` and the `error_strategy` of the task +applies, as before. + +Check the processes that hash, slugify, explode or replace an optional value: a missing value now stays `null`. Add a +`default` transformer after them where an empty string or an empty array is expected (`explode` followed by +`array_map` or `implode`, which reject `null`). + ### Error output of the CSV readers A line that `csv_reader` or `input_csv_reader` cannot read (number of columns not matching the headers, line that diff --git a/docs/reference/transformers/_template.md b/docs/reference/transformers/_template.md index 74c4b578..40a9c270 100644 --- a/docs/reference/transformers/_template.md +++ b/docs/reference/transformers/_template.md @@ -12,7 +12,9 @@ Transformer reference Accepted inputs --------------- -_Description of allowed types._ +_Description of allowed types. A string transformer gives `null` for `null`, casts a scalar or a `\Stringable` to a +string and throws an `UnexpectedValueException` for an array or another object; an array transformer throws an +`UnexpectedValueException` for anything but an array._ Possible outputs ---------------- diff --git a/docs/reference/transformers/array_element_transformer.md b/docs/reference/transformers/array_element_transformer.md index 4c4b69fc..906d0618 100644 --- a/docs/reference/transformers/array_element_transformer.md +++ b/docs/reference/transformers/array_element_transformer.md @@ -13,7 +13,7 @@ Transformer reference Accepted inputs --------------- -`array` +`array`. Any other value, `null` included, throws an `UnexpectedValueException`. Possible outputs ---------------- diff --git a/docs/reference/transformers/array_last_transformer.md b/docs/reference/transformers/array_last_transformer.md index 90f5f563..45a62f64 100644 --- a/docs/reference/transformers/array_last_transformer.md +++ b/docs/reference/transformers/array_last_transformer.md @@ -12,7 +12,7 @@ Transformer reference Accepted inputs --------------- -`array` +`array`. Any other value, `null` included, throws an `UnexpectedValueException`. Possible outputs ---------------- diff --git a/docs/reference/transformers/array_unset_transformer.md b/docs/reference/transformers/array_unset_transformer.md index 73359f11..7498d02f 100644 --- a/docs/reference/transformers/array_unset_transformer.md +++ b/docs/reference/transformers/array_unset_transformer.md @@ -12,7 +12,7 @@ Transformer reference Accepted inputs --------------- -`array`. Any other value throws an `UnexpectedValueException`. +`array`. Any other value, `null` included, throws an `UnexpectedValueException`. Possible outputs ---------------- diff --git a/docs/reference/transformers/convert_value_transformer.md b/docs/reference/transformers/convert_value_transformer.md index eeb6711a..a6e424bf 100644 --- a/docs/reference/transformers/convert_value_transformer.md +++ b/docs/reference/transformers/convert_value_transformer.md @@ -14,8 +14,9 @@ Accepted inputs * `string` or `int`: used as a key of `map` * `null`: always returns `null`, without lookup -* other scalars or objects: only if `auto_cast` is `true` (cast to string), otherwise an `UnexpectedValueException` is - thrown. Arrays are always rejected. +* another scalar or a `\Stringable`: only if `auto_cast` is `true` (cast to string), otherwise an + `UnexpectedValueException` is thrown +* an array or another object (a `\BackedEnum` included): always an `UnexpectedValueException` Possible outputs ---------------- diff --git a/docs/reference/transformers/date_parser_transformer.md b/docs/reference/transformers/date_parser_transformer.md index 058431d7..9d2aa550 100644 --- a/docs/reference/transformers/date_parser_transformer.md +++ b/docs/reference/transformers/date_parser_transformer.md @@ -16,12 +16,13 @@ Accepted inputs * 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 +* Any falsy value (`null`, `''`, `false`…) but an empty array, returned unchanged 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`). The trailing data allowed by a `+` in the format (e.g. `!Y-m-d+` for -`2024-02-29T10:00:00Z`) is ignored. An array or another object throws an `UnexpectedValueException`. +`2024-02-29T10:00:00Z`) is ignored. An array or another object (a `\BackedEnum` included) throws an +`UnexpectedValueException`. Possible outputs ---------------- diff --git a/docs/reference/transformers/explode_transformer.md b/docs/reference/transformers/explode_transformer.md index 3275a879..58e79550 100644 --- a/docs/reference/transformers/explode_transformer.md +++ b/docs/reference/transformers/explode_transformer.md @@ -12,12 +12,14 @@ Transformer reference Accepted inputs --------------- -Any value that can be cast to `string`, or `null`. +`string`, or a scalar or a `\Stringable` cast to a string. `null` gives `null`. An array or another object (a +`\BackedEnum` included) throws an `UnexpectedValueException`. Possible outputs ---------------- -`array`: the list of parts; an empty array if the input is `null` or an empty string +* `array`: the list of parts; an empty array for an empty string +* `null` if the input is `null` Options ------- diff --git a/docs/reference/transformers/hash_transformer.md b/docs/reference/transformers/hash_transformer.md index d3473f98..469d8072 100644 --- a/docs/reference/transformers/hash_transformer.md +++ b/docs/reference/transformers/hash_transformer.md @@ -12,13 +12,15 @@ Transformer reference Accepted inputs --------------- -Any value that can be cast to `string` (`null` gives the hash of an empty string). An array or an object that is not -`\Stringable` throws an `UnexpectedValueException` (an array was hashed as the string `Array`). +`string`, or a scalar or a `\Stringable` cast to a string. `null` gives `null`. An array or another object (a +`\BackedEnum` included) throws an `UnexpectedValueException`. `null` is not hashed (it gave the +hash of an empty string, the same for every missing value). Possible outputs ---------------- -`string`: the hash, as lowercase hexits by default, or raw binary data if `raw_output` is `true` +* `string`: the hash, as lowercase hexits by default, or raw binary data if `raw_output` is `true` +* `null` if the input is `null` Options ------- diff --git a/docs/reference/transformers/implode_transformer.md b/docs/reference/transformers/implode_transformer.md index f5a6da78..9a8f403a 100644 --- a/docs/reference/transformers/implode_transformer.md +++ b/docs/reference/transformers/implode_transformer.md @@ -13,7 +13,8 @@ Transformer reference Accepted inputs --------------- -`array` of values that can be cast to `string`. Any other input throws an `UnexpectedValueException`. +`array` of scalars, `null` or `\Stringable` values, cast to strings. Any other input, `null` included, or an item that +is an array or another object throws an `UnexpectedValueException`. Possible outputs ---------------- diff --git a/docs/reference/transformers/instantiate_transformer.md b/docs/reference/transformers/instantiate_transformer.md index ee2d8648..a83178ca 100644 --- a/docs/reference/transformers/instantiate_transformer.md +++ b/docs/reference/transformers/instantiate_transformer.md @@ -14,7 +14,7 @@ Accepted inputs --------------- `array`: the constructor arguments. A list is passed positionally; string keys are used as named arguments. Any other -value throws an `UnexpectedValueException`. +value, `null` included, throws an `UnexpectedValueException`. Possible outputs ---------------- diff --git a/docs/reference/transformers/multi_replace_transformer.md b/docs/reference/transformers/multi_replace_transformer.md index 307beb89..38196ab6 100644 --- a/docs/reference/transformers/multi_replace_transformer.md +++ b/docs/reference/transformers/multi_replace_transformer.md @@ -13,13 +13,14 @@ Transformer reference Accepted inputs --------------- -Any value that can be cast to string. +`string`, or a scalar or a `\Stringable` cast to a string. `null` gives `null`. An array or another object (a +`\BackedEnum` included) throws an `UnexpectedValueException`. Possible outputs ---------------- -`string`: the input with all replacements applied. If `replace_mapping` is empty, the input is returned unchanged -(not cast). +* `string`: the input with all replacements applied (cast to a string, even if `replace_mapping` is empty) +* `null` if the input is `null` Options ------- diff --git a/docs/reference/transformers/preg_filter_transformer.md b/docs/reference/transformers/preg_filter_transformer.md index a30212f3..a90330b6 100644 --- a/docs/reference/transformers/preg_filter_transformer.md +++ b/docs/reference/transformers/preg_filter_transformer.md @@ -14,12 +14,13 @@ Transformer reference Accepted inputs --------------- -Any value that can be cast to string. +`string`, or a scalar or a `\Stringable` cast to a string. `null` gives `null`. An array or another object (a +`\BackedEnum` included) throws an `UnexpectedValueException`. Possible outputs ---------------- -`string|null`: the replaced string, or `null` if no pattern matches. +`string|null`: the replaced string, or `null` if no pattern matches or if the input is `null`. An invalid regular expression is rejected with an `InvalidOptionsException` when the options are resolved. A PCRE error while matching (e.g. invalid UTF-8 with the `u` modifier, backtracking limit reached) throws an diff --git a/docs/reference/transformers/preg_match_transformer.md b/docs/reference/transformers/preg_match_transformer.md index 53a1dbb5..6aa5a196 100644 --- a/docs/reference/transformers/preg_match_transformer.md +++ b/docs/reference/transformers/preg_match_transformer.md @@ -13,7 +13,8 @@ Transformer reference Accepted inputs --------------- -Any value that can be cast to `string`, or `null`. +`string`, or a scalar or a `\Stringable` cast to a string. `null` gives `null`. An array or another object (a +`\BackedEnum` included) throws an `UnexpectedValueException`. Possible outputs ---------------- diff --git a/docs/reference/transformers/slugify_transformer.md b/docs/reference/transformers/slugify_transformer.md index 6fe9bb20..cf8280c7 100644 --- a/docs/reference/transformers/slugify_transformer.md +++ b/docs/reference/transformers/slugify_transformer.md @@ -18,13 +18,14 @@ Transformer reference Accepted inputs --------------- -`string`, or a scalar or `\Stringable` cast to string. `null`, an array or another object throws an -`UnexpectedValueException`. +`string`, or a scalar or a `\Stringable` cast to a string. `null` gives `null`. An array or another object (a +`\BackedEnum` included) throws an `UnexpectedValueException`. Possible outputs ---------------- -`string` +* `string` +* `null` if the input is `null` Options ------- diff --git a/docs/reference/transformers/sprintf_transformer.md b/docs/reference/transformers/sprintf_transformer.md index 367d4c6a..db35689d 100644 --- a/docs/reference/transformers/sprintf_transformer.md +++ b/docs/reference/transformers/sprintf_transformer.md @@ -15,6 +15,8 @@ Accepted inputs * `array`: each element is used as an argument of the format, in order * any other value (scalar, `null`, `\Stringable`): used as the single argument of the format +An argument that is an array or another object (a `\BackedEnum` included) throws an `UnexpectedValueException`. + Possible outputs ---------------- diff --git a/docs/reference/transformers/trim_transformer.md b/docs/reference/transformers/trim_transformer.md index e90244d3..660a4300 100644 --- a/docs/reference/transformers/trim_transformer.md +++ b/docs/reference/transformers/trim_transformer.md @@ -13,7 +13,8 @@ Transformer reference Accepted inputs --------------- -Any value that can be cast to `string`, or `null`. +`string`, or a scalar or a `\Stringable` cast to a string. `null` gives `null`. An array or another object (a +`\BackedEnum` included) throws an `UnexpectedValueException`. Possible outputs ---------------- diff --git a/docs/reference/transformers/unset_transformer.md b/docs/reference/transformers/unset_transformer.md index 168cda1a..b46d033f 100644 --- a/docs/reference/transformers/unset_transformer.md +++ b/docs/reference/transformers/unset_transformer.md @@ -12,8 +12,8 @@ Transformer reference Accepted inputs --------------- -`array` containing the `property` key. An `UnexpectedValueException` is thrown if the input is not an array, or if the -key does not exist (even when the condition is not met). +`array` containing the `property` key. An `UnexpectedValueException` is thrown if the input is not an array (`null` +included), or if the key does not exist (even when the condition is not met). Possible outputs ---------------- diff --git a/src/Transformer/Array/ArrayElementTransformer.php b/src/Transformer/Array/ArrayElementTransformer.php index 59062bca..0bab7302 100644 --- a/src/Transformer/Array/ArrayElementTransformer.php +++ b/src/Transformer/Array/ArrayElementTransformer.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Transformer\Array; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -26,6 +27,7 @@ final class ArrayElementTransformer implements ConfigurableTransformerInterface */ public function transform(mixed $value, array $options = []): mixed { + $value = InputPolicy::toArray($value, 'array_element'); $index = $options['index']; // null when the index is outside the array, at either end: no "Undefined array key" warning after the end, and // not the first element (as array_slice() would give) before the start diff --git a/src/Transformer/Array/ArrayLastTransformer.php b/src/Transformer/Array/ArrayLastTransformer.php index b578a169..88cbe024 100644 --- a/src/Transformer/Array/ArrayLastTransformer.php +++ b/src/Transformer/Array/ArrayLastTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\Array; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use CleverAge\ProcessBundle\Transformer\TransformerInterface; /** @@ -25,6 +26,8 @@ final class ArrayLastTransformer implements TransformerInterface */ public function transform(mixed $value, array $options = []): mixed { + $value = InputPolicy::toArray($value, 'array_last'); + // null for an empty array (no "Undefined array key" warning) return array_values(\array_slice($value, -1))[0] ?? null; } diff --git a/src/Transformer/Array/ArrayUnsetTransformer.php b/src/Transformer/Array/ArrayUnsetTransformer.php index 361d5f22..386e964a 100644 --- a/src/Transformer/Array/ArrayUnsetTransformer.php +++ b/src/Transformer/Array/ArrayUnsetTransformer.php @@ -13,8 +13,8 @@ namespace CleverAge\ProcessBundle\Transformer\Array; -use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -27,9 +27,7 @@ final class ArrayUnsetTransformer implements ConfigurableTransformerInterface */ public function transform(mixed $value, array $options = []): mixed { - if (!\is_array($value)) { - throw new UnexpectedValueException('Given value is not an array'); - } + $value = InputPolicy::toArray($value, 'array_unset'); unset($value[$options['key']]); return $value; diff --git a/src/Transformer/ConvertValueTransformer.php b/src/Transformer/ConvertValueTransformer.php index 5ff433e8..3a818e78 100644 --- a/src/Transformer/ConvertValueTransformer.php +++ b/src/Transformer/ConvertValueTransformer.php @@ -35,13 +35,11 @@ public function transform(mixed $value, array $options = []): mixed $input = $value; if (!\is_string($value) && !\is_int($value)) { // If not a valid array index if (!$options['auto_cast']) { - $type = \gettype($value); + $type = get_debug_type($value); throw new UnexpectedValueException("Value of type {$type} is not a valid array index, set auto_cast to true to cast it to a string"); } - if (\is_array($value)) { // Array to string conversion is a simple notice so we need to catch it here - throw new UnexpectedValueException("Unexpected input of type 'array' in convert_value transformer"); - } - $value = (string) $value; // Let's cast it to string + // An array or an object that cannot be cast to a string is rejected + $value = InputPolicy::toString($value, 'convert_value'); } if (!\array_key_exists($value, $options['map'])) { diff --git a/src/Transformer/Date/DateParserTransformer.php b/src/Transformer/Date/DateParserTransformer.php index 9bcbb265..8744eba6 100644 --- a/src/Transformer/Date/DateParserTransformer.php +++ b/src/Transformer/Date/DateParserTransformer.php @@ -15,6 +15,7 @@ use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -32,7 +33,8 @@ final class DateParserTransformer implements ConfigurableTransformerInterface */ public function transform(mixed $value, array $options = []): mixed { - if (!$value || $value instanceof \DateTime) { + // An empty array is rejected, as any array + if ((!$value && [] !== $value) || $value instanceof \DateTime) { return $value; } @@ -40,11 +42,7 @@ 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))); - } + $value = InputPolicy::toString($value, 'date_parser'); $date = \DateTime::createFromFormat($options['format'], $value); diff --git a/src/Transformer/InputPolicy.php b/src/Transformer/InputPolicy.php new file mode 100644 index 00000000..83a005ce --- /dev/null +++ b/src/Transformer/InputPolicy.php @@ -0,0 +1,60 @@ + + * + * @throws UnexpectedValueException if the value is not an array + */ + public static function toArray(mixed $value, string $code): array + { + if (!\is_array($value)) { + throw new UnexpectedValueException(\sprintf('The %s transformer expects an array, %s given.', $code, get_debug_type($value))); + } + + return $value; + } +} diff --git a/src/Transformer/MultiReplaceTransformer.php b/src/Transformer/MultiReplaceTransformer.php index ad74e4b4..c85085b6 100644 --- a/src/Transformer/MultiReplaceTransformer.php +++ b/src/Transformer/MultiReplaceTransformer.php @@ -28,11 +28,15 @@ final class MultiReplaceTransformer implements ConfigurableTransformerInterface /** * @param array $options */ - public function transform(mixed $value, array $options = []): mixed + public function transform(mixed $value, array $options = []): ?string { + if (null === $value) { + return null; + } + $value = InputPolicy::toString($value, 'multi_replace'); foreach ($options['replace_mapping'] as $pattern => $replacement) { // A numeric key of the mapping is an int - $value = str_replace((string) $pattern, (string) $replacement, (string) $value); + $value = str_replace((string) $pattern, (string) $replacement, $value); } return $value; diff --git a/src/Transformer/Object/InstantiateTransformer.php b/src/Transformer/Object/InstantiateTransformer.php index 4919450f..e4287c51 100644 --- a/src/Transformer/Object/InstantiateTransformer.php +++ b/src/Transformer/Object/InstantiateTransformer.php @@ -13,8 +13,8 @@ namespace CleverAge\ProcessBundle\Transformer\Object; -use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -27,11 +27,7 @@ final class InstantiateTransformer implements ConfigurableTransformerInterface */ public function transform(mixed $value, array $options = []): mixed { - if (!\is_array($value)) { - throw new UnexpectedValueException('Input value must be an array for transformer instantiate'); - } - - return (new \ReflectionClass($options['class']))->newInstanceArgs($value); + return (new \ReflectionClass($options['class']))->newInstanceArgs(InputPolicy::toArray($value, 'instantiate')); } public function configureOptions(OptionsResolver $resolver): void diff --git a/src/Transformer/PregFilterTransformer.php b/src/Transformer/PregFilterTransformer.php index 6346b049..b3f68171 100644 --- a/src/Transformer/PregFilterTransformer.php +++ b/src/Transformer/PregFilterTransformer.php @@ -24,10 +24,13 @@ final class PregFilterTransformer implements ConfigurableTransformerInterface */ public function transform(mixed $value, array $options = []): ?string { + if (null === $value) { + return null; + } $pattern = $options['pattern']; $replacement = $options['replacement']; - $result = preg_filter($pattern, $replacement, (string) $value); + $result = preg_filter($pattern, $replacement, InputPolicy::toString($value, 'preg_filter')); // null is also "no match": a PCRE error (e.g. invalid UTF-8 with the "u" modifier) is not if (null === $result) { Regex::checkLastError(\is_array($pattern) ? implode('", "', $pattern) : $pattern); diff --git a/src/Transformer/String/ExplodeTransformer.php b/src/Transformer/String/ExplodeTransformer.php index 84311c8a..532618e6 100644 --- a/src/Transformer/String/ExplodeTransformer.php +++ b/src/Transformer/String/ExplodeTransformer.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Transformer\String; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -24,15 +25,20 @@ final class ExplodeTransformer implements ConfigurableTransformerInterface /** * @param array $options * - * @return list + * @return list|null */ - public function transform(mixed $value, array $options = []): array + public function transform(mixed $value, array $options = []): ?array { - if (null === $value || '' === $value) { + if (null === $value) { + return null; + } + $value = InputPolicy::toString($value, 'explode'); + // explode() gives [""] for an empty string + if ('' === $value) { return []; } - return explode($options['delimiter'], (string) $value); + return explode($options['delimiter'], $value); } public function configureOptions(OptionsResolver $resolver): void diff --git a/src/Transformer/String/HashTransformer.php b/src/Transformer/String/HashTransformer.php index 8d4f68f6..7443c94c 100644 --- a/src/Transformer/String/HashTransformer.php +++ b/src/Transformer/String/HashTransformer.php @@ -13,8 +13,8 @@ namespace CleverAge\ProcessBundle\Transformer\String; -use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -36,13 +36,14 @@ public function configureOptions(OptionsResolver $resolver): void /** * @param array $options */ - public function transform(mixed $value, array $options = []): string + public function transform(mixed $value, array $options = []): ?string { - if (\is_array($value) || (\is_object($value) && !$value instanceof \Stringable)) { - // An array was hashed as the string "Array": the same hash for every array - throw new UnexpectedValueException(\sprintf('The hash transformer expects a string, %s given.', get_debug_type($value))); + // null is not hashed as "": the same hash for every missing value + if (null === $value) { + return null; } - return hash((string) $options['algo'], (string) $value, $options['raw_output']); + // An array was hashed as the string "Array": the same hash for every array + return hash((string) $options['algo'], InputPolicy::toString($value, 'hash'), $options['raw_output']); } } diff --git a/src/Transformer/String/ImplodeTransformer.php b/src/Transformer/String/ImplodeTransformer.php index 169787ed..f415c46a 100644 --- a/src/Transformer/String/ImplodeTransformer.php +++ b/src/Transformer/String/ImplodeTransformer.php @@ -15,6 +15,7 @@ use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -33,8 +34,12 @@ public function configureOptions(OptionsResolver $resolver): void */ public function transform(mixed $value, array $options = []): string { - if (!\is_array($value)) { - throw new UnexpectedValueException('Given value is not an array'); + $value = InputPolicy::toArray($value, 'implode'); + foreach ($value as $item) { + // An array was imploded as "Array", an object without __toString() threw an Error + if (null !== $item && !\is_scalar($item) && !$item instanceof \Stringable) { + throw new UnexpectedValueException(\sprintf('The implode transformer expects an array of strings, %s item given.', get_debug_type($item))); + } } return implode($options['separator'], $value); diff --git a/src/Transformer/String/PregMatchTransformer.php b/src/Transformer/String/PregMatchTransformer.php index 2c5debd5..07ecbe73 100644 --- a/src/Transformer/String/PregMatchTransformer.php +++ b/src/Transformer/String/PregMatchTransformer.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Transformer\String; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use CleverAge\ProcessBundle\Transformer\Regex; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -30,14 +31,18 @@ final class PregMatchTransformer implements ConfigurableTransformerInterface */ public function transform(mixed $value, array $options = []): ?array { - if (null === $value || '' === $value) { + if (null === $value) { + return null; + } + $value = InputPolicy::toString($value, 'preg_match'); + if ('' === $value) { return null; } if ($options['mode_all']) { - $result = preg_match_all($options['pattern'], (string) $value, $matches, $options['flags'], $options['offset']); + $result = preg_match_all($options['pattern'], $value, $matches, $options['flags'], $options['offset']); } else { - $result = preg_match($options['pattern'], (string) $value, $matches, $options['flags'], $options['offset']); + $result = preg_match($options['pattern'], $value, $matches, $options['flags'], $options['offset']); } // A PCRE error (e.g. invalid UTF-8 with the "u" modifier) is not "no match" if (false === $result) { diff --git a/src/Transformer/String/SlugifyTransformer.php b/src/Transformer/String/SlugifyTransformer.php index 88522c91..4a3c4a42 100644 --- a/src/Transformer/String/SlugifyTransformer.php +++ b/src/Transformer/String/SlugifyTransformer.php @@ -15,6 +15,7 @@ use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use CleverAge\ProcessBundle\Transformer\Regex; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Options; @@ -28,13 +29,12 @@ final class SlugifyTransformer implements ConfigurableTransformerInterface /** * @param array $options */ - public function transform(mixed $value, array $options = []): string + public function transform(mixed $value, array $options = []): ?string { - 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 slugify transformer expects a string, %s given.', get_debug_type($value))); + if (null === $value) { + return null; } + $value = InputPolicy::toString($value, 'slugify'); /** @var \Transliterator $transliterator */ $transliterator = $options['transliterator']; $string = $transliterator->transliterate($value); diff --git a/src/Transformer/String/SprintfTransformer.php b/src/Transformer/String/SprintfTransformer.php index 570af3ca..791c658c 100644 --- a/src/Transformer/String/SprintfTransformer.php +++ b/src/Transformer/String/SprintfTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\String; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -30,6 +31,12 @@ public function transform(mixed $value, array $options = []): string if (!\is_array($value)) { $value = [$value]; } + foreach ($value as $argument) { + // An array was formatted as "Array", an object without __toString() threw an Error + if (null !== $argument && !\is_scalar($argument) && !$argument instanceof \Stringable) { + throw new UnexpectedValueException(\sprintf('The sprintf transformer expects strings, %s given.', get_debug_type($argument))); + } + } return vsprintf($options['format'], $value); } diff --git a/src/Transformer/String/TrimTransformer.php b/src/Transformer/String/TrimTransformer.php index ff5f675f..93c7cb5e 100644 --- a/src/Transformer/String/TrimTransformer.php +++ b/src/Transformer/String/TrimTransformer.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Transformer\String; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use CleverAge\ProcessBundle\Transformer\InputPolicy; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -35,6 +36,7 @@ public function transform(mixed $value, ?array $options = []): ?string if (null === $value) { return null; } + $value = InputPolicy::toString($value, 'trim'); $charlist = $options['charlist']; // trim() removes bytes: a multibyte character of the list would cut the characters sharing its bytes (ranges @@ -49,10 +51,10 @@ public function transform(mixed $value, ?array $options = []): ?string $charlist ); - return mb_trim((string) $value, $charlist); + return mb_trim($value, $charlist); } - return trim((string) $value, $charlist); + return trim($value, $charlist); } public function configureOptions(OptionsResolver $resolver): void diff --git a/src/Transformer/UnsetTransformer.php b/src/Transformer/UnsetTransformer.php index 208bb4b8..da72ee09 100644 --- a/src/Transformer/UnsetTransformer.php +++ b/src/Transformer/UnsetTransformer.php @@ -36,9 +36,7 @@ public function __construct(PropertyAccessorInterface $accessor) */ public function transform(mixed $value, array $options = []): array { - if (!\is_array($value)) { - throw new UnexpectedValueException('Given value must be an array'); - } + $value = InputPolicy::toArray($value, 'unset'); if (!\array_key_exists($options['property'], $value)) { throw new UnexpectedValueException("Property {$options['property']} does not exists"); diff --git a/tests/Exception/SplExceptionsTest.php b/tests/Exception/SplExceptionsTest.php index 74500847..3e2a75f6 100644 --- a/tests/Exception/SplExceptionsTest.php +++ b/tests/Exception/SplExceptionsTest.php @@ -33,6 +33,7 @@ #[CoversClass(RuntimeException::class)] #[CoversClass(UnexpectedValueException::class)] #[UsesClass(ImplodeTransformer::class)] +#[UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class SplExceptionsTest extends TestCase { /** diff --git a/tests/Fixtures/InputPolicyEnum.php b/tests/Fixtures/InputPolicyEnum.php new file mode 100644 index 00000000..03c5daf2 --- /dev/null +++ b/tests/Fixtures/InputPolicyEnum.php @@ -0,0 +1,22 @@ +, string}> + */ + private const array STRING_TRANSFORMERS = [ + 'convert_value' => [['map' => ['12' => 'twelve'], 'auto_cast' => true], '12'], + 'date_parser' => [['format' => '!Y'], '2024'], + 'explode' => [['delimiter' => '1'], '213'], + 'hash' => [['algo' => 'md5'], '12'], + 'multi_replace' => [['replace_mapping' => ['1' => 'one']], '12'], + 'preg_filter' => [['pattern' => '/1/', 'replacement' => 'one'], '12'], + 'preg_match' => [['pattern' => '/(\d)/'], '12'], + 'slugify' => [[], '12'], + 'trim' => [['charlist' => '1'], '12'], + ]; + + /** + * Array transformers: anything but an array, null included, throws an UnexpectedValueException. + * + * @var array, array}> + */ + private const array ARRAY_TRANSFORMERS = [ + 'array_element' => [['index' => 0], ['a']], + 'array_last' => [[], ['a']], + 'array_unset' => [['key' => 'a'], ['a' => 1]], + 'implode' => [[], ['a', 'b']], + 'instantiate' => [['class' => \ArrayObject::class], []], + 'unset' => [['property' => 'a'], ['a' => 1]], + ]; + + /** + * Transformers with their own contract, out of the policy: any input (callback, cast, default, mapping, rules...), + * an array of arguments (sprintf, evaluator), an iterable (array_filter, array_first, array_map), a date + * (date_format), a DOM node (xpath_evaluator), an array or an object (property_accessor, serializer). + */ + private const array OWN_CONTRACT = [ + 'array_filter', 'array_first', 'array_map', 'cached', 'callback', 'cast', 'constant', 'date_format', 'default', + 'denormalize', 'dump', 'evaluator', 'expression_language_map', 'mapping', 'normalize', 'property_accessor', + 'recursive_property_setter', 'rules', 'sprintf', 'type_setter', 'wrapper', 'xpath_evaluator', + ]; + + public function testEveryTransformerHasAPolicy(): void + { + $codes = $this->getRegistry()->getTransformerCodes(); + $listed = [...array_keys(self::STRING_TRANSFORMERS), ...array_keys(self::ARRAY_TRANSFORMERS), ...self::OWN_CONTRACT]; + sort($codes); + sort($listed); + + self::assertSame($codes, $listed); + } + + /** + * @return iterable + */ + public static function provideStringTransformers(): iterable + { + foreach (array_keys(self::STRING_TRANSFORMERS) as $code) { + yield $code => [$code]; + } + } + + #[DataProvider('provideStringTransformers')] + public function testStringTransformerGivesNullForNull(string $code): void + { + self::assertNull($this->transform($code, self::STRING_TRANSFORMERS[$code][0], null)); + } + + #[DataProvider('provideStringTransformers')] + public function testStringTransformerCastsScalarsAndStringables(string $code): void + { + [$options, $string] = self::STRING_TRANSFORMERS[$code]; + $expected = $this->transform($code, $options, $string); + $stringable = new readonly class($string) implements \Stringable { + public function __construct(private string $value) + { + } + + public function __toString(): string + { + return $this->value; + } + }; + + self::assertNotNull($expected); + self::assertEquals($expected, $this->transform($code, $options, (int) $string)); + self::assertEquals($expected, $this->transform($code, $options, (float) $string)); + self::assertEquals($expected, $this->transform($code, $options, $stringable)); + } + + /** + * @return iterable + */ + public static function provideStringTransformersAndInvalidValues(): iterable + { + foreach (array_keys(self::STRING_TRANSFORMERS) as $code) { + yield "{$code}, array" => [$code, ['a']]; + yield "{$code}, empty array" => [$code, []]; + yield "{$code}, object" => [$code, new \stdClass()]; + yield "{$code}, enum" => [$code, InputPolicyEnum::A]; + } + } + + /** + * No raw TypeError or Error, no "Array to string conversion" warning ("Array" when the PHP errors are not thrown). + */ + #[DataProvider('provideStringTransformersAndInvalidValues')] + public function testStringTransformerRejectsArraysAndObjects(string $code, mixed $value): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage(\sprintf('The %s transformer expects a string, %s given.', $code, get_debug_type($value))); + + $this->transform($code, self::STRING_TRANSFORMERS[$code][0], $value); + } + + /** + * @return iterable + */ + public static function provideArrayTransformersAndInvalidValues(): iterable + { + foreach (array_keys(self::ARRAY_TRANSFORMERS) as $code) { + yield "{$code}, null" => [$code, null]; + yield "{$code}, string" => [$code, 'a']; + yield "{$code}, int" => [$code, 1]; + yield "{$code}, object" => [$code, new \ArrayObject(['a' => 1])]; + } + } + + #[DataProvider('provideArrayTransformersAndInvalidValues')] + public function testArrayTransformerRejectsAnythingButAnArray(string $code, mixed $value): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage(\sprintf('The %s transformer expects an array, %s given.', $code, get_debug_type($value))); + + $this->transform($code, self::ARRAY_TRANSFORMERS[$code][0], $value); + } + + /** + * @return iterable + */ + public static function provideArrayTransformers(): iterable + { + foreach (array_keys(self::ARRAY_TRANSFORMERS) as $code) { + yield $code => [$code]; + } + } + + #[DataProvider('provideArrayTransformers')] + public function testArrayTransformerAcceptsAnArray(string $code): void + { + [$options, $value] = self::ARRAY_TRANSFORMERS[$code]; + + self::assertNotNull($this->transform($code, $options, $value)); + } + + /** + * @param array $options + */ + private function transform(string $code, array $options, mixed $value): mixed + { + $transformer = $this->getRegistry()->getTransformer($code); + if ($transformer instanceof ConfigurableTransformerInterface) { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + $options = $resolver->resolve($options); + } + self::assertInstanceOf(TransformerInterface::class, $transformer); + + return $transformer->transform($value, $options); + } + + protected static function getKernelClass(): string + { + return TestKernel::class; + } + + private function getRegistry(): TransformerRegistry + { + $registry = self::getContainer()->get('test.transformer_registry'); + self::assertInstanceOf(TransformerRegistry::class, $registry); + + return $registry; + } +} diff --git a/tests/Task/TransformerTaskTest.php b/tests/Task/TransformerTaskTest.php index 9c72c0dd..93db76c8 100644 --- a/tests/Task/TransformerTaskTest.php +++ b/tests/Task/TransformerTaskTest.php @@ -51,6 +51,7 @@ #[\PHPUnit\Framework\Attributes\UsesClass(CallbackTransformer::class)] #[\PHPUnit\Framework\Attributes\UsesClass(MappingTransformer::class)] #[\PHPUnit\Framework\Attributes\UsesClass(TrimTransformer::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] #[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Configuration\DidYouMean::class)] class TransformerTaskTest extends TestCase { diff --git a/tests/Transformer/Array/ArrayElementTransformerTest.php b/tests/Transformer/Array/ArrayElementTransformerTest.php index a0418665..e4d32d4c 100644 --- a/tests/Transformer/Array/ArrayElementTransformerTest.php +++ b/tests/Transformer/Array/ArrayElementTransformerTest.php @@ -21,6 +21,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(ArrayElementTransformer::class)] #[\PHPUnit\Framework\Attributes\CoversMethod(ArrayElementTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(ArrayElementTransformer::class, 'configureOptions')] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class ArrayElementTransformerTest extends TestCase { public function testTransformReturnsNthElementFromArray(): void diff --git a/tests/Transformer/Array/ArrayLastTransformerTest.php b/tests/Transformer/Array/ArrayLastTransformerTest.php index d1923d99..0227acbb 100644 --- a/tests/Transformer/Array/ArrayLastTransformerTest.php +++ b/tests/Transformer/Array/ArrayLastTransformerTest.php @@ -13,11 +13,13 @@ namespace CleverAge\ProcessBundle\Tests\Transformer\Array; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\Array\ArrayLastTransformer; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; #[\PHPUnit\Framework\Attributes\CoversClass(ArrayLastTransformer::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class ArrayLastTransformerTest extends TestCase { /** @@ -50,7 +52,9 @@ public function testEmptyArrayReturnsNullWithoutWarning(): void public function testNonArrayInputThrows(): void { - $this->expectException(\TypeError::class); + // A raw TypeError was thrown + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage('The array_last transformer expects an array, string given.'); // @phpstan-ignore method.resultUnused (the call is expected to throw) (new ArrayLastTransformer())->transform('foo'); diff --git a/tests/Transformer/Array/ArrayUnsetTransformerTest.php b/tests/Transformer/Array/ArrayUnsetTransformerTest.php index 33e62876..e105b653 100644 --- a/tests/Transformer/Array/ArrayUnsetTransformerTest.php +++ b/tests/Transformer/Array/ArrayUnsetTransformerTest.php @@ -21,6 +21,7 @@ use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversClass(ArrayUnsetTransformer::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class ArrayUnsetTransformerTest extends TestCase { /** @@ -52,7 +53,7 @@ public function testNonArrayInputThrows(): void $transformer = new ArrayUnsetTransformer(); $this->expectException(\UnexpectedValueException::class); - $this->expectExceptionMessage('Given value is not an array'); + $this->expectExceptionMessage('The array_unset transformer expects an array, ArrayObject given.'); $transformer->transform(new \ArrayObject(['id' => 1]), $this->resolveOptions($transformer, ['key' => 'id'])); } diff --git a/tests/Transformer/ConvertValueTransformerTest.php b/tests/Transformer/ConvertValueTransformerTest.php index 763ffa9f..26ba9cce 100644 --- a/tests/Transformer/ConvertValueTransformerTest.php +++ b/tests/Transformer/ConvertValueTransformerTest.php @@ -21,6 +21,7 @@ use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversClass(ConvertValueTransformer::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class ConvertValueTransformerTest extends TestCase { private const array MAP = [ @@ -85,9 +86,9 @@ public function testKeepMissingTakesPrecedenceOverIgnoreMissing(): void */ public static function invalidKeyProvider(): iterable { - yield 'float' => [1.5, 'double']; - yield 'bool' => [true, 'boolean']; - yield 'object' => [new \stdClass(), 'object']; + yield 'float' => [1.5, 'float']; + yield 'bool' => [true, 'bool']; + yield 'object' => [new \stdClass(), 'stdClass']; yield 'array' => [['TEXTE'], 'array']; } @@ -133,7 +134,7 @@ public function testAutoCastKeepsTheInputWhenMissing(): void public function testArrayIsRejectedEvenWithAutoCast(): void { $this->expectException(\UnexpectedValueException::class); - $this->expectExceptionMessage("Unexpected input of type 'array' in convert_value transformer"); + $this->expectExceptionMessage('The convert_value transformer expects a string, array given.'); $this->transform(['TEXTE'], ['auto_cast' => true]); } diff --git a/tests/Transformer/Date/DateParserTransformerTest.php b/tests/Transformer/Date/DateParserTransformerTest.php index 09142c09..c7705710 100644 --- a/tests/Transformer/Date/DateParserTransformerTest.php +++ b/tests/Transformer/Date/DateParserTransformerTest.php @@ -21,6 +21,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(DateParserTransformer::class)] #[\PHPUnit\Framework\Attributes\CoversMethod(DateParserTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(DateParserTransformer::class, 'configureOptions')] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class DateParserTransformerTest extends TestCase { public function testTransformValidDate(): void diff --git a/tests/Transformer/InputPolicyTest.php b/tests/Transformer/InputPolicyTest.php new file mode 100644 index 00000000..515dae3f --- /dev/null +++ b/tests/Transformer/InputPolicyTest.php @@ -0,0 +1,81 @@ + + */ + public static function provideStrings(): iterable + { + yield 'string' => ['a', 'a']; + yield 'empty string' => ['', '']; + yield 'int' => [12, '12']; + yield 'float' => [1.5, '1.5']; + yield 'true' => [true, '1']; + yield 'false' => [false, '']; + yield 'stringable' => [new class implements \Stringable { + public function __toString(): string + { + return 'b'; + } + }, 'b']; + } + + #[DataProvider('provideStrings')] + public function testToString(mixed $value, string $expected): void + { + self::assertSame($expected, InputPolicy::toString($value, 'code')); + } + + /** + * @return iterable + */ + public static function provideInvalidStrings(): iterable + { + yield 'null' => [null, 'null']; + yield 'array' => [['a'], 'array']; + yield 'object' => [new \stdClass(), 'stdClass']; + } + + #[DataProvider('provideInvalidStrings')] + public function testToStringRejects(mixed $value, string $type): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage("The code transformer expects a string, {$type} given."); + + InputPolicy::toString($value, 'code'); + } + + public function testToArray(): void + { + self::assertSame(['a' => 1], InputPolicy::toArray(['a' => 1], 'code')); + } + + public function testToArrayRejects(): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage('The code transformer expects an array, null given.'); + + InputPolicy::toArray(null, 'code'); + } +} diff --git a/tests/Transformer/MultiReplaceTransformerTest.php b/tests/Transformer/MultiReplaceTransformerTest.php index 262fbf5d..74895bce 100644 --- a/tests/Transformer/MultiReplaceTransformerTest.php +++ b/tests/Transformer/MultiReplaceTransformerTest.php @@ -21,6 +21,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(MultiReplaceTransformer::class)] #[\PHPUnit\Framework\Attributes\CoversMethod(MultiReplaceTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(MultiReplaceTransformer::class, 'configureOptions')] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class MultiReplaceTransformerTest extends TestCase { public function testTransform(): void @@ -65,7 +66,7 @@ public function testTransformWithNullValue(): void $transformedValue = $transformer->transform($value, $options); - $this->assertEquals('', $transformedValue); + $this->assertNull($transformedValue); } public function testConfigureOptions(): void diff --git a/tests/Transformer/Object/InstantiateTransformerTest.php b/tests/Transformer/Object/InstantiateTransformerTest.php index e94fb584..adbdc648 100644 --- a/tests/Transformer/Object/InstantiateTransformerTest.php +++ b/tests/Transformer/Object/InstantiateTransformerTest.php @@ -20,6 +20,7 @@ use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversClass(InstantiateTransformer::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class InstantiateTransformerTest extends TestCase { public function testListIsPassedAsPositionalArguments(): void @@ -69,7 +70,7 @@ public function testNonArrayInputThrows(): void $options = $this->resolveOptions($transformer, ['class' => \ArrayObject::class]); $this->expectException(\UnexpectedValueException::class); - $this->expectExceptionMessage('Input value must be an array for transformer instantiate'); + $this->expectExceptionMessage('The instantiate transformer expects an array, string given.'); $transformer->transform('foo', $options); } diff --git a/tests/Transformer/PregFilterTransformerTest.php b/tests/Transformer/PregFilterTransformerTest.php index d525263b..9f985046 100644 --- a/tests/Transformer/PregFilterTransformerTest.php +++ b/tests/Transformer/PregFilterTransformerTest.php @@ -22,6 +22,7 @@ #[\PHPUnit\Framework\Attributes\CoversMethod(PregFilterTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(PregFilterTransformer::class, 'configureOptions')] #[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\Regex::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class PregFilterTransformerTest extends TestCase { public function testTransformWithStringReplacement(): void diff --git a/tests/Transformer/String/ExplodeTransformerTest.php b/tests/Transformer/String/ExplodeTransformerTest.php index 6ec867f0..aa87db07 100644 --- a/tests/Transformer/String/ExplodeTransformerTest.php +++ b/tests/Transformer/String/ExplodeTransformerTest.php @@ -21,6 +21,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(ExplodeTransformer::class)] #[\PHPUnit\Framework\Attributes\CoversMethod(ExplodeTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(ExplodeTransformer::class, 'configureOptions')] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class ExplodeTransformerTest extends TestCase { public function testTransform(): void @@ -45,9 +46,8 @@ public function testTransformWithNullValue(): void { $transformer = new ExplodeTransformer(); - $result = $transformer->transform(null, ['delimiter' => ',']); - - $this->assertEquals([], $result); + $this->assertNull($transformer->transform(null, ['delimiter' => ','])); + $this->assertSame([], $transformer->transform('', ['delimiter' => ','])); } public function testConfigureOptions(): void diff --git a/tests/Transformer/String/HashTransformerTest.php b/tests/Transformer/String/HashTransformerTest.php index d546c635..9ef13903 100644 --- a/tests/Transformer/String/HashTransformerTest.php +++ b/tests/Transformer/String/HashTransformerTest.php @@ -22,6 +22,7 @@ use Symfony\Component\OptionsResolver\OptionsResolver; #[CoversClass(HashTransformer::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class HashTransformerTest extends TestCase { public function testTransform(): void @@ -30,7 +31,8 @@ public function testTransform(): void $this->assertSame(md5('value'), $transformer->transform('value', $this->resolve(['algo' => 'md5']))); $this->assertSame(md5('12'), $transformer->transform(12, $this->resolve(['algo' => 'md5']))); - $this->assertSame(md5(''), $transformer->transform(null, $this->resolve(['algo' => 'md5']))); + // null is not hashed as "": the same hash for every missing value + $this->assertNull($transformer->transform(null, $this->resolve(['algo' => 'md5']))); $this->assertSame(hash('sha256', 'value', true), $transformer->transform('value', $this->resolve(['algo' => 'sha256', 'raw_output' => true]))); $stringable = new class implements \Stringable { public function __toString(): string diff --git a/tests/Transformer/String/ImplodeTransformerTest.php b/tests/Transformer/String/ImplodeTransformerTest.php index 9f1e7dc5..30ae514a 100644 --- a/tests/Transformer/String/ImplodeTransformerTest.php +++ b/tests/Transformer/String/ImplodeTransformerTest.php @@ -13,13 +13,17 @@ namespace CleverAge\ProcessBundle\Tests\Transformer\String; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; +use CleverAge\ProcessBundle\Tests\Fixtures\InputPolicyEnum; use CleverAge\ProcessBundle\Transformer\String\ImplodeTransformer; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversClass(ImplodeTransformer::class)] #[\PHPUnit\Framework\Attributes\CoversMethod(ImplodeTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(ImplodeTransformer::class, 'configureOptions')] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class ImplodeTransformerTest extends TestCase { public function testTransform(): void @@ -40,6 +44,28 @@ public function testTransformWithInvalidValue(): void $transformer->transform('invalid_value', ['separator' => ',']); } + /** + * @return iterable + */ + public static function provideInvalidItems(): iterable + { + yield 'array item' => [['a'], 'array']; + yield 'object item' => [new \stdClass(), 'stdClass']; + yield 'enum item' => [InputPolicyEnum::A, InputPolicyEnum::class]; + } + + /** + * An array item was imploded as "Array" with a warning, an object without __toString() threw an Error (#405). + */ + #[DataProvider('provideInvalidItems')] + public function testInvalidItemIsRejected(mixed $item, string $type): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage("The implode transformer expects an array of strings, {$type} item given."); + + (new ImplodeTransformer())->transform(['a', $item], ['separator' => ',']); + } + public function testTransformWithDefaultSeparator(): void { $transformer = new ImplodeTransformer(); diff --git a/tests/Transformer/String/PregMatchTransformerTest.php b/tests/Transformer/String/PregMatchTransformerTest.php index 88c3f686..b860619c 100644 --- a/tests/Transformer/String/PregMatchTransformerTest.php +++ b/tests/Transformer/String/PregMatchTransformerTest.php @@ -22,6 +22,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(PregMatchTransformer::class)] #[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\Regex::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class PregMatchTransformerTest extends TestCase { /** diff --git a/tests/Transformer/String/SlugifyTransformerTest.php b/tests/Transformer/String/SlugifyTransformerTest.php index e86f2910..81d1f301 100644 --- a/tests/Transformer/String/SlugifyTransformerTest.php +++ b/tests/Transformer/String/SlugifyTransformerTest.php @@ -22,6 +22,7 @@ #[\PHPUnit\Framework\Attributes\CoversMethod(SlugifyTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(SlugifyTransformer::class, 'configureOptions')] #[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\Regex::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class SlugifyTransformerTest extends TestCase { public function testTransformWithDefaultOptions(): void @@ -168,12 +169,18 @@ public function __toString(): string $this->assertSame('helene', $transformer->transform($stringable, $options)); } + public function testNullValue(): void + { + $transformer = new SlugifyTransformer(); + + $this->assertNull($transformer->transform(null, $this->resolveOptions($transformer))); + } + /** * @return iterable */ public static function provideInvalidValues(): iterable { - yield 'null' => [null]; yield 'array' => [['a']]; yield 'object' => [new \stdClass()]; } diff --git a/tests/Transformer/String/SprintfTransformerTest.php b/tests/Transformer/String/SprintfTransformerTest.php index 3fca8c11..11d0b6c1 100644 --- a/tests/Transformer/String/SprintfTransformerTest.php +++ b/tests/Transformer/String/SprintfTransformerTest.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Tests\Transformer\String; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; +use CleverAge\ProcessBundle\Tests\Fixtures\InputPolicyEnum; use CleverAge\ProcessBundle\Transformer\String\SprintfTransformer; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -82,4 +84,27 @@ public function testWidthArgument(): void $this->assertSame(' 42', $transformer->transform([5, 42], $resolver->resolve(['format' => '%*d']))); } + + /** + * @return iterable + */ + public static function provideInvalidArguments(): iterable + { + yield 'array argument' => [[['a']], 'array']; + yield 'object argument' => [[new \stdClass()], 'stdClass']; + yield 'object' => [new \stdClass(), 'stdClass']; + yield 'enum' => [InputPolicyEnum::A, InputPolicyEnum::class]; + } + + /** + * An array was formatted as "Array" with a warning, an object without __toString() threw an Error (#405). + */ + #[DataProvider('provideInvalidArguments')] + public function testInvalidArgumentIsRejected(mixed $value, string $type): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage("The sprintf transformer expects strings, {$type} given."); + + (new SprintfTransformer())->transform($value, ['format' => '%s']); + } } diff --git a/tests/Transformer/String/TrimTransformerTest.php b/tests/Transformer/String/TrimTransformerTest.php index 0e5a696e..b31aaace 100644 --- a/tests/Transformer/String/TrimTransformerTest.php +++ b/tests/Transformer/String/TrimTransformerTest.php @@ -20,6 +20,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(TrimTransformer::class)] #[\PHPUnit\Framework\Attributes\CoversMethod(TrimTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(TrimTransformer::class, 'configureOptions')] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class TrimTransformerTest extends TestCase { public function testTransformTrimsStringWithDefaultCharlist(): void diff --git a/tests/Transformer/TransformerTraitTest.php b/tests/Transformer/TransformerTraitTest.php index 1a97270f..09f8990c 100644 --- a/tests/Transformer/TransformerTraitTest.php +++ b/tests/Transformer/TransformerTraitTest.php @@ -27,6 +27,7 @@ #[\PHPUnit\Framework\Attributes\UsesClass(TransformerRegistry::class)] #[\PHPUnit\Framework\Attributes\UsesClass(CallbackTransformer::class)] #[\PHPUnit\Framework\Attributes\UsesClass(TrimTransformer::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] #[\PHPUnit\Framework\Attributes\UsesClass(MissingTransformerException::class)] #[\PHPUnit\Framework\Attributes\UsesClass(TransformerException::class)] #[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Configuration\DidYouMean::class)] diff --git a/tests/Transformer/UnsetTransformerTest.php b/tests/Transformer/UnsetTransformerTest.php index 7d267647..97315a94 100644 --- a/tests/Transformer/UnsetTransformerTest.php +++ b/tests/Transformer/UnsetTransformerTest.php @@ -26,6 +26,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(UnsetTransformer::class)] #[\PHPUnit\Framework\Attributes\UsesTrait(ConditionTrait::class)] #[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\Regex::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(\CleverAge\ProcessBundle\Transformer\InputPolicy::class)] class UnsetTransformerTest extends TestCase { private const array INPUT = [ @@ -88,7 +89,7 @@ public function testNonArrayInputThrows(): void $options = $this->resolveOptions($transformer, ['property' => 'to_unset']); $this->expectException(\UnexpectedValueException::class); - $this->expectExceptionMessage('Given value must be an array'); + $this->expectExceptionMessage('The unset transformer expects an array, string given.'); $transformer->transform('not an array', $options); }