From badce35193f7dbee6cd0b4202709805ebd1e14a9 Mon Sep 17 00:00:00 2001 From: Nicolas Joubert Date: Tue, 3 Nov 2026 10:40:25 +0100 Subject: [PATCH] #398 - Transformers edge cases: trim with a multibyte charlist, convert_value keep_missing, numeric keys of multi_replace and conditions, hash of an array, options validated with the configuration Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/reference/traits/condition_trait.md | 7 ++ .../transformers/explode_transformer.md | 2 +- .../transformers/hash_transformer.md | 3 +- .../transformers/instantiate_transformer.md | 2 +- .../transformers/multi_replace_transformer.md | 2 +- .../transformers/sprintf_transformer.md | 3 +- .../transformers/trim_transformer.md | 2 +- src/Transformer/ConditionTrait.php | 28 ++++-- src/Transformer/ConvertValueTransformer.php | 4 +- src/Transformer/MultiReplaceTransformer.php | 16 +++- .../Object/InstantiateTransformer.php | 2 + src/Transformer/String/ExplodeTransformer.php | 2 + src/Transformer/String/HashTransformer.php | 6 ++ src/Transformer/String/SprintfTransformer.php | 17 +++- src/Transformer/String/TrimTransformer.php | 9 +- tests/Task/FilterTaskTest.php | 21 +++++ .../ConvertValueTransformerTest.php | 7 +- .../MultiReplaceTransformerTest.php | 22 +++++ .../Object/InstantiateTransformerTest.php | 10 +-- .../String/ExplodeTransformerTest.php | 10 +++ .../String/HashTransformerTest.php | 85 +++++++++++++++++++ .../String/SprintfTransformerTest.php | 37 ++++++++ .../String/TrimTransformerTest.php | 14 +++ 24 files changed, 287 insertions(+), 25 deletions(-) create mode 100644 tests/Transformer/String/HashTransformerTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 73519523..f98cdf29 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 +* [#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. * [#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/traits/condition_trait.md b/docs/reference/traits/condition_trait.md index c680b2d9..f818e04b 100644 --- a/docs/reference/traits/condition_trait.md +++ b/docs/reference/traits/condition_trait.md @@ -64,6 +64,13 @@ empty: '[deleted_at]': ~ ``` +Or, with the list form of `empty` and `not_empty`: + +```yaml +not_empty: ['[email]'] +empty: ['[deleted_at]'] +``` + * Regular expressions, on an object input ```yaml diff --git a/docs/reference/transformers/explode_transformer.md b/docs/reference/transformers/explode_transformer.md index 926bfe89..3275a879 100644 --- a/docs/reference/transformers/explode_transformer.md +++ b/docs/reference/transformers/explode_transformer.md @@ -24,7 +24,7 @@ Options | Code | Type | Required | Default | Description | |-------------|----------|:--------:|---------|---------------------------------------------| -| `delimiter` | `string` | **X** | | The boundary string, must not be empty | +| `delimiter` | `string` | **X** | | The boundary string, must not be empty (checked with the configuration) | Examples -------- diff --git a/docs/reference/transformers/hash_transformer.md b/docs/reference/transformers/hash_transformer.md index f0f85ed3..d3473f98 100644 --- a/docs/reference/transformers/hash_transformer.md +++ b/docs/reference/transformers/hash_transformer.md @@ -12,7 +12,8 @@ Transformer reference Accepted inputs --------------- -Any value that can be cast to `string`. +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`). Possible outputs ---------------- diff --git a/docs/reference/transformers/instantiate_transformer.md b/docs/reference/transformers/instantiate_transformer.md index c01410ea..ee2d8648 100644 --- a/docs/reference/transformers/instantiate_transformer.md +++ b/docs/reference/transformers/instantiate_transformer.md @@ -26,7 +26,7 @@ Options | Code | Type | Required | Default | Description | |---------|----------|:--------:|---------|--------------------------------------------| -| `class` | `string` | **X** | | Fully qualified class name to instantiate | +| `class` | `string` | **X** | | Fully qualified class name to instantiate, must exist (checked with the configuration) | Examples -------- diff --git a/docs/reference/transformers/multi_replace_transformer.md b/docs/reference/transformers/multi_replace_transformer.md index cead0494..307beb89 100644 --- a/docs/reference/transformers/multi_replace_transformer.md +++ b/docs/reference/transformers/multi_replace_transformer.md @@ -26,7 +26,7 @@ Options | Code | Type | Required | Default | Description | |-------------------|---------|:--------:|---------|------------------------------------------------------------------------------------------| -| `replace_mapping` | `array` | **X** | | Searched string as key, replacement as value. Entries are applied sequentially, in order | +| `replace_mapping` | `array` | **X** | | Searched string as key, replacement as value (a string or a scalar, cast to string; checked with the configuration). Entries are applied sequentially, in order | Examples -------- diff --git a/docs/reference/transformers/sprintf_transformer.md b/docs/reference/transformers/sprintf_transformer.md index 81ec6b4c..0d31af09 100644 --- a/docs/reference/transformers/sprintf_transformer.md +++ b/docs/reference/transformers/sprintf_transformer.md @@ -66,4 +66,5 @@ Notes ----- In Symfony YAML configuration files, `%` is used for container parameters: escape it as `%%` (`'%%s'` is resolved as -`'%s'`). A format with more placeholders than arguments throws a `\ValueError`. +`'%s'`). An invalid format (e.g. a `%` alone, not escaped as `%%`) is rejected with the configuration. A format with +more placeholders than arguments throws an `\ArgumentCountError`, with the value. diff --git a/docs/reference/transformers/trim_transformer.md b/docs/reference/transformers/trim_transformer.md index 3b24732c..5740542b 100644 --- a/docs/reference/transformers/trim_transformer.md +++ b/docs/reference/transformers/trim_transformer.md @@ -26,7 +26,7 @@ Options | Code | Type | Required | Default | Description | |------------|----------|:--------:|---------------------|----------------------------------------------------------------| -| `charlist` | `string` | | `" \t\n\r\0\x0B"` | Characters to strip (ranges like `a..z` are supported) | +| `charlist` | `string` | | `" \t\n\r\0\x0B"` | Characters to strip (ranges like `a..z` are supported, for single-byte characters only); multibyte characters (e.g. `é`, `«`) are supported, with `mb_trim()` | Examples -------- diff --git a/src/Transformer/ConditionTrait.php b/src/Transformer/ConditionTrait.php index a6666a5b..b7bebc9c 100644 --- a/src/Transformer/ConditionTrait.php +++ b/src/Transformer/ConditionTrait.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer; +use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -33,37 +34,37 @@ trait ConditionTrait protected function checkCondition(mixed $input, array $conditions): bool { foreach ($conditions['match'] as $key => $value) { - if (!$this->checkValue($input, $key, $value)) { + if (!$this->checkValue($input, (string) $key, $value)) { return false; } } foreach ($conditions['empty'] as $key => $value) { - if (!$this->checkEmpty($input, $key)) { + if (!$this->checkEmpty($input, (string) $key)) { return false; } } foreach ($conditions['match_regexp'] as $key => $value) { - if (!$this->checkValue($input, $key, $value, true, true)) { + if (!$this->checkValue($input, (string) $key, $value, true, true)) { return false; } } foreach ($conditions['not_match'] as $key => $value) { - if (!$this->checkValue($input, $key, $value, false)) { + if (!$this->checkValue($input, (string) $key, $value, false)) { return false; } } foreach ($conditions['not_empty'] as $key => $value) { - if ($this->checkEmpty($input, $key)) { + if ($this->checkEmpty($input, (string) $key)) { return false; } } foreach ($conditions['not_match_regexp'] as $key => $value) { - if (!$this->checkValue($input, $key, $value, false, true)) { + if (!$this->checkValue($input, (string) $key, $value, false, true)) { return false; } } @@ -106,6 +107,21 @@ protected function configureConditionOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('empty', 'array'); $resolver->setAllowedTypes('not_match_regexp', 'array'); $resolver->setAllowedTypes('match_regexp', 'array'); + // The list form of empty / not_empty (e.g. not_empty: ['[email]']): the values are the property paths + foreach (['empty', 'not_empty'] as $option) { + $resolver->setNormalizer($option, static function (Options $options, array $value): array { + $conditions = []; + foreach ($value as $key => $path) { + if (\is_int($key) && \is_string($path)) { + $conditions[$path] = null; + } else { + $conditions[$key] = $path; + } + } + + return $conditions; + }); + } } /** diff --git a/src/Transformer/ConvertValueTransformer.php b/src/Transformer/ConvertValueTransformer.php index 4d5e6df9..a680909b 100644 --- a/src/Transformer/ConvertValueTransformer.php +++ b/src/Transformer/ConvertValueTransformer.php @@ -34,6 +34,7 @@ public function transform(mixed $value, array $options = []): mixed return null; } + $input = $value; if (!\is_string($value) && !\is_int($value)) { // If not a valid array index if (!$options['auto_cast']) { $type = \gettype($value); @@ -47,7 +48,8 @@ public function transform(mixed $value, array $options = []): mixed if (!\array_key_exists($value, $options['map'])) { if ($options['keep_missing']) { - return $value; + // The input itself, not its value cast by auto_cast + return $input; } if (!$options['ignore_missing']) { throw new UnexpectedValueException("Missing value in map '{$value}'"); diff --git a/src/Transformer/MultiReplaceTransformer.php b/src/Transformer/MultiReplaceTransformer.php index 8c352dee..26a77b6a 100644 --- a/src/Transformer/MultiReplaceTransformer.php +++ b/src/Transformer/MultiReplaceTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -32,7 +33,8 @@ class MultiReplaceTransformer implements ConfigurableTransformerInterface public function transform(mixed $value, array $options = []): mixed { foreach ($options['replace_mapping'] as $pattern => $replacement) { - $value = str_replace($pattern, $replacement, (string) $value); + // A numeric key of the mapping is an int + $value = str_replace((string) $pattern, (string) $replacement, (string) $value); } return $value; @@ -42,6 +44,18 @@ public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired('replace_mapping'); $resolver->setAllowedTypes('replace_mapping', 'array'); + $resolver->setAllowedValues( + 'replace_mapping', + static function (array $mapping): bool { + foreach ($mapping as $replacement) { + if (null !== $replacement && !\is_scalar($replacement)) { + throw new InvalidOptionsException(\sprintf('The replacements of the "replace_mapping" option must be strings, %s given.', get_debug_type($replacement))); + } + } + + return true; + } + ); } public function getCode(): string diff --git a/src/Transformer/Object/InstantiateTransformer.php b/src/Transformer/Object/InstantiateTransformer.php index 2d7eb785..6a598f6a 100644 --- a/src/Transformer/Object/InstantiateTransformer.php +++ b/src/Transformer/Object/InstantiateTransformer.php @@ -40,6 +40,8 @@ public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired(['class']); $resolver->setAllowedTypes('class', ['string']); + // Rejected with the configuration, not with the first value + $resolver->setAllowedValues('class', static fn (string $class): bool => class_exists($class)); } public function getCode(): string diff --git a/src/Transformer/String/ExplodeTransformer.php b/src/Transformer/String/ExplodeTransformer.php index 0c2021c0..e9ea59e1 100644 --- a/src/Transformer/String/ExplodeTransformer.php +++ b/src/Transformer/String/ExplodeTransformer.php @@ -49,5 +49,7 @@ public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired(['delimiter']); $resolver->setAllowedTypes('delimiter', ['string']); + // explode() fails on an empty delimiter: rejected with the configuration, not with the first value + $resolver->setAllowedValues('delimiter', static fn (string $delimiter): bool => '' !== $delimiter); } } diff --git a/src/Transformer/String/HashTransformer.php b/src/Transformer/String/HashTransformer.php index 4ad919a2..6850c545 100644 --- a/src/Transformer/String/HashTransformer.php +++ b/src/Transformer/String/HashTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\String; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -39,6 +40,11 @@ public function configureOptions(OptionsResolver $resolver): void */ 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))); + } + return hash((string) $options['algo'], (string) $value, $options['raw_output']); } diff --git a/src/Transformer/String/SprintfTransformer.php b/src/Transformer/String/SprintfTransformer.php index 3b015248..c7044ff4 100644 --- a/src/Transformer/String/SprintfTransformer.php +++ b/src/Transformer/String/SprintfTransformer.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Transformer\String; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -40,12 +41,22 @@ public function getCode(): string return 'sprintf'; } - /** - * @codeCoverageIgnore - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('format', '%s'); $resolver->setAllowedTypes('format', 'string'); + // An invalid format (e.g. a "%" alone) is rejected with the configuration, not with the first value + $resolver->setAllowedValues('format', static function (string $format): bool { + // Enough arguments for every conversion specification, positional ones included + preg_match_all('/%(\d+)\$/', $format, $positions); + $count = max([substr_count($format, '%'), ...array_map(intval(...), $positions[1])]) + 1; + try { + vsprintf($format, array_fill(0, $count, '')); + } catch (\ValueError $error) { + throw new InvalidOptionsException(\sprintf('Invalid "format" option "%s": %s', $format, $error->getMessage()), 0, $error); + } + + return true; + }); } } diff --git a/src/Transformer/String/TrimTransformer.php b/src/Transformer/String/TrimTransformer.php index 8421a0fa..2ed86cb3 100644 --- a/src/Transformer/String/TrimTransformer.php +++ b/src/Transformer/String/TrimTransformer.php @@ -38,7 +38,14 @@ public function transform(mixed $value, ?array $options = []): ?string return null; } - return trim((string) $value, $options['charlist']); + $charlist = $options['charlist']; + // trim() removes bytes: a multibyte character of the list would cut the characters sharing its bytes (ranges + // with ".." are only supported for single-byte characters) + if (1 === preg_match('/[\x80-\xff]/', $charlist)) { + return mb_trim((string) $value, $charlist); + } + + return trim((string) $value, $charlist); } /** diff --git a/tests/Task/FilterTaskTest.php b/tests/Task/FilterTaskTest.php index 761df166..12fcef91 100644 --- a/tests/Task/FilterTaskTest.php +++ b/tests/Task/FilterTaskTest.php @@ -179,4 +179,25 @@ private function execute(array $options, mixed $input): ProcessState return $state; } + + /** + * A numeric property path (e.g. a list input) is an int key: a TypeError was thrown. + */ + public function testNumericPropertyPaths(): void + { + // The path "1" is not readable on an array (unlike "[1]"): null + $this->assertFalse($this->execute(['match' => [1 => null, '[1]' => 'b']], ['a', 'b'])->isSkipped()); + $this->assertTrue($this->execute(['match' => [0 => 'x']], ['a', 'b'])->isSkipped()); + $this->assertTrue($this->execute(['not_empty' => [0 => null]], ['a'])->isSkipped()); + } + + /** + * The list form of empty / not_empty: the values are the property paths (a TypeError was thrown). + */ + public function testListFormOfEmptyAndNotEmpty(): void + { + $this->assertFalse($this->execute(['not_empty' => ['[email]'], 'empty' => ['[deleted_at]']], ['email' => 'a@b.c'])->isSkipped()); + $this->assertTrue($this->execute(['not_empty' => ['[email]']], ['email' => ''])->isSkipped()); + $this->assertTrue($this->execute(['empty' => ['[deleted_at]']], ['deleted_at' => 'yesterday'])->isSkipped()); + } } diff --git a/tests/Transformer/ConvertValueTransformerTest.php b/tests/Transformer/ConvertValueTransformerTest.php index d424a791..96c5406e 100644 --- a/tests/Transformer/ConvertValueTransformerTest.php +++ b/tests/Transformer/ConvertValueTransformerTest.php @@ -122,9 +122,12 @@ public function testAutoCastConvertsInvalidKeyToString(mixed $value, mixed $expe self::assertSame($expected, $this->transform($value, ['auto_cast' => true])); } - public function testAutoCastKeepsCastValueWhenMissing(): void + /** + * The input itself, as documented, not its value cast by auto_cast. + */ + public function testAutoCastKeepsTheInputWhenMissing(): void { - self::assertSame('2.5', $this->transform(2.5, ['auto_cast' => true, 'keep_missing' => true])); + self::assertSame(2.5, $this->transform(2.5, ['auto_cast' => true, 'keep_missing' => true])); } public function testArrayIsRejectedEvenWithAutoCast(): void diff --git a/tests/Transformer/MultiReplaceTransformerTest.php b/tests/Transformer/MultiReplaceTransformerTest.php index 158efe1f..7a8ff265 100644 --- a/tests/Transformer/MultiReplaceTransformerTest.php +++ b/tests/Transformer/MultiReplaceTransformerTest.php @@ -15,6 +15,7 @@ use CleverAge\ProcessBundle\Transformer\MultiReplaceTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversClass(MultiReplaceTransformer::class)] @@ -90,4 +91,25 @@ public function testGetCodeReturnsCorrectCode(): void $this->assertEquals('multi_replace', $code); } + + /** + * A numeric key of the mapping is an int: str_replace() threw a TypeError. + */ + public function testTransformWithNumericKeys(): void + { + $transformer = new MultiReplaceTransformer(); + + $this->assertSame('one ten', $transformer->transform('1 10', ['replace_mapping' => ['10' => 'ten', '1' => 'one', 2 => 3]])); + } + + public function testAReplacementMustBeAString(): void + { + $resolver = new OptionsResolver(); + (new MultiReplaceTransformer())->configureOptions($resolver); + + $this->assertSame(['a' => 1, 'b' => null], $resolver->resolve(['replace_mapping' => ['a' => 1, 'b' => null]])['replace_mapping']); + $this->expectException(InvalidOptionsException::class); + $this->expectExceptionMessage('The replacements of the "replace_mapping" option must be strings, array given.'); + $resolver->resolve(['replace_mapping' => ['a' => ['b']]]); + } } diff --git a/tests/Transformer/Object/InstantiateTransformerTest.php b/tests/Transformer/Object/InstantiateTransformerTest.php index 53336787..fb4d5328 100644 --- a/tests/Transformer/Object/InstantiateTransformerTest.php +++ b/tests/Transformer/Object/InstantiateTransformerTest.php @@ -79,14 +79,14 @@ public function testNonArrayInputThrows(): void $transformer->transform('foo', $options); } + /** + * Rejected with the configuration: it was only detected with the first value. + */ public function testUnknownClassThrows(): void { - $transformer = new InstantiateTransformer(); - $options = $this->resolveOptions($transformer, ['class' => 'App\Unknown\Foo']); - - $this->expectException(\ReflectionException::class); + $this->expectException(InvalidOptionsException::class); - $transformer->transform([], $options); + $this->resolveOptions(new InstantiateTransformer(), ['class' => 'App\Unknown\Foo']); } public function testClassIsRequired(): void diff --git a/tests/Transformer/String/ExplodeTransformerTest.php b/tests/Transformer/String/ExplodeTransformerTest.php index 41b4afd3..c08f8e52 100644 --- a/tests/Transformer/String/ExplodeTransformerTest.php +++ b/tests/Transformer/String/ExplodeTransformerTest.php @@ -15,6 +15,7 @@ use CleverAge\ProcessBundle\Transformer\String\ExplodeTransformer; use PHPUnit\Framework\TestCase; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversClass(ExplodeTransformer::class)] @@ -72,4 +73,13 @@ public function testConfigureOptions(): void $resolvedOptions = $resolver->resolve(); $this->assertEquals(['delimiter'], array_keys($resolvedOptions)); } + + public function testAnEmptyDelimiterIsRejected(): void + { + $resolver = new OptionsResolver(); + (new ExplodeTransformer())->configureOptions($resolver); + + $this->expectException(InvalidOptionsException::class); + $resolver->resolve(['delimiter' => '']); + } } diff --git a/tests/Transformer/String/HashTransformerTest.php b/tests/Transformer/String/HashTransformerTest.php new file mode 100644 index 00000000..aac7d2cb --- /dev/null +++ b/tests/Transformer/String/HashTransformerTest.php @@ -0,0 +1,85 @@ +assertSame('hash', $transformer->getCode()); + $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']))); + $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 + { + return 'value'; + } + }; + $this->assertSame(md5('value'), $transformer->transform($stringable, $this->resolve(['algo' => 'md5']))); + } + + /** + * @return iterable + */ + public static function provideInvalidValues(): iterable + { + yield 'array' => [['a']]; + yield 'object' => [new \stdClass()]; + } + + /** + * An array was hashed as the string "Array": the same hash for every array. + */ + #[DataProvider('provideInvalidValues')] + public function testInvalidValue(mixed $value): void + { + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage('The hash transformer expects a string, '.get_debug_type($value).' given.'); + + (new HashTransformer())->transform($value, $this->resolve(['algo' => 'md5'])); + } + + public function testUnknownAlgorithm(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolve(['algo' => 'unknown']); + } + + /** + * @param array $options + * + * @return array + */ + private function resolve(array $options): array + { + $resolver = new OptionsResolver(); + (new HashTransformer())->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/String/SprintfTransformerTest.php b/tests/Transformer/String/SprintfTransformerTest.php index af8100da..d7d04133 100644 --- a/tests/Transformer/String/SprintfTransformerTest.php +++ b/tests/Transformer/String/SprintfTransformerTest.php @@ -14,11 +14,15 @@ namespace CleverAge\ProcessBundle\Tests\Transformer\String; use CleverAge\ProcessBundle\Transformer\String\SprintfTransformer; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversClass(SprintfTransformer::class)] #[\PHPUnit\Framework\Attributes\CoversMethod(SprintfTransformer::class, 'transform')] #[\PHPUnit\Framework\Attributes\CoversMethod(SprintfTransformer::class, 'getCode')] +#[\PHPUnit\Framework\Attributes\CoversMethod(SprintfTransformer::class, 'configureOptions')] class SprintfTransformerTest extends TestCase { public function testTransform(): void @@ -37,4 +41,37 @@ public function testCode(): void $result = $trimTransformer->getCode(); $this->assertEquals('sprintf', $result); } + + /** + * @return iterable + */ + public static function provideValidFormats(): iterable + { + yield 'default' => ['%s']; + yield 'several' => ['%s-%d-%.2f %%']; + yield 'positional' => ['%3$s %1$s']; + yield 'no specification' => ['text']; + } + + #[DataProvider('provideValidFormats')] + public function testValidFormats(string $format): void + { + $resolver = new OptionsResolver(); + (new SprintfTransformer())->configureOptions($resolver); + + $this->assertSame($format, $resolver->resolve(['format' => $format])['format']); + } + + /** + * An invalid format was only detected with the first value. + */ + public function testAnInvalidFormatIsRejected(): void + { + $resolver = new OptionsResolver(); + (new SprintfTransformer())->configureOptions($resolver); + + $this->expectException(InvalidOptionsException::class); + $this->expectExceptionMessage('Invalid "format" option "50%": Missing format specifier at end of string'); + $resolver->resolve(['format' => '50%']); + } } diff --git a/tests/Transformer/String/TrimTransformerTest.php b/tests/Transformer/String/TrimTransformerTest.php index 962fdacf..b830e61b 100644 --- a/tests/Transformer/String/TrimTransformerTest.php +++ b/tests/Transformer/String/TrimTransformerTest.php @@ -73,4 +73,18 @@ public function testConfigureOptionsSetsDefaultOptions(): void $this->assertEquals(['charlist' => " \t\n\r\0\x0B"], $resolvedOptions); } + + /** + * trim() removes bytes: a multibyte character of the list cut the characters sharing its bytes ("Été" gave "\x89t"). + */ + public function testTransformWithAMultibyteCharlist(): void + { + $transformer = new TrimTransformer(); + + $this->assertSame('Ét', $transformer->transform('Été', ['charlist' => 'é'])); + $this->assertSame('t', $transformer->transform('ÉtéÉ', ['charlist' => 'éÉ'])); + $this->assertSame('t', $transformer->transform('« t »', ['charlist' => '« »'])); + // A single-byte charlist keeps the ranges of trim() + $this->assertSame('123', $transformer->transform('abc123cba', ['charlist' => 'a..c'])); + } }