From 8554f61036863af340023200da0626a19442e826 Mon Sep 17 00:00:00 2001 From: Nicolas Joubert Date: Fri, 9 Oct 2026 10:24:55 +0200 Subject: [PATCH] test #197 Add missing tests: every Task and Transformer is now covered by unit tests. Remove the obsolete tests.old directory. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 3 + tests.old/AbstractProcessTest.php | 139 ----- tests.old/BasicTest.php | 114 ---- tests.old/BlockingTaskTest.php | 83 --- tests.old/CircularProcessTest.php | 52 -- tests.old/ContextTest.php | 119 ---- tests.old/EmptyProcessTest.php | 29 - tests.old/ExceptionManagementTest.php | 32 -- tests.old/FlushableTaskTest.php | 52 -- tests.old/IterableTaskTest.php | 144 ----- tests.old/MultiBranchProcessTest.php | 117 ---- tests.old/MultiWorkflowTest.php | 58 -- tests.old/ProcessManagerTest.php | 70 --- tests.old/Task/ColumnAggregatorTaskTest.php | 64 --- tests.old/Task/FilterTaskTest.php | 57 -- tests.old/Task/ProcessExecutorTaskTest.php | 41 -- tests.old/Task/StopTaskTest.php | 37 -- tests.old/Task/TransformerTaskTest.php | 56 -- tests.old/Task/ValidatorTaskTest.php | 36 -- .../ArrayFilterTransformerTest.php | 76 --- .../Transformer/CallbackTransformerTest.php | 87 --- .../Transformer/DateTransformersTest.php | 81 --- .../Transformer/GenericTransformersTest.php | 26 - tests.old/Transformer/HashTransformerTest.php | 43 -- .../Transformer/MappingTransformerTest.php | 134 ----- .../Transformer/RulesTransformerTest.php | 34 -- .../Transformer/TransformerExceptionTest.php | 60 -- .../Transformer/TypeSetterTransformerTest.php | 49 -- .../Transformer/UnsetTransformerTest.php | 103 ---- .../XpathEvaluatorTransformerTest.php | 92 ---- tests/Task/AggregateIterableTaskTest.php | 83 +++ tests/Task/ArrayMergeTaskTest.php | 153 +++++ tests/Task/ConstantIterableOutputTaskTest.php | 145 +++++ tests/Task/ConstantOutputTaskTest.php | 107 ++++ tests/Task/Debug/DebugTaskTest.php | 96 ++++ tests/Task/Debug/DieTaskTest.php | 57 ++ tests/Task/Debug/ErrorForwarderTaskTest.php | 65 +++ tests/Task/Debug/StopwatchTaskTest.php | 107 ++++ tests/Task/DummyTaskTest.php | 56 ++ tests/Task/File/Csv/CsvWriterTaskTest.php | 285 ++++++++++ tests/Task/File/FileMoverTaskTest.php | 216 ++++++++ tests/Task/File/FileReaderTaskTest.php | 127 +++++ tests/Task/File/FileRemoverTaskTest.php | 91 +++ tests/Task/File/FileWriterTaskTest.php | 125 +++++ tests/Task/File/InputFileReaderTaskTest.php | 138 +++++ .../JsonStream/JsonStreamReaderTaskTest.php | 252 +++++++++ tests/Task/File/Xml/XmlReaderTaskTest.php | 187 +++++++ tests/Task/File/Xml/XmlWriterTaskTest.php | 179 ++++++ tests/Task/File/Yaml/YamlReaderTaskTest.php | 220 ++++++++ tests/Task/File/Yaml/YamlWriterTaskTest.php | 159 ++++++ tests/Task/FilterTaskTest.php | 175 ++++++ .../Task/GroupByAggregateIterableTaskTest.php | 144 +++++ tests/Task/InputAggregatorTaskTest.php | 198 +++++++ tests/Task/InputIteratorTaskTest.php | 142 +++++ .../Task/Process/ProcessExecutorTaskTest.php | 196 +++++++ tests/Task/PropertyGetterTaskTest.php | 126 +++++ tests/Task/Reporting/LoggerTaskTest.php | 196 +++++++ tests/Task/RowAggregatorTaskTest.php | 143 +++++ .../Serialization/DenormalizerTaskTest.php | 179 ++++++ tests/Task/SkipEmptyTaskTest.php | 85 +++ tests/Task/SplitJoinLineTaskTest.php | 169 ++++++ tests/Task/StopTaskTest.php | 46 ++ tests/Task/TransformerTaskTest.php | 217 ++++++++ tests/Task/Validation/ValidatorTaskTest.php | 304 ++++++++++ .../Array/ArrayLastTransformerTest.php | 57 ++ .../Array/ArrayMapTransformerTest.php | 157 ++++++ .../Array/ArrayUnsetTransformerTest.php | 91 +++ tests/Transformer/CallbackTransformerTest.php | 139 +++++ .../ConvertValueTransformerTest.php | 192 +++++++ .../Transformer/EvaluatorTransformerTest.php | 171 ++++++ tests/Transformer/MappingTransformerTest.php | 521 ++++++++++++++++++ .../Object/InstantiateTransformerTest.php | 118 ++++ .../PropertyAccessorTransformerTest.php | 168 ++++++ ...RecursivePropertySetterTransformerTest.php | 260 +++++++++ .../DenormalizeTransformerTest.php | 159 ++++++ .../NormalizeTransformerTest.php | 148 +++++ .../String/PregMatchTransformerTest.php | 130 +++++ tests/Transformer/UnsetTransformerTest.php | 162 ++++++ 78 files changed, 7644 insertions(+), 2085 deletions(-) delete mode 100644 tests.old/AbstractProcessTest.php delete mode 100644 tests.old/BasicTest.php delete mode 100644 tests.old/BlockingTaskTest.php delete mode 100644 tests.old/CircularProcessTest.php delete mode 100644 tests.old/ContextTest.php delete mode 100644 tests.old/EmptyProcessTest.php delete mode 100644 tests.old/ExceptionManagementTest.php delete mode 100644 tests.old/FlushableTaskTest.php delete mode 100644 tests.old/IterableTaskTest.php delete mode 100644 tests.old/MultiBranchProcessTest.php delete mode 100644 tests.old/MultiWorkflowTest.php delete mode 100644 tests.old/ProcessManagerTest.php delete mode 100644 tests.old/Task/ColumnAggregatorTaskTest.php delete mode 100644 tests.old/Task/FilterTaskTest.php delete mode 100644 tests.old/Task/ProcessExecutorTaskTest.php delete mode 100644 tests.old/Task/StopTaskTest.php delete mode 100644 tests.old/Task/TransformerTaskTest.php delete mode 100644 tests.old/Task/ValidatorTaskTest.php delete mode 100644 tests.old/Transformer/ArrayFilterTransformerTest.php delete mode 100644 tests.old/Transformer/CallbackTransformerTest.php delete mode 100644 tests.old/Transformer/DateTransformersTest.php delete mode 100644 tests.old/Transformer/GenericTransformersTest.php delete mode 100644 tests.old/Transformer/HashTransformerTest.php delete mode 100644 tests.old/Transformer/MappingTransformerTest.php delete mode 100644 tests.old/Transformer/RulesTransformerTest.php delete mode 100644 tests.old/Transformer/TransformerExceptionTest.php delete mode 100644 tests.old/Transformer/TypeSetterTransformerTest.php delete mode 100644 tests.old/Transformer/UnsetTransformerTest.php delete mode 100644 tests.old/Transformer/XpathEvaluatorTransformerTest.php create mode 100644 tests/Task/AggregateIterableTaskTest.php create mode 100644 tests/Task/ArrayMergeTaskTest.php create mode 100644 tests/Task/ConstantIterableOutputTaskTest.php create mode 100644 tests/Task/ConstantOutputTaskTest.php create mode 100644 tests/Task/Debug/DebugTaskTest.php create mode 100644 tests/Task/Debug/DieTaskTest.php create mode 100644 tests/Task/Debug/ErrorForwarderTaskTest.php create mode 100644 tests/Task/Debug/StopwatchTaskTest.php create mode 100644 tests/Task/DummyTaskTest.php create mode 100644 tests/Task/File/Csv/CsvWriterTaskTest.php create mode 100644 tests/Task/File/FileMoverTaskTest.php create mode 100644 tests/Task/File/FileReaderTaskTest.php create mode 100644 tests/Task/File/FileRemoverTaskTest.php create mode 100644 tests/Task/File/FileWriterTaskTest.php create mode 100644 tests/Task/File/InputFileReaderTaskTest.php create mode 100644 tests/Task/File/JsonStream/JsonStreamReaderTaskTest.php create mode 100644 tests/Task/File/Xml/XmlReaderTaskTest.php create mode 100644 tests/Task/File/Xml/XmlWriterTaskTest.php create mode 100644 tests/Task/File/Yaml/YamlReaderTaskTest.php create mode 100644 tests/Task/File/Yaml/YamlWriterTaskTest.php create mode 100644 tests/Task/FilterTaskTest.php create mode 100644 tests/Task/GroupByAggregateIterableTaskTest.php create mode 100644 tests/Task/InputAggregatorTaskTest.php create mode 100644 tests/Task/InputIteratorTaskTest.php create mode 100644 tests/Task/Process/ProcessExecutorTaskTest.php create mode 100644 tests/Task/PropertyGetterTaskTest.php create mode 100644 tests/Task/Reporting/LoggerTaskTest.php create mode 100644 tests/Task/RowAggregatorTaskTest.php create mode 100644 tests/Task/Serialization/DenormalizerTaskTest.php create mode 100644 tests/Task/SkipEmptyTaskTest.php create mode 100644 tests/Task/SplitJoinLineTaskTest.php create mode 100644 tests/Task/StopTaskTest.php create mode 100644 tests/Task/TransformerTaskTest.php create mode 100644 tests/Task/Validation/ValidatorTaskTest.php create mode 100644 tests/Transformer/Array/ArrayLastTransformerTest.php create mode 100644 tests/Transformer/Array/ArrayMapTransformerTest.php create mode 100644 tests/Transformer/Array/ArrayUnsetTransformerTest.php create mode 100644 tests/Transformer/CallbackTransformerTest.php create mode 100644 tests/Transformer/ConvertValueTransformerTest.php create mode 100644 tests/Transformer/EvaluatorTransformerTest.php create mode 100644 tests/Transformer/MappingTransformerTest.php create mode 100644 tests/Transformer/Object/InstantiateTransformerTest.php create mode 100644 tests/Transformer/Object/PropertyAccessorTransformerTest.php create mode 100644 tests/Transformer/Object/RecursivePropertySetterTransformerTest.php create mode 100644 tests/Transformer/Serialization/DenormalizeTransformerTest.php create mode 100644 tests/Transformer/Serialization/NormalizeTransformerTest.php create mode 100644 tests/Transformer/String/PregMatchTransformerTest.php create mode 100644 tests/Transformer/UnsetTransformerTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index a711be6d..7a8ae6b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ Latest ------ +## Changes +* [#197](https://github.com/cleverage/process-bundle/issues/197) Add missing tests: every Task and Transformer is now covered by unit tests. Remove the obsolete `tests.old` directory. + v5.1 ----- diff --git a/tests.old/AbstractProcessTest.php b/tests.old/AbstractProcessTest.php deleted file mode 100644 index d8a1be5f..00000000 --- a/tests.old/AbstractProcessTest.php +++ /dev/null @@ -1,139 +0,0 @@ -processManager = $this->getContainer() - ->get(ProcessManager::class); - $this->processConfigurationRegistry = $this->getContainer() - ->get(ProcessConfigurationRegistry::class); - $this->transformerRegistry = $this->getContainer() - ->get(TransformerRegistry::class); - } - - /** - * Assert that an array of values match what's been registered in the standard queue - * It can also match task codes using the checkTask flag. - */ - protected function assertDataQueue(array $expected, string $processName, bool $checkTask = true) - { - $dataQueueListener = $this->getContainer() - ->get(DataQueueEventListener::class); - $actualQueue = $dataQueueListener->getQueue($processName); - - self::assertCount(\count($expected), $actualQueue, 'Event count does not match'); - - /** - * @var int $key - * @var ProcessState $value - */ - foreach ($actualQueue as $key => $value) { - self::assertArrayHasKey($key, $expected); - if ($checkTask) { - if (\array_key_exists('task', $expected[$key])) { - self::assertEquals( - $expected[$key]['task'], - $value->getPreviousState() - ->getTaskConfiguration() - ->getCode(), - "Task #{$key} does not match" - ); - } - if (\array_key_exists('value', $expected[$key])) { - self::assertEquals($expected[$key]['value'], $value->getInput(), "Value #{$key} does not match"); - } - } else { - self::assertEquals($expected[$key], $value->getInput(), "Value #{$key} does not match"); - } - } - } - - /** - * Returns the booted symfony container. - * - * Compatibility backport for symfony/phpunit-bridge that should work with v3 or v4 - */ - protected static function getContainer(): ContainerInterface - { - if (null !== self::getContainer()) { - return self::getContainer(); - } - - $container = self::$kernel->getContainer(); - $container = $container->has('test.service_container') ? $container->get('test.service_container') : $container; - - return $container; - } - - /** - * Helper method to configure options and test a transformation. - */ - protected function assertTransformation(string $transformerCode, mixed $expected, mixed $value, array $options = []) - { - $result = $this->transform($transformerCode, $value, $options); - self::assertEquals($expected, $result); - } - - /** - * Transform some value using referenced transformer with given options. - */ - protected function transform(string $transformerCode, mixed $value, array $options = []) - { - $transformer = $this->transformerRegistry->getTransformer($transformerCode); - - if ($transformer instanceof ConfigurableTransformerInterface) { - $resolver = new OptionsResolver(); - $transformer->configureOptions($resolver); - $options = $resolver->resolve($options); - } - - return $transformer->transform($value, $options); - } -} diff --git a/tests.old/BasicTest.php b/tests.old/BasicTest.php deleted file mode 100644 index de19e6a8..00000000 --- a/tests.old/BasicTest.php +++ /dev/null @@ -1,114 +0,0 @@ -setExpectedException(\CleverAge\ProcessBundle\Exception\MissingProcessException::class); - - $this->processManager->execute('test.unknown_test'); - } - - /** - * Check that a known process can be executed and return defined output. - */ - public function testSimpleProcess(): void - { - $result = $this->processManager->execute('test.simple_process', 'success'); - - self::assertEquals('success', $result); - } - - /** - * Assert that the error branch is not called. - */ - public function testErrorProcess(): void - { - $this->processManager->execute('test.error_process'); - $this->assertDataQueue( - [ - [ - 'task' => 'doNothing', - 'value' => 1, - ], - [ - 'task' => 'doNothing', - 'value' => 2, - ], - [ - 'task' => 'doNothing', - 'value' => 3, - ], - ], - 'test.error_process' - ); - } - - /** - * Assert that the error branch is called, and blocking task are correctly working. - */ - public function testErrorProcessBlocking(): void - { - $this->processManager->execute('test.error_process_with_blocking'); - $this->assertDataQueue( - [ - [ - 'task' => 'doNothing2', - 'value' => 1, - ], - [ - 'task' => 'doNothing2', - 'value' => 2, - ], - [ - 'task' => 'doNothing2', - 'value' => 3, - ], - [ - 'task' => 'aggregate', - 'value' => [1, 2, 3], - ], - ], - 'test.error_process_with_blocking' - ); - } - - public function testFailingEntryPointWithAncestors(): void - { - $this->setExpectedException(\CleverAge\ProcessBundle\Exception\InvalidProcessConfigurationException::class); - - $this->processManager->execute('test.entry_point_with_ancestor'); - } - - /** - * Check that the use of a string in task "outputs" or "errors" is possible. - */ - public function testStringOutput(): void - { - $result = $this->processManager->execute('test.string_outputs', 'success'); - self::assertEquals('success', $result); - - $result = $this->processManager->execute('test.string_errors', 'success'); - self::assertEquals('success', $result); - } -} diff --git a/tests.old/BlockingTaskTest.php b/tests.old/BlockingTaskTest.php deleted file mode 100644 index 26111c29..00000000 --- a/tests.old/BlockingTaskTest.php +++ /dev/null @@ -1,83 +0,0 @@ -processManager->execute('test.simple_blocking'); - - self::assertEquals([1, 2, 3], $result); - } - - public function testBlockingSolo(): void - { - $result = $this->processManager->execute('test.blocking_solo', 'success'); - - self::assertEquals(['success'], $result); - } - - public function testMultipleBlockingSolo(): void - { - $result = $this->processManager->execute('test.multiple_blocking_solo', 'success'); - - self::assertEquals([['success']], $result); - } - - /** - * Assert a process with multiple blocking tasks can execute properly. - * Check - * - a subsequent blocking task will be proceeded at least once - * - a subsequent blocking task will be proceeded at most once. - */ - public function testMultipleBlocking(): void - { - $result = $this->processManager->execute('test.multiple_blocking'); - - self::assertEquals([1, 2, 3], $result); - } - - /** - * Assert when there is multiple iterations before a blocking that all are successfully resolved, and the blocking - * is executed only once. - */ - public function testMultipleIterationBlocking(): void - { - $this->processManager->execute('test.multiple_iteration_blocking'); - - $this->assertDataQueue( - [ - [ - 'task' => 'aggregate', - 'value' => [1, 2, 3, 1, 2, 3, 1, 2, 3], - ], - ], - 'test.multiple_iteration_blocking' - ); - } - - /** - * Assert that if a blocking is never executed, it will automatically skip subsequent tasks. - */ - public function testBlockingEmptyData(): void - { - $this->processManager->execute('test.blocking_empty_data'); - - $this->assertDataQueue([], 'test.blocking_empty_data'); - } -} diff --git a/tests.old/CircularProcessTest.php b/tests.old/CircularProcessTest.php deleted file mode 100644 index 699a9bc7..00000000 --- a/tests.old/CircularProcessTest.php +++ /dev/null @@ -1,52 +0,0 @@ -setExpectedException(\CleverAge\ProcessBundle\Exception\CircularProcessException::class); - - $this->processManager->execute('test.circular_process'); - } - - public function testReversedCircularProcess(): void - { - $this->setExpectedException(\CleverAge\ProcessBundle\Exception\CircularProcessException::class); - - $this->processManager->execute('test.circular_process.reversed'); - } - - public function testSelfCircularProcess(): void - { - $this->setExpectedException(\CleverAge\ProcessBundle\Exception\CircularProcessException::class); - - $this->processManager->execute('test.circular_process.self'); - } - - /** - * A loop in an independent branch was sometime not properly detected. - */ - public function testLongCircularProcess(): void - { - $this->setExpectedException(\CleverAge\ProcessBundle\Exception\CircularProcessException::class); - - $this->processManager->execute('test.circular_process.long'); - } -} diff --git a/tests.old/ContextTest.php b/tests.old/ContextTest.php deleted file mode 100644 index 62a6a27e..00000000 --- a/tests.old/ContextTest.php +++ /dev/null @@ -1,119 +0,0 @@ -processManager->execute('test.context', 'ko', [ - 'value' => 'ok', - ]); - - self::assertEquals('ok', $result); - - $result = $this->processManager->execute('test.context.sub_value', null, [ - 'value' => 'ok', - ]); - - self::assertEquals([ - 'key' => 'ok', - ], $result); - } - - /** - * Assert a value can correctly passed and merged into a string, through context. - */ - public function testContextMergedValue(): void - { - $result = $this->processManager->execute('test.context.merged_value', null, [ - 'value' => 'ok', - ]); - - self::assertEquals('value is ok', $result); - } - - /** - * Assert 2 values can correctly passed and merged into a string, through context. - */ - public function testContextMultiValue(): void - { - $result = $this->processManager->execute( - 'test.context.multi_values', - null, - [ - 'value1' => 'red', - 'value2' => 'dead', - ] - ); - - self::assertEquals('red is dead', $result); - } - - /** - * Assert a complex value will fail while being merged into a string, through context. - */ - public function testContextCannotMergeValue(): void - { - $this->setExpectedException(\RuntimeException::class); - - $this->processManager->execute( - 'test.context.merged_value', - null, - [ - 'value' => [ - 'another_key' => 'another_value', - ], - ] - ); - } - - /** - * Assert a complex value can correctly passed through context. - */ - public function testComplexContext(): void - { - $result = $this->processManager->execute('test.context', null, [ - 'value' => [ - 'another_key' => 'another_value', - ], - ]); - - self::assertEquals([ - 'another_key' => 'another_value', - ], $result); - - $result = $this->processManager->execute( - 'test.context.sub_value', - null, - [ - 'value' => [ - 'another_key' => 'another_value', - ], - ] - ); - - self::assertEquals([ - 'key' => [ - 'another_key' => 'another_value', - ], - ], $result); - } -} diff --git a/tests.old/EmptyProcessTest.php b/tests.old/EmptyProcessTest.php deleted file mode 100644 index c1445723..00000000 --- a/tests.old/EmptyProcessTest.php +++ /dev/null @@ -1,29 +0,0 @@ -processManager->execute('test.empty_process'); - self::assertTrue(true, 'There was an exception'); - } -} diff --git a/tests.old/ExceptionManagementTest.php b/tests.old/ExceptionManagementTest.php deleted file mode 100644 index 449c437a..00000000 --- a/tests.old/ExceptionManagementTest.php +++ /dev/null @@ -1,32 +0,0 @@ -processManager->execute('test.exception_management.set_exception_in_the_middle'); - - self::assertEquals(['abc', 'bcd', 'cde', 'def'], $result['success']); - - self::assertEquals([1], $result['errors']); - } -} diff --git a/tests.old/FlushableTaskTest.php b/tests.old/FlushableTaskTest.php deleted file mode 100644 index e0b56f45..00000000 --- a/tests.old/FlushableTaskTest.php +++ /dev/null @@ -1,52 +0,0 @@ -processManager->execute('test.simple_flushable'); - - self::assertCount(2, $result); - self::assertEquals([1, 2], $result[0]); - self::assertEquals([3], $result[1]); - } - - public function testSingleFlushable(): void - { - $result = $this->processManager->execute('test.single_flushable'); - - self::assertCount(1, $result); - self::assertEquals([1], $result[0]); - } - - public function testSimpleFlushableNoIterable(): void - { - $result = $this->processManager->execute('test.simple_flushable_no_iterable'); - - self::assertCount(1, $result); - self::assertEquals([1], $result[0]); - } - - public function testIterableFlushable(): void - { - $result = $this->processManager->execute('test.iterable_flushable'); - - self::assertEquals([1, 2, 3, 1, 2, 3], $result); - } -} diff --git a/tests.old/IterableTaskTest.php b/tests.old/IterableTaskTest.php deleted file mode 100644 index 2b7e227b..00000000 --- a/tests.old/IterableTaskTest.php +++ /dev/null @@ -1,144 +0,0 @@ -processManager->execute('test.iterable_process'); - - $this->assertDataQueue( - [ - [ - 'task' => 'data', - 'value' => 1, - ], - [ - 'task' => 'doNothing', - 'value' => 1, - ], - [ - 'task' => 'data', - 'value' => 2, - ], - [ - 'task' => 'doNothing', - 'value' => 2, - ], - [ - 'task' => 'data', - 'value' => 3, - ], - [ - 'task' => 'doNothing', - 'value' => 3, - ], - [ - 'task' => 'data', - 'value' => 4, - ], - [ - 'task' => 'doNothing', - 'value' => 4, - ], - [ - 'task' => 'aggregate', - 'value' => [1, 2, 3, 4], - ], - ], - 'test.iterable_process' - ); - } - - /** - * Assert 2 iterators can run alone, without a subsequent blocking task - * Assert \CleverAge\ProcessBundle\Task\InputIteratorTask can correctly reset. - */ - public function testDoubleIterableAlone(): void - { - $this->processManager->execute('test.double_iterable_alone'); - - $this->assertDataQueue( - [ - [ - 'task' => 'iterate', - 'value' => 1, - ], - [ - 'task' => 'iterate', - 'value' => 2, - ], - [ - 'task' => 'iterate', - 'value' => 3, - ], - [ - 'task' => 'iterate', - 'value' => 4, - ], - ], - 'test.double_iterable_alone' - ); - } - - /** - * Assert the SplitJoinLineTask works the way it's supposed to. - */ - public function testSplitJoinLine(): void - { - $this->processManager->execute('test.split_join_iterable'); - - $this->assertDataQueue( - [ - [ - 'product' => 'toto', - 'asset' => 'a', - ], - [ - 'product' => 'toto', - 'asset' => 'b', - ], - [ - 'product' => 'toto', - 'asset' => 'c', - ], - [ - 'product' => 'toto', - 'asset' => 'd', - ], - [ - 'product' => 'tata', - 'asset' => 'e', - ], - [ - 'product' => 'tata', - 'asset' => 'f', - ], - [ - 'product' => 'tata', - 'asset' => 'g', - ], - [ - 'product' => 'tata', - 'asset' => 'h', - ], - ], - 'test.split_join_iterable' - ); - } -} diff --git a/tests.old/MultiBranchProcessTest.php b/tests.old/MultiBranchProcessTest.php deleted file mode 100644 index c4b8b43a..00000000 --- a/tests.old/MultiBranchProcessTest.php +++ /dev/null @@ -1,117 +0,0 @@ -processManager->execute('test.multi_branch_process_first'); - $this->assertDataQueue([ - [ - 'task' => 'data1', - 'value' => 'ok', - ], - ], 'test.multi_branch_process_first'); - - $this->processManager->execute('test.multi_branch_process_entry'); - $this->assertDataQueue([ - [ - 'task' => 'data2', - 'value' => 'ok', - ], - ], 'test.multi_branch_process_entry'); - - $this->processManager->execute('test.multi_branch_process_entry_reversed'); - $this->assertDataQueue([ - [ - 'task' => 'data2', - 'value' => 'ok', - ], - ], 'test.multi_branch_process_entry'); - - $this->processManager->execute('test.multi_branch_process_end'); - $this->assertDataQueue([ - [ - 'task' => 'data2', - 'value' => 'ok', - ], - ], 'test.multi_branch_process_end'); - - $this->processManager->execute('test.multi_branch_process_entry_end'); - $this->assertDataQueue([ - [ - 'task' => 'data2', - 'value' => 'ok', - ], - ], 'test.multi_branch_process_entry_end'); - } - - public function testMainGroupOrder(): void - { - $process = $this->processConfigurationRegistry->getProcessConfiguration('test.multi_branch_process_first'); - self::assertEquals( - ['data1', 'pushDataEvent1'], - $process->getMainTaskGroup(), - 'Failed testing task order with process test.multi_branch_process_first' - ); - - $process = $this->processConfigurationRegistry->getProcessConfiguration('test.multi_branch_process_entry'); - self::assertEquals( - ['data2', 'pushDataEvent2'], - $process->getMainTaskGroup(), - 'Failed testing task order with process test.multi_branch_process_entry' - ); - - $process = $this->processConfigurationRegistry->getProcessConfiguration( - 'test.multi_branch_process_entry_reversed' - ); - self::assertEquals( - ['data2', 'pushDataEvent2'], - $process->getMainTaskGroup(), - 'Failed testing task order with process test.multi_branch_process_entry_reversed' - ); - - $process = $this->processConfigurationRegistry->getProcessConfiguration('test.multi_branch_process_end'); - self::assertEquals( - ['data2', 'pushDataEvent2'], - $process->getMainTaskGroup(), - 'Failed testing task order with process test.multi_branch_process_end' - ); - - $process = $this->processConfigurationRegistry->getProcessConfiguration('test.multi_branch_process_entry_end'); - self::assertEquals( - ['data2', 'pushDataEvent2'], - $process->getMainTaskGroup(), - 'Failed testing task order with process test.multi_branch_process_entry_end' - ); - } - - /** - * Assert a task cannot be started if the process is not valid. - */ - public function testMultiBranchProcessError(): void - { - $this->setExpectedException(\CleverAge\ProcessBundle\Exception\InvalidProcessConfigurationException::class); - - $this->processManager->execute('test.multi_branch_process_entry_end_error'); - } -} diff --git a/tests.old/MultiWorkflowTest.php b/tests.old/MultiWorkflowTest.php deleted file mode 100644 index 3a20f625..00000000 --- a/tests.old/MultiWorkflowTest.php +++ /dev/null @@ -1,58 +0,0 @@ -processManager->execute('test.multi_workflow_process'); - - $this->assertDataQueue( - [ - [ - 'task' => 'data', - 'value' => 1, - ], - [ - 'task' => 'data', - 'value' => 2, - ], - [ - 'task' => 'data', - 'value' => 3, - ], - [ - 'task' => 'aggregate', - 'value' => [1, 2, 3], - ], - [ - 'task' => 'aggregate2', - 'value' => [1, 2, 3], - ], - [ - 'task' => 'inputAggregate', - 'value' => [ - 'aggregate' => [1, 2, 3], - 'aggregate2' => [1, 2, 3], - ], - ], - ], - 'test.multi_workflow_process' - ); - } -} diff --git a/tests.old/ProcessManagerTest.php b/tests.old/ProcessManagerTest.php deleted file mode 100644 index 3d019b5e..00000000 --- a/tests.old/ProcessManagerTest.php +++ /dev/null @@ -1,70 +0,0 @@ -prophesize(EventDispatcherInterface::class); - - $dispatchStartProphecy = new MethodProphecy($edProphecy, 'dispatch', [ - new TypeToken(ProcessEvent::class), - ProcessEvent::EVENT_PROCESS_STARTED, - ]); - $dispatchStartProphecy->shouldBeCalled(); - $edProphecy->addMethodProphecy($dispatchStartProphecy); - - $dispatchStartProphecy = new MethodProphecy($edProphecy, 'dispatch', [ - new TypeToken(ProcessEvent::class), - ProcessEvent::EVENT_PROCESS_ENDED, - ]); - $dispatchStartProphecy->shouldBeCalled(); - $edProphecy->addMethodProphecy($dispatchStartProphecy); - - $dispatchStartProphecy = new MethodProphecy($edProphecy, 'dispatch', [ - new TypeToken(ProcessEvent::class), - ProcessEvent::EVENT_PROCESS_FAILED, - ]); - $dispatchStartProphecy->shouldNotBeCalled(); - $edProphecy->addMethodProphecy($dispatchStartProphecy); - - /** @var EventDispatcherInterface $eventDispatcher */ - $eventDispatcher = $edProphecy->reveal(); - $processManager = new ProcessManager( - $this->getContainer(), - $this->getContainer() - ->get(ProcessLogger::class), - $this->getContainer() - ->get(TaskLogger::class), - $this->getContainer() - ->get(ProcessConfigurationRegistry::class), - $this->getContainer() - ->get(ContextualOptionResolver::class), - $eventDispatcher - ); - - $processManager->execute('test.simple_process'); - } -} diff --git a/tests.old/Task/ColumnAggregatorTaskTest.php b/tests.old/Task/ColumnAggregatorTaskTest.php deleted file mode 100644 index 8639380c..00000000 --- a/tests.old/Task/ColumnAggregatorTaskTest.php +++ /dev/null @@ -1,64 +0,0 @@ - 'A', - 'col2' => 'val1', - ]; - $input2 = [ - 'col1' => 'B', - 'col2' => 'val2', - ]; - $input3 = [ - 'col1' => 'A', - 'col2' => 'val3', - ]; - $input4 = [ - 'col1' => 'B', - 'col2' => 'val4', - ]; - $input = [$input1, $input2, $input3, $input4]; - - self::assertEquals( - [ - 'aggregateAny' => [ - 'col1' => [ - 'column' => 'col1', - 'values' => $input, - ], - ], - 'aggregateA' => [ - 'col1' => [ - 'column' => 'col1', - 'values' => [$input1, $input3], - ], - ], - 'aggregateB' => [ - 'col1' => [ - 'column' => 'col1', - 'values' => [$input2, $input4], - ], - ], - ], - $this->processManager->execute('test.column_aggregator_task.simple', $input) - ); - } -} diff --git a/tests.old/Task/FilterTaskTest.php b/tests.old/Task/FilterTaskTest.php deleted file mode 100644 index 8d6caf56..00000000 --- a/tests.old/Task/FilterTaskTest.php +++ /dev/null @@ -1,57 +0,0 @@ - 'value1', - 'key2' => 'value2', - 'key3' => ['something'], - ], - [ - 'key1' => 'value1b', - 'key2' => 'value2b', - 'key3' => ['something'], - ], - [ - 'key1' => 'value1c', - 'key2' => 'value2c', - 'key3' => [], - ], - ]; - $result = $this->processManager->execute('test.filter_task.match', $input); - self::assertEquals([$input[0]], $result); - - $result = $this->processManager->execute('test.filter_task.not_match', $input); - self::assertEquals([$input[1], $input[2]], $result); - - $result = $this->processManager->execute('test.filter_task.empty', $input); - self::assertEquals([$input[2]], $result); - - $result = $this->processManager->execute('test.filter_task.not_empty', $input); - self::assertEquals([$input[0], $input[1]], $result); - } -} diff --git a/tests.old/Task/ProcessExecutorTaskTest.php b/tests.old/Task/ProcessExecutorTaskTest.php deleted file mode 100644 index 35309169..00000000 --- a/tests.old/Task/ProcessExecutorTaskTest.php +++ /dev/null @@ -1,41 +0,0 @@ -processManager->execute('test.process_execute_task'); - self::assertEquals([1, 2, 3, 4], $result); - } - - /** - * Assert correct error if it doesn't match a good subprocess name. - */ - public function testExecutorError(): void - { - $this->setExpectedException(\RuntimeException::class); - - $this->processManager->execute('test.process_execute_task.error'); - } -} diff --git a/tests.old/Task/StopTaskTest.php b/tests.old/Task/StopTaskTest.php deleted file mode 100644 index 617824c3..00000000 --- a/tests.old/Task/StopTaskTest.php +++ /dev/null @@ -1,37 +0,0 @@ -processManager->execute('test.task.stop_task.iterable_interruption'); - - $this->assertDataQueue( - [ - [ - 'task' => 'data', - 'value' => 1, - ], - ], - 'test.task.stop_task.iterable_interruption' - ); - } -} diff --git a/tests.old/Task/TransformerTaskTest.php b/tests.old/Task/TransformerTaskTest.php deleted file mode 100644 index 46bc3374..00000000 --- a/tests.old/Task/TransformerTaskTest.php +++ /dev/null @@ -1,56 +0,0 @@ -processManager->execute('test.transformer_task.simple', 'value'); - - self::assertEquals([ - 'field' => 'value', - ], $result); - } - - /** - * Assert that if "ignore_missing" is false, then an error is thrown for missing fields. - */ - public function testMissingMapping(): void - { - $this->setExpectedException(\RuntimeException::class); - - $this->processManager->execute('test.transformer_task.error', 'value'); - } - - /** - * Assert we can use multiple times the same sub-transformer using # suffixes. - */ - public function testMultiSubtransformers(): void - { - $result = $this->processManager->execute('test.transformer_task.multi_subtransformers', [3, null, 4, 2]); - - self::assertEquals([ - 'field' => [2, 4, 3], - ], $result); - } -} diff --git a/tests.old/Task/ValidatorTaskTest.php b/tests.old/Task/ValidatorTaskTest.php deleted file mode 100644 index efb1d62b..00000000 --- a/tests.old/Task/ValidatorTaskTest.php +++ /dev/null @@ -1,36 +0,0 @@ - 42, - 'any_field' => 'hello', - 'choice_field' => 'Some random value 1', - ]; - $result = $this->processManager->execute('test.validator_task', $input); - self::assertEquals($input, $result); - } -} diff --git a/tests.old/Transformer/ArrayFilterTransformerTest.php b/tests.old/Transformer/ArrayFilterTransformerTest.php deleted file mode 100644 index 3188289b..00000000 --- a/tests.old/Transformer/ArrayFilterTransformerTest.php +++ /dev/null @@ -1,76 +0,0 @@ - 1, - 'filter_value' => 'X', - ], - [ - 'data' => 2, - 'filter_value' => 'Y', - ], - [ - 'data' => 3, - ], - [ - 'data' => 4, - 'filter_value' => 'X', - ], - [ - 'data' => 5, - 'filter_value' => 'Y', - ], - [ - 'data' => 6, - ], - ]; - - $result = $this->processManager->execute('test.array_filter_transformer.simple', $input); - - $nativeResult = array_filter( - $input, - static fn ($item): bool => isset($item['filter_value']) && 'X' === $item['filter_value'] - ); - - // Note that to match native function, key are preserved - $expectedResult = [ - 0 => [ - 'data' => 1, - 'filter_value' => 'X', - ], - 3 => [ - 'data' => 4, - 'filter_value' => 'X', - ], - ]; - - self::assertCount(2, $result); - self::assertEquals($expectedResult, $result); - self::assertEquals($nativeResult, $result); - } -} diff --git a/tests.old/Transformer/CallbackTransformerTest.php b/tests.old/Transformer/CallbackTransformerTest.php deleted file mode 100644 index 72795ae9..00000000 --- a/tests.old/Transformer/CallbackTransformerTest.php +++ /dev/null @@ -1,87 +0,0 @@ -processManager->execute('test.callback_transformer.simple', $input); - - self::assertEquals('3', $result); - } - - /** - * Assert data is correctly filtered. - */ - public function testLeftParametersCallback(): void - { - $input = '3'; - - $result = $this->processManager->execute('test.callback_transformer.left_parameters', $input); - - self::assertEquals('1-2-3', $result); - } - - /** - * Assert data is correctly filtered. - */ - public function testRightParametersCallback(): void - { - $input = '3'; - - $result = $this->processManager->execute('test.callback_transformer.right_parameters', $input); - - self::assertEquals('3-4-5', $result); - } - - /** - * Assert data is correctly filtered. - */ - public function testAdditionalParametersCallback(): void - { - $input = '6'; - - $result = $this->processManager->execute('test.callback_transformer.additional_parameters', $input); - - self::assertEquals('6-7-8', $result); - } - - /** - * Assert data is correctly filtered. - */ - public function testLeftAndRightParametersCallback(): void - { - $input = '3'; - - $result = $this->processManager->execute('test.callback_transformer.left_right_parameters', $input); - - self::assertEquals('1-2-3-4-5', $result); - } -} diff --git a/tests.old/Transformer/DateTransformersTest.php b/tests.old/Transformer/DateTransformersTest.php deleted file mode 100644 index 15eba89e..00000000 --- a/tests.old/Transformer/DateTransformersTest.php +++ /dev/null @@ -1,81 +0,0 @@ -processManager->execute('test.date_transformers.date_format', '2001-01-01T00:00:00+00:00'); - self::assertEquals('2001-01-01', $result); - } - - /** - * Assert a date object can be formatted into a string. - */ - public function testDateFormatObject(): void - { - $date = \DateTime::createFromFormat(\DATE_ATOM, '2001-01-02T00:00:00+00:00'); - $result = $this->processManager->execute('test.date_transformers.date_format', $date); - self::assertEquals('2001-01-02', $result); - } - - /** - * Assert a date can be parsed using a given format. - */ - public function testDateParser(): void - { - $date = \DateTime::createFromFormat('d/m/Y', '01/01/2001'); - $result = $this->processManager->execute('test.date_transformers.date_parser', '2001-01-01'); - - // There could be a 1s difference, depending on execution time... - $date->setTime(0, 0); - $result->setTime(0, 0); - - self::assertInstanceOf(\DateTime::class, $result); - if ($result instanceof \DateTime) { - self::assertEquals($date->getTimestamp(), $result->getTimestamp()); - } - } - - /** - * Assert that a date is not parsed if the format doesn't match. - */ - public function testDateParserError(): void - { - $this->setExpectedException(\RuntimeException::class); - - $this->processManager->execute('test.date_transformers.date_parser', '2001-01-01T00:00:00+00:00'); - } - - /** - * Assert date parser & formatter can be chained to transform a date string into another. - */ - public function testDateParseFormat(): void - { - $result = $this->processManager->execute( - 'test.date_transformers.date_parse_format', - '2001-01-01T00:00:00+00:00' - ); - self::assertEquals('2001-01-01', $result); - } -} diff --git a/tests.old/Transformer/GenericTransformersTest.php b/tests.old/Transformer/GenericTransformersTest.php deleted file mode 100644 index 39adf0b2..00000000 --- a/tests.old/Transformer/GenericTransformersTest.php +++ /dev/null @@ -1,26 +0,0 @@ -assertTransformation('test.generic_transformers.simple', 'my_ok', 'my_ok'); - $this->assertTransformation('test.generic_transformers.simple', 'ok', null); - } - - public function testContextualOptions(): void - { - $this->assertTransformation('test.generic_transformers.contextual_options', 'my_ok', 'my_ok', [ - 'default_value' => 'ok', - ]); - $this->assertTransformation('test.generic_transformers.contextual_options', 'ok', null, [ - 'default_value' => 'ok', - ]); - } -} diff --git a/tests.old/Transformer/HashTransformerTest.php b/tests.old/Transformer/HashTransformerTest.php deleted file mode 100644 index 16c74980..00000000 --- a/tests.old/Transformer/HashTransformerTest.php +++ /dev/null @@ -1,43 +0,0 @@ -processManager->execute('test.hash_transformer.md5', 'This is a string'); - self::assertEquals('41fb5b5ae4d57c5ee528adb00e5e8e74', $result); - } - - /** - * Assert a string can be hash in sha512. - */ - public function testSha512Hash(): void - { - $result = $this->processManager->execute('test.hash_transformer.sha512', 'This is a string'); - self::assertEquals( - 'f4d54d32e3523357ff023903eaba2721e8c8cfc7702663782cb3e52faf2c56c002cc3096b5f2b6df870be665d0040e9963590eb02d03d166e52999cd1c430db1', - $result - ); - } -} diff --git a/tests.old/Transformer/MappingTransformerTest.php b/tests.old/Transformer/MappingTransformerTest.php deleted file mode 100644 index c3156adb..00000000 --- a/tests.old/Transformer/MappingTransformerTest.php +++ /dev/null @@ -1,134 +0,0 @@ -processManager->execute('test.mapping_transformer.simple', [ - 'field' => 'value', - ]); - - self::assertEquals([ - 'field2' => 'value', - ], $result); - } - - /** - * Assert that if "ignore_missing" is false, then an error is thrown for missing fields. - */ - public function testMissingMapping(): void - { - $this->setExpectedException(\RuntimeException::class); - - $this->processManager->execute('test.mapping_transformer.error', [ - 'field' => 'value', - ]); - } - - /** - * Assert we can use multiple times the same sub-transformer using # suffixes. - */ - public function testMultiSubtransformers(): void - { - $result = $this->processManager->execute( - 'test.mapping_transformer.multi_subtransformers', - [ - 'field' => [3, null, 4, 2], - ] - ); - - self::assertEquals([ - 'field2' => [2, 4, 3], - ], $result); - } - - /** - * Assert we can use a deep property path as a key to generate a multi-depth array. - */ - public function testDeepMapping(): void - { - $result = $this->processManager->execute('test.mapping_transformer.deep_mapping', [ - 'value' => 'ok', - ]); - - self::assertEquals([ - 'field1' => [ - 'field2' => [ - 'field3' => 'ok', - ], - ], - ], $result); - } - - /** - * Test the '.' source property path. - */ - public function testFullInput(): void - { - $result = $this->processManager->execute('test.mapping_transformer.full_input', [ - 'value' => 'ok', - ]); - - self::assertEquals([ - 'out' => [ - 'value' => 'ok', - ], - ], $result); - } - - /** - * Test the '.' source property path inside an array of source codes. - */ - public function testFullInputInArray(): void - { - $result = $this->processManager->execute('test.mapping_transformer.full_input_in_array', [ - 'field' => 'ok', - ]); - - self::assertEquals([ - 'out' => [ - 'some_field' => 'ok', - 'full' => [ - 'field' => 'ok', - ], - ], - ], $result); - } - - /** - * Test that a source property can be an array with numeric keys (see commit e141cb61). - */ - public function testMultiSourceFieldInSequence(): void - { - $result = $this->processManager->execute('test.mapping_transformer.multi_source_field_in_sequence', [ - 'field1' => 'a', - 'field2' => 'b', - 'field3' => 'c', - ]); - - self::assertEquals([ - 'out' => ['a', 'b', 'c'], - ], $result); - } -} diff --git a/tests.old/Transformer/RulesTransformerTest.php b/tests.old/Transformer/RulesTransformerTest.php deleted file mode 100644 index 40375bbf..00000000 --- a/tests.old/Transformer/RulesTransformerTest.php +++ /dev/null @@ -1,34 +0,0 @@ -processManager->execute('test.rules_transformer.simple', 'ok'); - self::assertEquals('result1', $result1); - - $result2 = $this->processManager->execute('test.rules_transformer.simple', 'ko'); - self::assertEquals('result2', $result2); - - $result3 = $this->processManager->execute('test.rules_transformer.simple', 'any'); - self::assertEquals('result3', $result3); - } -} diff --git a/tests.old/Transformer/TransformerExceptionTest.php b/tests.old/Transformer/TransformerExceptionTest.php deleted file mode 100644 index 7052ef9b..00000000 --- a/tests.old/Transformer/TransformerExceptionTest.php +++ /dev/null @@ -1,60 +0,0 @@ -getMessage()); - } - - /** - * Simple test case using a simulated error inside a mapping transformer and array_map transformers. - */ - public function testDeepError(): void - { - $input = [ - 'field' => [ - [ - ['a', 'b'], - 1, // Error here - ], - ], - ]; - - $message = null; - try { - $this->processManager->execute('test.transformer_exception.deep', $input); - } catch (\RuntimeException $exception) { - $message = $exception->getMessage(); - } - - self::assertNotNull($message); - self::assertContains("For target property '1', transformation 'implode' have failed", $message); - } -} diff --git a/tests.old/Transformer/TypeSetterTransformerTest.php b/tests.old/Transformer/TypeSetterTransformerTest.php deleted file mode 100644 index da8e88f1..00000000 --- a/tests.old/Transformer/TypeSetterTransformerTest.php +++ /dev/null @@ -1,49 +0,0 @@ -processManager->execute('test.type_setter_transformer.int_to_int', 1); - self::assertSame(1, $result); - } - - /** - * Assert string to int convertion. - */ - public function testStringToInt(): void - { - $result = $this->processManager->execute('test.type_setter_transformer.string_to_int', '1'); - self::assertSame(1, $result); - } - - /** - * Assert int to string convertion. - */ - public function testIntToString(): void - { - $result = $this->processManager->execute('test.type_setter_transformer.int_to_string', 1); - self::assertSame('1', $result); - } -} diff --git a/tests.old/Transformer/UnsetTransformerTest.php b/tests.old/Transformer/UnsetTransformerTest.php deleted file mode 100644 index 6562800f..00000000 --- a/tests.old/Transformer/UnsetTransformerTest.php +++ /dev/null @@ -1,103 +0,0 @@ - 1, - 'to_unset' => 1, - 'to_test' => 2, - ]; - $result = $this->processManager->execute('test.unset_transformer.simple', $input); - self::assertEquals([ - 'other' => 1, - 'to_test' => 2, - ], $result); - } - - /** - * Assert a few simple condition can trigger unset (or not). - */ - public function testConditionalUnset(): void - { - $input = [ - 'other' => 1, - 'to_unset' => 1, - 'to_test' => 2, - ]; - - // Should unset - $result = $this->processManager->execute('test.unset_transformer.condition', $input); - self::assertEquals([ - 'other' => 1, - 'to_test' => 2, - ], $result); - - // No unset - $input['to_test'] = 3; - $result = $this->processManager->execute('test.unset_transformer.condition', $input); - self::assertEquals([ - 'other' => 1, - 'to_unset' => 1, - 'to_test' => 3, - ], $result); - - // Checking null, no unset - $result = $this->processManager->execute('test.unset_transformer.condition_null', $input); - self::assertEquals([ - 'other' => 1, - 'to_unset' => 1, - 'to_test' => 3, - ], $result); - - // Should unset - $input['to_test'] = null; - $result = $this->processManager->execute('test.unset_transformer.condition_null', $input); - self::assertEquals([ - 'other' => 1, - 'to_test' => null, - ], $result); - } - - /** - * Assert the transformer detect wrong types. - */ - public function testWrongUnsetString(): void - { - $this->setExpectedException(\RuntimeException::class); - - $this->processManager->execute('test.unset_transformer.simple', 'not an array'); - } - - /** - * Assert the transformer detect wrong values. - */ - public function testWrongUnsetMissingProperty(): void - { - $this->setExpectedException(\RuntimeException::class); - - $this->processManager->execute('test.unset_transformer.simple', ['no property found']); - } -} diff --git a/tests.old/Transformer/XpathEvaluatorTransformerTest.php b/tests.old/Transformer/XpathEvaluatorTransformerTest.php deleted file mode 100644 index a1cc61ec..00000000 --- a/tests.old/Transformer/XpathEvaluatorTransformerTest.php +++ /dev/null @@ -1,92 +0,0 @@ -loadXML('ok1ok2ok3'); - - $node = $domDocument->getElementsByTagName('b')[0]; - $this->assertTransformation('xpath_evaluator', ['ok1', 'ok2', 'ok3'], $node, [ - 'query' => ['./c/text()', './d/text()', './e/text()'], - ]); - } - - public function testMultiQueryWithKey(): void - { - $domDocument = new \DOMDocument(); - $domDocument->loadXML('ok1ok2ok3'); - - $node = $domDocument->getElementsByTagName('b')[0]; - $this->assertTransformation('xpath_evaluator', [ - 'c' => 'ok1', - 'd' => 'ok2', - 'e' => 'ok3', - ], $node, [ - 'query' => [ - 'c' => './c/text()', - 'd' => './d/text()', - 'e' => './e/text()', - ], - ]); - } - - public function testOverridableSubqueries(): void - { - $xml = << - - ok1 - ok2 - ok3 - - - ok4 - ok5 - ok6 - - -XML; - $domDocument = new \DOMDocument(); - $domDocument->loadXML($xml); - - $node = $domDocument->getElementsByTagName('b')[0]; - $this->assertTransformation('xpath_evaluator', [ - 'all_c_values' => ['ok1', 'ok2', 'ok3'], - 'e_value' => 'ok4', - 'f_value' => 'ok5', - ], $node, [ - 'query' => [ - 'all_c_values' => [ - 'subquery' => '/a/b/c/text()', - 'single_result' => false, - ], - 'e_value' => '/a/d/e/text()', - 'f_value' => [ - 'subquery' => '/a/d/f/text()', - ], - ], - ]); - } -} diff --git a/tests/Task/AggregateIterableTaskTest.php b/tests/Task/AggregateIterableTaskTest.php new file mode 100644 index 00000000..8c79f0fe --- /dev/null +++ b/tests/Task/AggregateIterableTaskTest.php @@ -0,0 +1,83 @@ +createState(); + $object = new \stdClass(); + + foreach ([1, 'two', ['three'], null, $object] as $input) { + $state->setInput($input); + $task->execute($state); + self::assertNull($state->getOutput()); + self::assertFalse($state->isSkipped()); + } + + $task->proceed($state); + + self::assertFalse($state->isSkipped()); + self::assertSame([1, 'two', ['three'], null, $object], $state->getOutput()); + } + + public function testIdenticalInputsAreAllKept(): void + { + $task = new AggregateIterableTask(); + $state = $this->createState(); + + foreach (['a', 'a', 'a'] as $input) { + $state->setInput($input); + $task->execute($state); + } + $task->proceed($state); + + self::assertSame(['a', 'a', 'a'], $state->getOutput()); + } + + public function testProceedWithoutInputIsSkipped(): void + { + $task = new AggregateIterableTask(); + $state = $this->createState(); + + $task->proceed($state); + + self::assertTrue($state->isSkipped()); + self::assertNull($state->getOutput()); + } + + private function createState(): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setSkipped(false); + $state->setTaskConfiguration(new TaskConfiguration('aggregate', AggregateIterableTask::class, [])); + + return $state; + } +} diff --git a/tests/Task/ArrayMergeTaskTest.php b/tests/Task/ArrayMergeTaskTest.php new file mode 100644 index 00000000..e1f251c9 --- /dev/null +++ b/tests/Task/ArrayMergeTaskTest.php @@ -0,0 +1,153 @@ +, list>, array}> + */ + public static function mergeProvider(): iterable + { + $inputs = [ + ['a' => 1, 'b' => ['c' => 2], 0 => 'x'], + ['b' => ['d' => 3], 0 => 'y'], + ]; + + yield 'default is array_merge' => [[], $inputs, ['a' => 1, 'b' => ['d' => 3], 0 => 'x', 1 => 'y']]; + yield 'array_merge' => [ + ['merge_function' => 'array_merge'], + $inputs, + ['a' => 1, 'b' => ['d' => 3], 0 => 'x', 1 => 'y'], + ]; + yield 'array_merge_recursive' => [ + ['merge_function' => 'array_merge_recursive'], + $inputs, + ['a' => 1, 'b' => ['c' => 2, 'd' => 3], 0 => 'x', 1 => 'y'], + ]; + yield 'array_replace' => [ + ['merge_function' => 'array_replace'], + $inputs, + ['a' => 1, 'b' => ['d' => 3], 0 => 'y'], + ]; + yield 'array_replace_recursive' => [ + ['merge_function' => 'array_replace_recursive'], + $inputs, + ['a' => 1, 'b' => ['c' => 2, 'd' => 3], 0 => 'y'], + ]; + } + + /** + * @param list> $inputs + */ + #[DataProvider('mergeProvider')] + public function testInputsAreMergedWithMergeFunction(array $options, array $inputs, array $expected): void + { + $task = new ArrayMergeTask(); + $state = $this->createState($options); + $task->initialize($state); + + foreach ($inputs as $input) { + $state->setInput($input); + $task->execute($state); + self::assertNull($state->getOutput(), 'Blocking task must not output before proceed'); + } + $task->proceed($state); + + self::assertSame($expected, $state->getOutput()); + } + + public function testProceedWithoutInputOutputsEmptyArray(): void + { + $task = new ArrayMergeTask(); + $state = $this->createState([]); + $task->initialize($state); + + $task->proceed($state); + + self::assertSame([], $state->getOutput()); + } + + /** + * @return iterable + */ + public static function nonArrayInputProvider(): iterable + { + yield 'string' => ['foo']; + yield 'int' => [1]; + yield 'null' => [null]; + yield 'object' => [new \stdClass()]; + } + + #[DataProvider('nonArrayInputProvider')] + public function testNonArrayInputThrowsException(mixed $input): void + { + $task = new ArrayMergeTask(); + $state = $this->createState([]); + $task->initialize($state); + $state->setInput($input); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Input must be an array'); + $task->execute($state); + } + + /** + * @return iterable + */ + public static function invalidMergeFunctionProvider(): iterable + { + yield 'unknown function' => ['array_combine']; + yield 'non string' => [['array_merge']]; + } + + #[DataProvider('invalidMergeFunctionProvider')] + public function testInvalidMergeFunctionIsRejected(mixed $mergeFunction): void + { + $task = new ArrayMergeTask(); + $state = $this->createState(['merge_function' => $mergeFunction]); + + $this->expectException(InvalidOptionsException::class); + $task->initialize($state); + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('merge', ArrayMergeTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/ConstantIterableOutputTaskTest.php b/tests/Task/ConstantIterableOutputTaskTest.php new file mode 100644 index 00000000..04697d9a --- /dev/null +++ b/tests/Task/ConstantIterableOutputTaskTest.php @@ -0,0 +1,145 @@ +createState(['output' => ['id' => 123, 'firstname' => 'Test1', 'lastname' => 'Test2']]); + $task->initialize($state); + + self::assertSame([123, 'Test1', 'Test2'], $this->iterate($task, $state)); + } + + public function testIterationKeyIsSetInErrorContext(): void + { + $task = new ConstantIterableOutputTask(); + $state = $this->createState(['output' => ['a' => 'foo', 'b' => 'bar']]); + $task->initialize($state); + + $task->execute($state); + self::assertSame(['iterator_key' => 'a'], $state->getErrorContext()); + self::assertTrue($task->next($state)); + + $task->execute($state); + self::assertSame(['iterator_key' => 'b'], $state->getErrorContext()); + self::assertFalse($task->next($state)); + self::assertSame([], $state->getErrorContext()); + } + + public function testInputIsIgnored(): void + { + $task = new ConstantIterableOutputTask(); + $state = $this->createState(['output' => ['foo', 'bar']], ['ignored', 'input', 'values']); + $task->initialize($state); + + self::assertSame(['foo', 'bar'], $this->iterate($task, $state)); + } + + public function testIterationRestartsOnNextInput(): void + { + $task = new ConstantIterableOutputTask(); + $state = $this->createState(['output' => ['foo', 'bar']], 'first'); + $task->initialize($state); + + self::assertSame(['foo', 'bar'], $this->iterate($task, $state)); + + $state->setInput('second'); + self::assertSame(['foo', 'bar'], $this->iterate($task, $state)); + } + + public function testEmptyOutputIsSkipped(): void + { + $task = new ConstantIterableOutputTask(); + $state = $this->createState(['output' => []]); + $task->initialize($state); + + $task->execute($state); + + self::assertTrue($state->isSkipped()); + self::assertFalse($task->next($state)); + } + + public function testNonArrayOutputIsRejected(): void + { + $task = new ConstantIterableOutputTask(); + $state = $this->createState(['output' => 'foo']); + + $this->expectException(InvalidOptionsException::class); + $task->initialize($state); + } + + public function testMissingOutputOptionIsRejected(): void + { + $task = new ConstantIterableOutputTask(); + $state = $this->createState([]); + + $this->expectException(MissingOptionsException::class); + $task->initialize($state); + } + + /** + * Mimic the process manager loop on an iterable task. + * + * @return list + */ + private function iterate(ConstantIterableOutputTask $task, ProcessState $state): array + { + $outputs = []; + do { + $state->setSkipped(false); + $task->execute($state); + if (!$state->isSkipped()) { + $outputs[] = $state->getOutput(); + } + } while ($task->next($state)); + + return $outputs; + } + + private function createState(array $options, mixed $input = null): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('constant', ConstantIterableOutputTask::class, $options)); + $state->setInput($input); + $state->reset(false); + + return $state; + } +} diff --git a/tests/Task/ConstantOutputTaskTest.php b/tests/Task/ConstantOutputTaskTest.php new file mode 100644 index 00000000..4b29355d --- /dev/null +++ b/tests/Task/ConstantOutputTaskTest.php @@ -0,0 +1,107 @@ + + */ + public static function outputProvider(): iterable + { + yield 'array' => [['id' => 123, 'firstname' => 'Test1']]; + yield 'string' => ['foo']; + yield 'int' => [42]; + yield 'bool' => [false]; + yield 'null' => [null]; + } + + #[DataProvider('outputProvider')] + public function testOutputIsTheConfiguredValue(mixed $output): void + { + $task = new ConstantOutputTask(); + $state = $this->createState(['output' => $output], 'ignored input'); + $task->initialize($state); + + $task->execute($state); + + self::assertSame($output, $state->getOutput()); + self::assertFalse($state->isSkipped()); + } + + public function testInputIsIgnored(): void + { + $task = new ConstantOutputTask(); + $state = $this->createState(['output' => 'constant'], 'first'); + $task->initialize($state); + + $task->execute($state); + self::assertSame('constant', $state->getOutput()); + + $state->setInput(['second']); + $task->execute($state); + self::assertSame('constant', $state->getOutput()); + } + + public function testOutputIsResolvedFromContext(): void + { + $task = new ConstantOutputTask(); + $state = $this->createState(['output' => '{{ value }}'], null, ['value' => 'from context']); + $task->initialize($state); + + $task->execute($state); + + self::assertSame('from context', $state->getOutput()); + } + + public function testMissingOutputOptionFailsAtInitialization(): void + { + $task = new ConstantOutputTask(); + $state = $this->createState([]); + + $this->expectException(MissingOptionsException::class); + $task->initialize($state); + } + + private function createState(array $options, mixed $input = null, array $context = []): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext($context); + $state->setTaskConfiguration(new TaskConfiguration('constant', ConstantOutputTask::class, $options)); + $state->setInput($input); + $state->reset(false); + + return $state; + } +} diff --git a/tests/Task/Debug/DebugTaskTest.php b/tests/Task/Debug/DebugTaskTest.php new file mode 100644 index 00000000..ada89697 --- /dev/null +++ b/tests/Task/Debug/DebugTaskTest.php @@ -0,0 +1,96 @@ + */ + private array $dumped = []; + + private ?\Closure $previousHandler = null; + + protected function setUp(): void + { + $this->dumped = []; + $previousHandler = VarDumper::setHandler(function (mixed $var): void { + $this->dumped[] = $var; + }); + $this->previousHandler = null === $previousHandler ? null : \Closure::fromCallable($previousHandler); + } + + protected function tearDown(): void + { + VarDumper::setHandler($this->previousHandler); + } + + /** + * @return iterable + */ + public static function inputProvider(): iterable + { + yield 'string' => ['foo']; + yield 'int' => [42]; + yield 'array' => [['id' => 123, 'firstname' => 'Test1']]; + yield 'object' => [new \ArrayObject(['foo' => 'bar'])]; + yield 'null' => [null]; + } + + #[DataProvider('inputProvider')] + public function testInputIsDumpedAndForwardedToTheOutput(mixed $input): void + { + $state = $this->createState($input); + + (new DebugTask())->execute($state); + + self::assertSame([$input], $this->dumped); + self::assertSame($input, $state->getOutput()); + self::assertFalse($state->isSkipped()); + } + + public function testEachExecutionDumpsItsOwnInput(): void + { + $task = new DebugTask(); + $outputs = []; + foreach (['a', 'b'] as $input) { + $state = $this->createState($input); + $task->execute($state); + $outputs[] = $state->getOutput(); + } + + self::assertSame(['a', 'b'], $this->dumped); + self::assertSame(['a', 'b'], $outputs); + } + + private function createState(mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->reset(false); + $state->setInput($input); + + return $state; + } +} diff --git a/tests/Task/Debug/DieTaskTest.php b/tests/Task/Debug/DieTaskTest.php new file mode 100644 index 00000000..45c50669 --- /dev/null +++ b/tests/Task/Debug/DieTaskTest.php @@ -0,0 +1,57 @@ +setInput('foo'); + echo 'before;'; + try { + (new DieTask())->execute(\$state); + } finally { + echo 'finally;'; + } + echo 'after;'; + PHP; + + $process = new PhpProcess($script); + $process->run(); + + self::assertSame('', $process->getErrorOutput()); + self::assertSame(0, $process->getExitCode()); + self::assertSame('before;', $process->getOutput()); + } +} diff --git a/tests/Task/Debug/ErrorForwarderTaskTest.php b/tests/Task/Debug/ErrorForwarderTaskTest.php new file mode 100644 index 00000000..c7713787 --- /dev/null +++ b/tests/Task/Debug/ErrorForwarderTaskTest.php @@ -0,0 +1,65 @@ + + */ + public static function inputProvider(): iterable + { + yield 'string' => ['Error 1']; + yield 'int' => [42]; + yield 'array' => [['id' => 123]]; + yield 'object' => [new \ArrayObject(['foo' => 'bar'])]; + yield 'null' => [null]; + } + + #[DataProvider('inputProvider')] + public function testInputIsForwardedToTheErrorOutputAndTaskIsSkipped(mixed $input): void + { + $state = $this->execute($input); + + self::assertTrue($state->isSkipped()); + self::assertTrue($state->hasErrorOutput()); + self::assertSame($input, $state->getErrorOutput()); + self::assertNull($state->getOutput()); + self::assertNull($state->getException()); + self::assertFalse($state->isStopped()); + } + + private function execute(mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->reset(false); + $state->setInput($input); + + (new ErrorForwarderTask())->execute($state); + + return $state; + } +} diff --git a/tests/Task/Debug/StopwatchTaskTest.php b/tests/Task/Debug/StopwatchTaskTest.php new file mode 100644 index 00000000..b06baccb --- /dev/null +++ b/tests/Task/Debug/StopwatchTaskTest.php @@ -0,0 +1,107 @@ +start('first', 'cat1'); + $stopwatch->stop('first'); + $stopwatch->start('second', 'cat2'); + $logger = $this->createLogger(); + + $state = $this->execute($logger, $stopwatch, 'input'); + + self::assertCount(2, $logger->records); + self::assertSame([LogLevel::INFO, LogLevel::INFO], array_column($logger->records, 'level')); + self::assertSame($stopwatch->getEvent('first'), $logger->records[0]['message']); + self::assertSame($stopwatch->getEvent('second'), $logger->records[1]['message']); + self::assertStringStartsWith('cat1/first: ', (string) $logger->records[0]['message']); + self::assertStringStartsWith('cat2/second: ', (string) $logger->records[1]['message']); + self::assertNull($state->getOutput()); + self::assertFalse($state->isSkipped()); + } + + public function testEventsOfOtherSectionsAreNotLogged(): void + { + $stopwatch = new Stopwatch(); + $stopwatch->openSection(); + $stopwatch->start('nested'); + $stopwatch->stop('nested'); + $stopwatch->stopSection('section'); + $logger = $this->createLogger(); + + $this->execute($logger, $stopwatch, null); + + self::assertNotSame([], $stopwatch->getSectionEvents('section')); + foreach ($logger->records as $record) { + self::assertInstanceOf(StopwatchEvent::class, $record['message']); + self::assertStringNotContainsString('nested', (string) $record['message']); + } + } + + public function testNothingIsLoggedWithoutEvent(): void + { + $logger = $this->createLogger(); + + $state = $this->execute($logger, new Stopwatch(), 'input'); + + self::assertSame([], $logger->records); + self::assertNull($state->getOutput()); + } + + private function execute(AbstractLogger $logger, Stopwatch $stopwatch, mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->reset(false); + $state->setInput($input); + + (new StopwatchTask($logger, $stopwatch))->execute($state); + + return $state; + } + + /** + * @return AbstractLogger&object{records: list}>} + */ + private function createLogger(): AbstractLogger + { + return new class extends AbstractLogger { + /** @var list}> */ + public array $records = []; + + public function log($level, string|\Stringable $message, array $context = []): void + { + $this->records[] = ['level' => $level, 'message' => $message, 'context' => $context]; + } + }; + } +} diff --git a/tests/Task/DummyTaskTest.php b/tests/Task/DummyTaskTest.php new file mode 100644 index 00000000..8b0e4af6 --- /dev/null +++ b/tests/Task/DummyTaskTest.php @@ -0,0 +1,56 @@ + + */ + public static function inputProvider(): iterable + { + yield 'array' => [['id' => 123]]; + yield 'object' => [new \stdClass()]; + yield 'string' => ['foo']; + yield 'int' => [0]; + yield 'empty array' => [[]]; + yield 'null' => [null]; + } + + #[DataProvider('inputProvider')] + public function testInputIsPassedToOutputUnchanged(mixed $input): void + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setInput($input); + $state->reset(false); + + (new DummyTask())->execute($state); + + self::assertSame($input, $state->getOutput()); + self::assertFalse($state->isSkipped()); + self::assertFalse($state->isStopped()); + } +} diff --git a/tests/Task/File/Csv/CsvWriterTaskTest.php b/tests/Task/File/Csv/CsvWriterTaskTest.php new file mode 100644 index 00000000..2059c265 --- /dev/null +++ b/tests/Task/File/Csv/CsvWriterTaskTest.php @@ -0,0 +1,285 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('csv_writer_test_', true); + } + + protected function tearDown(): void + { + (new Filesystem())->remove($this->tmpDir); + } + + public function testWritesHeadersFromFirstInputKeysAndOutputsFilePath(): void + { + $filePath = $this->tmpDir.'/out.csv'; + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $filePath]); + + $this->write($task, $state, [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]); + + self::assertSame($filePath, $state->getOutput()); + self::assertSame("id;name\n1;foo\n2;bar\n", file_get_contents($filePath)); + } + + public function testCreatesMissingParentDirectory(): void + { + $filePath = $this->tmpDir.'/sub/dir/out.csv'; + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $filePath]); + + $this->write($task, $state, [['id' => 1]]); + + self::assertFileExists($filePath); + } + + public function testWritesColumnsInStaticHeadersOrder(): void + { + $filePath = $this->tmpDir.'/out.csv'; + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $filePath, 'headers' => ['name', 'id']]); + + $this->write($task, $state, [['id' => 1, 'name' => 'foo']]); + + self::assertSame("name;id\nfoo;1\n", file_get_contents($filePath)); + } + + public function testDoesNotWriteHeadersWhenDisabled(): void + { + $filePath = $this->tmpDir.'/out.csv'; + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $filePath, 'write_headers' => false]); + + $this->write($task, $state, [['id' => 1, 'name' => 'foo']]); + + self::assertSame("1;foo\n", file_get_contents($filePath)); + } + + public function testUsesDelimiterEnclosureAndSplitCharacterOptions(): void + { + $filePath = $this->tmpDir.'/out.csv'; + $task = new CsvWriterTask(); + $state = $this->createState([ + 'file_path' => $filePath, + 'delimiter' => ',', + 'enclosure' => "'", + 'split_character' => '/', + ]); + + $this->write($task, $state, [['id' => 1, 'tags' => ['a', 'b'], 'label' => 'x,y']]); + + self::assertSame("id,tags,label\n1,a/b,'x,y'\n", file_get_contents($filePath)); + } + + public function testImplodesArrayValuesWithDefaultSplitCharacter(): void + { + $filePath = $this->tmpDir.'/out.csv'; + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $filePath]); + + $this->write($task, $state, [['tags' => ['a', 'b', 'c']]]); + + self::assertSame("tags\na|b|c\n", file_get_contents($filePath)); + } + + public function testDefaultModeOverwritesExistingFile(): void + { + $filePath = $this->tmpDir.'/out.csv'; + (new Filesystem())->dumpFile($filePath, "old;content\n"); + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $filePath]); + + $this->write($task, $state, [['id' => 1]]); + + self::assertSame("id\n1\n", file_get_contents($filePath)); + } + + public function testAppendModeDoesNotRewriteHeadersInNonEmptyFile(): void + { + $filePath = $this->tmpDir.'/out.csv'; + (new Filesystem())->dumpFile($filePath, "id;name\n1;foo\n"); + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $filePath, 'mode' => 'ab', 'headers' => ['id', 'name']]); + + $this->write($task, $state, [['id' => 2, 'name' => 'bar']]); + + self::assertSame("id;name\n1;foo\n2;bar\n", file_get_contents($filePath)); + } + + public function testAppendModeWritesHeadersInEmptyFile(): void + { + $filePath = $this->tmpDir.'/out.csv'; + (new Filesystem())->dumpFile($filePath, ''); + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $filePath, 'mode' => 'ab', 'headers' => ['id']]); + + $this->write($task, $state, [['id' => 1]]); + + self::assertSame("id\n1\n", file_get_contents($filePath)); + } + + /** + * @return iterable + */ + public static function placeholderProvider(): iterable + { + yield 'date' => ['out_{date}.csv', '/^out_\d{8}\.csv$/']; + yield 'date_time' => ['out_{date_time}.csv', '/^out_\d{8}_\d{6}\.csv$/']; + yield 'timestamp' => ['out_{timestamp}.csv', '/^out_\d{10,}\.csv$/']; + yield 'unique_token' => ['out_{unique_token}.csv', '/^out_[0-9a-f]+\.\d+\.csv$/']; + } + + #[DataProvider('placeholderProvider')] + public function testReplacesPlaceholdersInFilePath(string $fileName, string $expectedPattern): void + { + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $this->tmpDir.'/'.$fileName]); + + $this->write($task, $state, [['id' => 1]]); + + $output = $state->getOutput(); + self::assertIsString($output); + self::assertSame($this->tmpDir, \dirname($output)); + self::assertMatchesRegularExpression($expectedPattern, basename($output)); + self::assertFileExists($output); + } + + public function testDatePlaceholderIsReplacedByCurrentDate(): void + { + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $this->tmpDir.'/out_{date}.csv']); + $expectedDate = date('Ymd'); + + $this->write($task, $state, [['id' => 1]]); + + self::assertSame($this->tmpDir.'/out_'.$expectedDate.'.csv', $state->getOutput()); + } + + public function testThrowsWhenInputIsNotAnArrayWithStaticHeaders(): void + { + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $this->tmpDir.'/out.csv', 'headers' => ['id']]); + $task->initialize($state); + $state->setInput('not an array'); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Input value is not an array'); + $task->execute($state); + } + + public function testThrowsWhenInputHasMissingColumn(): void + { + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $this->tmpDir.'/out.csv', 'headers' => ['id', 'name']]); + $task->initialize($state); + $state->setInput(['id' => 1, 'other' => 'foo']); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Missing column name'); + $task->execute($state); + } + + public function testThrowsWhenInputHasExtraColumn(): void + { + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $this->tmpDir.'/out.csv']); + $task->initialize($state); + $state->setInput(['id' => 1]); + $task->execute($state); + $state->setInput(['id' => 2, 'name' => 'extra']); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('invalid number of columns'); + $task->execute($state); + } + + public function testThrowsOnMissingFilePathOption(): void + { + $task = new CsvWriterTask(); + $state = $this->createState([]); + + $this->expectException(MissingOptionsException::class); + $task->initialize($state); + } + + public function testThrowsOnInvalidHeadersOptionType(): void + { + $task = new CsvWriterTask(); + $state = $this->createState(['file_path' => $this->tmpDir.'/out.csv', 'headers' => 'id']); + + $this->expectException(InvalidOptionsException::class); + $task->initialize($state); + } + + /** + * Mimics the ProcessManager behaviour for a blocking task: execute for each input, then proceed and finalize. + * + * @param list $inputs + */ + private function write(CsvWriterTask $task, ProcessState $state, array $inputs): void + { + $task->initialize($state); + foreach ($inputs as $input) { + $state->setInput($input); + $task->execute($state); + } + $task->proceed($state); + $task->finalize($state); + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('write', CsvWriterTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/File/FileMoverTaskTest.php b/tests/Task/File/FileMoverTaskTest.php new file mode 100644 index 00000000..11e53e18 --- /dev/null +++ b/tests/Task/File/FileMoverTaskTest.php @@ -0,0 +1,216 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('file_mover_test_'); + $this->filesystem = new Filesystem(); + $this->filesystem->dumpFile($this->tmpDir.'/src/file.csv', 'source'); + $this->filesystem->mkdir($this->tmpDir.'/dest'); + } + + protected function tearDown(): void + { + $this->filesystem->remove($this->tmpDir); + } + + public function testMovesFileToDestinationPath(): void + { + $destination = $this->tmpDir.'/dest/renamed.csv'; + + $state = $this->execute(['destination' => $destination], $this->tmpDir.'/src/file.csv'); + + self::assertSame($destination, $state->getOutput()); + self::assertFileDoesNotExist($this->tmpDir.'/src/file.csv'); + self::assertSame('source', file_get_contents($destination)); + } + + /** + * @return iterable + */ + public static function directoryDestinationProvider(): iterable + { + yield 'without trailing separator' => ['']; + yield 'with trailing separator' => [\DIRECTORY_SEPARATOR]; + } + + #[DataProvider('directoryDestinationProvider')] + public function testKeepsOriginalFileNameWhenDestinationIsADirectory(string $suffix): void + { + $state = $this->execute(['destination' => $this->tmpDir.'/dest'.$suffix], $this->tmpDir.'/src/file.csv'); + + self::assertSame($this->tmpDir.'/dest/file.csv', $state->getOutput()); + self::assertSame('source', file_get_contents($this->tmpDir.'/dest/file.csv')); + } + + public function testThrowsWhenInputFileDoesNotExist(): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('File does not exists'); + + $this->execute(['destination' => $this->tmpDir.'/dest'], $this->tmpDir.'/src/missing.csv'); + } + + public function testThrowsWhenDestinationExistsWithoutOverwrite(): void + { + $this->filesystem->dumpFile($this->tmpDir.'/dest/file.csv', 'existing'); + + try { + $this->execute(['destination' => $this->tmpDir.'/dest'], $this->tmpDir.'/src/file.csv'); + self::fail('An IOException should have been thrown'); + } catch (IOException) { + self::assertSame('existing', file_get_contents($this->tmpDir.'/dest/file.csv')); + self::assertFileExists($this->tmpDir.'/src/file.csv'); + } + } + + public function testOverwritesExistingDestinationWhenAllowed(): void + { + $this->filesystem->dumpFile($this->tmpDir.'/dest/file.csv', 'existing'); + + $state = $this->execute( + ['destination' => $this->tmpDir.'/dest', 'overwrite' => true], + $this->tmpDir.'/src/file.csv', + ); + + self::assertSame($this->tmpDir.'/dest/file.csv', $state->getOutput()); + self::assertSame('source', file_get_contents($this->tmpDir.'/dest/file.csv')); + self::assertFileDoesNotExist($this->tmpDir.'/src/file.csv'); + } + + public function testAutoincrementKeepsNameWhenDestinationIsFree(): void + { + $state = $this->execute( + ['destination' => $this->tmpDir.'/dest', 'autoincrement' => true], + $this->tmpDir.'/src/file.csv', + ); + + self::assertSame($this->tmpDir.'/dest/file.csv', $state->getOutput()); + } + + public function testAutoincrementAddsSuffixBeforeExtension(): void + { + $this->filesystem->dumpFile($this->tmpDir.'/dest/file.csv', 'existing'); + + $state = $this->execute( + ['destination' => $this->tmpDir.'/dest', 'autoincrement' => true], + $this->tmpDir.'/src/file.csv', + ); + + self::assertSame($this->tmpDir.'/dest/file-1.csv', $state->getOutput()); + self::assertSame('source', file_get_contents($this->tmpDir.'/dest/file-1.csv')); + self::assertSame('existing', file_get_contents($this->tmpDir.'/dest/file.csv')); + } + + public function testAutoincrementIncrementsExistingSuffix(): void + { + $this->filesystem->dumpFile($this->tmpDir.'/dest/file.csv', 'existing'); + $this->filesystem->dumpFile($this->tmpDir.'/dest/file-1.csv', 'existing 1'); + + $state = $this->execute( + ['destination' => $this->tmpDir.'/dest', 'autoincrement' => true], + $this->tmpDir.'/src/file.csv', + ); + + self::assertSame($this->tmpDir.'/dest/file-2.csv', $state->getOutput()); + self::assertSame('source', file_get_contents($this->tmpDir.'/dest/file-2.csv')); + } + + public function testAutoincrementAppendsSuffixToFileWithoutExtension(): void + { + $this->filesystem->dumpFile($this->tmpDir.'/src/file', 'source'); + $this->filesystem->dumpFile($this->tmpDir.'/dest/file', 'existing'); + + $state = $this->execute( + ['destination' => $this->tmpDir.'/dest', 'autoincrement' => true], + $this->tmpDir.'/src/file', + ); + + self::assertSame($this->tmpDir.'/dest/file-1', $state->getOutput()); + self::assertSame('source', file_get_contents($this->tmpDir.'/dest/file-1')); + } + + public function testThrowsOnMissingDestinationOption(): void + { + $this->expectException(MissingOptionsException::class); + + $this->execute([], $this->tmpDir.'/src/file.csv'); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'destination not a string' => [['destination' => ['foo']]]; + yield 'overwrite not a boolean' => [['destination' => 'foo', 'overwrite' => 'yes']]; + yield 'autoincrement not a boolean' => [['destination' => 'foo', 'autoincrement' => 1]]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testThrowsOnInvalidOptions(array $options): void + { + $this->expectException(InvalidOptionsException::class); + + $this->execute($options, $this->tmpDir.'/src/file.csv'); + } + + private function execute(array $options, mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('move', FileMoverTask::class, $options)); + + $task = new FileMoverTask(); + $task->initialize($state); + $state->setInput($input); + $task->execute($state); + + return $state; + } +} diff --git a/tests/Task/File/FileReaderTaskTest.php b/tests/Task/File/FileReaderTaskTest.php new file mode 100644 index 00000000..fc85b339 --- /dev/null +++ b/tests/Task/File/FileReaderTaskTest.php @@ -0,0 +1,127 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('file_reader_test_', true); + (new Filesystem())->dumpFile($this->tmpDir.'/sample.txt', "line 1\nline 2\n"); + } + + protected function tearDown(): void + { + $filesystem = new Filesystem(); + $filesystem->chmod($this->tmpDir, 0o755, 0o000, true); + $filesystem->remove($this->tmpDir); + } + + public function testOutputsWholeFileContent(): void + { + $state = $this->execute(['filename' => $this->tmpDir.'/sample.txt']); + + self::assertSame("line 1\nline 2\n", $state->getOutput()); + } + + public function testIgnoresInput(): void + { + $state = $this->execute(['filename' => $this->tmpDir.'/sample.txt'], $this->tmpDir.'/other.txt'); + + self::assertSame("line 1\nline 2\n", $state->getOutput()); + } + + public function testOutputsEmptyStringForEmptyFile(): void + { + (new Filesystem())->dumpFile($this->tmpDir.'/empty.txt', ''); + + $state = $this->execute(['filename' => $this->tmpDir.'/empty.txt']); + + self::assertSame('', $state->getOutput()); + } + + public function testThrowsWhenFileDoesNotExist(): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("File does not exists: '{$this->tmpDir}/missing.txt'"); + + $this->execute(['filename' => $this->tmpDir.'/missing.txt']); + } + + public function testThrowsWhenFileIsNotReadable(): void + { + $filename = $this->tmpDir.'/sample.txt'; + chmod($filename, 0o000); + clearstatcache(); + if (is_readable($filename)) { + self::markTestSkipped('File permissions are not enforced for the current user (root?)'); + } + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("File is not readable: '{$filename}'"); + + $this->execute(['filename' => $filename]); + } + + public function testThrowsOnMissingFilenameOption(): void + { + $this->expectException(MissingOptionsException::class); + + $this->execute([]); + } + + public function testThrowsOnInvalidFilenameOptionType(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->execute(['filename' => 42]); + } + + private function execute(array $options, mixed $input = null): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('read', FileReaderTask::class, $options)); + + $task = new FileReaderTask(); + $task->initialize($state); + $state->setInput($input); + $task->execute($state); + + return $state; + } +} diff --git a/tests/Task/File/FileRemoverTaskTest.php b/tests/Task/File/FileRemoverTaskTest.php new file mode 100644 index 00000000..7ddf62e4 --- /dev/null +++ b/tests/Task/File/FileRemoverTaskTest.php @@ -0,0 +1,91 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('file_remover_test_', true); + $this->filesystem = new Filesystem(); + $this->filesystem->dumpFile($this->tmpDir.'/a.txt', 'A'); + $this->filesystem->dumpFile($this->tmpDir.'/b.txt', 'B'); + $this->filesystem->dumpFile($this->tmpDir.'/dir/sub/c.txt', 'C'); + } + + protected function tearDown(): void + { + $this->filesystem->remove($this->tmpDir); + } + + public function testRemovesFileGivenAsInput(): void + { + $state = $this->execute($this->tmpDir.'/a.txt'); + + self::assertFileDoesNotExist($this->tmpDir.'/a.txt'); + self::assertFileExists($this->tmpDir.'/b.txt'); + self::assertNull($state->getOutput()); + } + + public function testRemovesDirectoryRecursively(): void + { + $this->execute($this->tmpDir.'/dir'); + + self::assertDirectoryDoesNotExist($this->tmpDir.'/dir'); + self::assertFileExists($this->tmpDir.'/a.txt'); + } + + public function testRemovesEveryPathOfAList(): void + { + $this->execute([$this->tmpDir.'/a.txt', $this->tmpDir.'/dir']); + + self::assertFileDoesNotExist($this->tmpDir.'/a.txt'); + self::assertDirectoryDoesNotExist($this->tmpDir.'/dir'); + self::assertFileExists($this->tmpDir.'/b.txt'); + } + + public function testIgnoresMissingPath(): void + { + $state = $this->execute($this->tmpDir.'/missing.txt'); + + self::assertFileExists($this->tmpDir.'/a.txt'); + self::assertNull($state->getOutput()); + } + + private function execute(mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setInput($input); + + (new FileRemoverTask())->execute($state); + + return $state; + } +} diff --git a/tests/Task/File/FileWriterTaskTest.php b/tests/Task/File/FileWriterTaskTest.php new file mode 100644 index 00000000..7d22ecc7 --- /dev/null +++ b/tests/Task/File/FileWriterTaskTest.php @@ -0,0 +1,125 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('file_writer_test_', true); + } + + protected function tearDown(): void + { + (new Filesystem())->remove($this->tmpDir); + } + + public function testWritesInputAndOutputsFilename(): void + { + $filename = $this->tmpDir.'/result.txt'; + $task = new FileWriterTask(); + $state = $this->createState(['filename' => $filename]); + $task->initialize($state); + + $this->write($task, $state, "hello\nworld"); + + self::assertSame($filename, $state->getOutput()); + self::assertSame("hello\nworld", file_get_contents($filename)); + } + + public function testCreatesMissingParentDirectories(): void + { + $filename = $this->tmpDir.'/sub/dir/result.txt'; + $task = new FileWriterTask(); + $state = $this->createState(['filename' => $filename]); + $task->initialize($state); + + $this->write($task, $state, 'content'); + + self::assertSame('content', file_get_contents($filename)); + } + + public function testEachInputOverwritesTheFile(): void + { + $filename = $this->tmpDir.'/result.txt'; + (new Filesystem())->dumpFile($filename, 'previous content'); + $task = new FileWriterTask(); + $state = $this->createState(['filename' => $filename]); + $task->initialize($state); + + $this->write($task, $state, 'first'); + self::assertSame('first', file_get_contents($filename)); + + $this->write($task, $state, 'second'); + self::assertSame('second', file_get_contents($filename)); + } + + public function testThrowsOnMissingFilenameOption(): void + { + $task = new FileWriterTask(); + $state = $this->createState([]); + + $this->expectException(MissingOptionsException::class); + + $task->initialize($state); + } + + public function testThrowsOnInvalidFilenameOptionType(): void + { + $task = new FileWriterTask(); + $state = $this->createState(['filename' => ['result.txt']]); + + $this->expectException(InvalidOptionsException::class); + + $task->initialize($state); + } + + private function write(FileWriterTask $task, ProcessState $state, mixed $input): void + { + $state->setInput($input); + $task->execute($state); + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('write', FileWriterTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/File/InputFileReaderTaskTest.php b/tests/Task/File/InputFileReaderTaskTest.php new file mode 100644 index 00000000..bb4b8600 --- /dev/null +++ b/tests/Task/File/InputFileReaderTaskTest.php @@ -0,0 +1,138 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('input_file_reader_test_', true); + $filesystem = new Filesystem(); + $filesystem->dumpFile($this->tmpDir.'/a.txt', 'content A'); + $filesystem->dumpFile($this->tmpDir.'/b.txt', 'content B'); + } + + protected function tearDown(): void + { + $filesystem = new Filesystem(); + $filesystem->chmod($this->tmpDir, 0o755, 0o000, true); + $filesystem->remove($this->tmpDir); + } + + public function testOutputsContentOfFileGivenAsInput(): void + { + $task = new InputFileReaderTask(); + $state = $this->createState([]); + $task->initialize($state); + + self::assertSame('content A', $this->read($task, $state, $this->tmpDir.'/a.txt')); + } + + public function testReadsDifferentFilesSuccessively(): void + { + $task = new InputFileReaderTask(); + $state = $this->createState([]); + $task->initialize($state); + + self::assertSame( + ['content A', 'content B', 'content A'], + [ + $this->read($task, $state, $this->tmpDir.'/a.txt'), + $this->read($task, $state, $this->tmpDir.'/b.txt'), + $this->read($task, $state, $this->tmpDir.'/a.txt'), + ], + ); + } + + public function testThrowsWhenInputFileDoesNotExist(): void + { + $task = new InputFileReaderTask(); + $state = $this->createState([]); + $task->initialize($state); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("File does not exists: '{$this->tmpDir}/missing.txt'"); + + $this->read($task, $state, $this->tmpDir.'/missing.txt'); + } + + public function testThrowsWhenInputFileIsNotReadable(): void + { + $filename = $this->tmpDir.'/a.txt'; + chmod($filename, 0o000); + clearstatcache(); + if (is_readable($filename)) { + self::markTestSkipped('File permissions are not enforced for the current user (root?)'); + } + $task = new InputFileReaderTask(); + $state = $this->createState([]); + $task->initialize($state); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("File is not readable: '{$filename}'"); + + $this->read($task, $state, $filename); + } + + public function testRejectsFilenameOption(): void + { + $task = new InputFileReaderTask(); + $state = $this->createState(['filename' => $this->tmpDir.'/a.txt']); + + $this->expectException(UndefinedOptionsException::class); + + $task->initialize($state); + } + + private function read(InputFileReaderTask $task, ProcessState $state, mixed $input): mixed + { + $state->setInput($input); + $task->execute($state); + + return $state->getOutput(); + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('read', InputFileReaderTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/File/JsonStream/JsonStreamReaderTaskTest.php b/tests/Task/File/JsonStream/JsonStreamReaderTaskTest.php new file mode 100644 index 00000000..7ee3658d --- /dev/null +++ b/tests/Task/File/JsonStream/JsonStreamReaderTaskTest.php @@ -0,0 +1,252 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('json_stream_reader_test_', true); + $this->filesystem = new Filesystem(); + } + + protected function tearDown(): void + { + $this->filesystem->remove($this->tmpDir); + } + + public function testOutputsEachDecodedLine(): void + { + $file = $this->createFile("{\"id\":1,\"name\":\"foo\"}\n[1,2]\n{\"nested\":{\"a\":true}}\n"); + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + self::assertSame( + [['id' => 1, 'name' => 'foo'], [1, 2], ['nested' => ['a' => true]]], + $this->iterate($task, $state, $file), + ); + } + + public function testReadsLastLineWithoutTrailingNewline(): void + { + $file = $this->createFile("{\"a\":1}\n{\"b\":2}"); + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + self::assertSame([['a' => 1], ['b' => 2]], $this->iterate($task, $state, $file)); + } + + public function testSkipsEmptyAndNullLines(): void + { + $file = $this->createFile("{\"a\":1}\n\nnull\n{\"b\":2}\n\n"); + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + self::assertSame([['a' => 1], ['b' => 2]], $this->iterate($task, $state, $file)); + } + + public function testSkipsEmptyFile(): void + { + $file = $this->createFile(''); + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + self::assertSame([], $this->iterate($task, $state, $file)); + } + + public function testReadsSameFileAgainOnSecondExecution(): void + { + $file = $this->createFile("{\"a\":1}\n{\"b\":2}\n"); + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + $expected = [['a' => 1], ['b' => 2]]; + self::assertSame( + [$expected, $expected], + [$this->iterate($task, $state, $file), $this->iterate($task, $state, $file)], + ); + } + + public function testReadsDifferentFilesSuccessively(): void + { + $fileA = $this->createFile("{\"a\":1}\n{\"a\":2}\n", 'a.jsonl'); + $fileB = $this->createFile("{\"b\":1}\n", 'b.jsonl'); + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + self::assertSame([['a' => 1], ['a' => 2]], $this->iterate($task, $state, $fileA)); + self::assertSame([['b' => 1]], $this->iterate($task, $state, $fileB)); + } + + public function testThrowsOnInvalidJsonByDefault(): void + { + $file = $this->createFile("{\"a\":1}\n{invalid\n"); + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + $this->expectException(\JsonException::class); + + $this->iterate($task, $state, $file); + } + + public function testSkipsInvalidJsonWithoutJsonFlags(): void + { + $file = $this->createFile("{\"a\":1}\n{invalid\n{\"b\":2}\n"); + $task = new JsonStreamReaderTask(); + $state = $this->createState(['json_flags' => []]); + + self::assertSame([['a' => 1], ['b' => 2]], $this->iterate($task, $state, $file)); + } + + public function testAppliesJsonFlags(): void + { + $file = $this->createFile("{\"big\":123456789012345678901234567890}\n"); + $task = new JsonStreamReaderTask(); + $state = $this->createState(['json_flags' => [\JSON_THROW_ON_ERROR, \JSON_BIGINT_AS_STRING]]); + + self::assertSame([['big' => '123456789012345678901234567890']], $this->iterate($task, $state, $file)); + } + + public function testAppliesSplFileObjectFlags(): void + { + // Without any flag, the blank line is read as "\n" and fails to decode with the default JSON_THROW_ON_ERROR flag + $file = $this->createFile("{\"a\":1}\n\n{\"b\":2}\n"); + $task = new JsonStreamReaderTask(); + $state = $this->createState(['spl_file_object_flags' => []]); + + $this->expectException(\JsonException::class); + + $this->iterate($task, $state, $file); + } + + /** + * @return iterable + */ + public static function scalarLineProvider(): iterable + { + yield 'integer' => ['42', 'int']; + yield 'string' => ['"foo"', 'string']; + yield 'boolean' => ['true', 'bool']; + } + + #[DataProvider('scalarLineProvider')] + public function testThrowsOnScalarLine(string $line, string $type): void + { + $file = $this->createFile("{\"a\":1}\n{$line}\n"); + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage(\sprintf('Line 2 of file "%s" must be a JSON object or array, got %s', $file, $type)); + + $this->iterate($task, $state, $file); + } + + public function testThrowsWhenFileDoesNotExist(): void + { + $task = new JsonStreamReaderTask(); + $state = $this->createState([]); + + $this->expectException(\RuntimeException::class); + + $this->iterate($task, $state, $this->tmpDir.'/missing.jsonl'); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'spl_file_object_flags not an array' => [['spl_file_object_flags' => \SplFileObject::SKIP_EMPTY]]; + yield 'json_flags not an array' => [['json_flags' => \JSON_THROW_ON_ERROR]]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testThrowsOnInvalidOptions(array $options): void + { + $task = new JsonStreamReaderTask(); + $state = $this->createState($options); + + $this->expectException(InvalidOptionsException::class); + + $task->initialize($state); + } + + /** + * Mimics the ProcessManager loop over an iterable task and returns the non-skipped outputs. + * + * @return list + */ + private function iterate(JsonStreamReaderTask $task, ProcessState $state, string $input): array + { + $outputs = []; + $state->setInput($input); + do { + $state->setSkipped(false); + $task->execute($state); + if (!$state->isSkipped()) { + $outputs[] = $state->getOutput(); + } + } while ($task->next($state)); + + return $outputs; + } + + private function createFile(string $content, string $name = 'data.jsonl'): string + { + $path = $this->tmpDir.'/'.$name; + $this->filesystem->dumpFile($path, $content); + + return $path; + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('read', JsonStreamReaderTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/File/Xml/XmlReaderTaskTest.php b/tests/Task/File/Xml/XmlReaderTaskTest.php new file mode 100644 index 00000000..ca6689a6 --- /dev/null +++ b/tests/Task/File/Xml/XmlReaderTaskTest.php @@ -0,0 +1,187 @@ + */ + private array $logs = []; + + protected function setUp(): void + { + $this->tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('xml_reader_test_', true); + (new Filesystem())->dumpFile($this->tmpDir.'/file.xml', 'foobar'); + } + + protected function tearDown(): void + { + (new Filesystem())->remove($this->tmpDir); + } + + public function testOutputsDomDocumentOfTheFile(): void + { + $state = $this->execute(['file_path' => $this->tmpDir.'/file.xml']); + + $output = $state->getOutput(); + self::assertInstanceOf(\DOMDocument::class, $output); + self::assertSame('root', $output->documentElement?->nodeName); + self::assertSame(2, $output->getElementsByTagName('item')->length); + self::assertSame('bar', $output->getElementsByTagName('item')->item(1)?->textContent); + self::assertSame([], $this->logs); + } + + public function testInputIsIgnoredWithAWarning(): void + { + $state = $this->execute(['file_path' => $this->tmpDir.'/file.xml'], 'ignored input'); + + self::assertInstanceOf(\DOMDocument::class, $state->getOutput()); + self::assertSame([[LogLevel::WARNING, 'Input has been ignored for XMLReaderTask']], $this->logs); + } + + public function testCustomModeIsUsed(): void + { + $state = $this->execute(['file_path' => $this->tmpDir.'/file.xml', 'mode' => 'r']); + + self::assertInstanceOf(\DOMDocument::class, $state->getOutput()); + } + + public function testFileIsReadAgainOnEachExecution(): void + { + $task = $this->createTask(); + $state = $this->createState(['file_path' => $this->tmpDir.'/file.xml']); + $task->initialize($state); + + $task->execute($state); + $first = $state->getOutput(); + file_put_contents($this->tmpDir.'/file.xml', ''); + $task->execute($state); + $second = $state->getOutput(); + + self::assertInstanceOf(\DOMDocument::class, $first); + self::assertInstanceOf(\DOMDocument::class, $second); + self::assertNotSame($first, $second); + self::assertSame('other', $second->documentElement?->nodeName); + } + + public function testEmptyFileThrows(): void + { + file_put_contents($this->tmpDir.'/empty.xml', ''); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('is empty'); + + $this->execute(['file_path' => $this->tmpDir.'/empty.xml']); + } + + public function testInvalidXmlThrows(): void + { + file_put_contents($this->tmpDir.'/invalid.xml', '1'); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Invalid XML in file'); + + $this->execute(['file_path' => $this->tmpDir.'/invalid.xml']); + } + + public function testMissingFileThrows(): void + { + $this->expectException(\RuntimeException::class); + + $this->execute(['file_path' => $this->tmpDir.'/missing.xml']); + } + + public function testFilePathIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->execute([]); + } + + public function testFilePathMustBeAString(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->execute(['file_path' => 42]); + } + + public function testModeMustBeAString(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->execute(['file_path' => $this->tmpDir.'/file.xml', 'mode' => true]); + } + + private function execute(array $options, mixed $input = null): ProcessState + { + $task = $this->createTask(); + $state = $this->createState($options); + $state->setInput($input); + $task->initialize($state); + $task->execute($state); + + return $state; + } + + private function createTask(): XmlReaderTask + { + return new XmlReaderTask(new class(function (mixed $level, string $message): void { + $this->logs[] = [$level, $message]; + }) extends AbstractLogger { + public function __construct(private readonly \Closure $onLog) + { + } + + public function log($level, string|\Stringable $message, array $context = []): void + { + ($this->onLog)($level, (string) $message); + } + }); + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('read', XmlReaderTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/File/Xml/XmlWriterTaskTest.php b/tests/Task/File/Xml/XmlWriterTaskTest.php new file mode 100644 index 00000000..d91f3212 --- /dev/null +++ b/tests/Task/File/Xml/XmlWriterTaskTest.php @@ -0,0 +1,179 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('xml_writer_test_', true); + (new Filesystem())->mkdir($this->tmpDir); + } + + protected function tearDown(): void + { + (new Filesystem())->remove($this->tmpDir); + } + + public function testWritesTheDocumentAndOutputsTheFilePath(): void + { + $filePath = $this->tmpDir.'/file.xml'; + $task = new XmlWriterTask(new NullLogger()); + $state = $this->createState(['file_path' => $filePath]); + $state->setInput($this->createDocument('ok')); + $task->initialize($state); + + $task->execute($state); + + self::assertSame($filePath, $state->getOutput()); + self::assertSame("\nok\n", file_get_contents($filePath)); + } + + public function testEachExecutionOverwritesTheFileWithDefaultMode(): void + { + $filePath = $this->tmpDir.'/file.xml'; + $task = new XmlWriterTask(new NullLogger()); + $state = $this->createState(['file_path' => $filePath]); + $task->initialize($state); + + $state->setInput($this->createDocument('')); + $task->execute($state); + $state->setInput($this->createDocument('')); + $task->execute($state); + + self::assertSame("\n\n", file_get_contents($filePath)); + } + + public function testAppendModeKeepsPreviousContent(): void + { + $filePath = $this->tmpDir.'/file.xml'; + $task = new XmlWriterTask(new NullLogger()); + $state = $this->createState(['file_path' => $filePath, 'mode' => 'ab']); + $task->initialize($state); + + $state->setInput($this->createDocument('')); + $task->execute($state); + $state->setInput($this->createDocument('')); + $task->execute($state); + + self::assertSame( + "\n\n\n\n", + file_get_contents($filePath), + ); + } + + /** + * @return iterable + */ + public static function invalidInputProvider(): iterable + { + yield 'null' => [null]; + yield 'string' => ['']; + yield 'array' => [['root' => 'foo']]; + yield 'dom element' => [new \DOMElement('root')]; + } + + #[DataProvider('invalidInputProvider')] + public function testNonDomDocumentInputThrows(mixed $input): void + { + $filePath = $this->tmpDir.'/file.xml'; + $task = new XmlWriterTask(new NullLogger()); + $state = $this->createState(['file_path' => $filePath]); + $state->setInput($input); + $task->initialize($state); + + try { + $task->execute($state); + self::fail('An exception should have been thrown'); + } catch (\UnexpectedValueException $e) { + self::assertSame('Input must be a \DOMDocument', $e->getMessage()); + } + self::assertFileDoesNotExist($filePath); + } + + public function testFilePathIsRequired(): void + { + $task = new XmlWriterTask(new NullLogger()); + + $this->expectException(MissingOptionsException::class); + + $task->initialize($this->createState([])); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'file_path not a string' => [['file_path' => 42]]; + yield 'mode not a string' => [['file_path' => '/tmp/file.xml', 'mode' => 1]]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrow(array $options): void + { + $task = new XmlWriterTask(new NullLogger()); + + $this->expectException(InvalidOptionsException::class); + + $task->initialize($this->createState($options)); + } + + private function createDocument(string $xml): \DOMDocument + { + $dom = new \DOMDocument(); + $dom->loadXML($xml); + + return $dom; + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('write', XmlWriterTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/File/Yaml/YamlReaderTaskTest.php b/tests/Task/File/Yaml/YamlReaderTaskTest.php new file mode 100644 index 00000000..52a509e1 --- /dev/null +++ b/tests/Task/File/Yaml/YamlReaderTaskTest.php @@ -0,0 +1,220 @@ +tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('yaml_reader_test_', true); + (new Filesystem())->mkdir($this->tmpDir); + } + + protected function tearDown(): void + { + (new Filesystem())->remove($this->tmpDir); + } + + public function testIteratesOverRootMappingValues(): void + { + $filePath = $this->dump("foo:\n name: Foo\n tags: [a, b]\nbar:\n name: Bar\n"); + $task = new YamlReaderTask(); + $state = $this->createState(['file_path' => $filePath]); + $task->initialize($state); + + [$outputs, $keys] = $this->iterate($task, $state); + + self::assertSame([['name' => 'Foo', 'tags' => ['a', 'b']], ['name' => 'Bar']], $outputs); + self::assertSame(['foo', 'bar'], $keys); + self::assertSame([], $state->getErrorContext()); + } + + public function testIteratesOverRootSequence(): void + { + $filePath = $this->dump("- 1\n- two\n- { three: 3 }\n"); + $task = new YamlReaderTask(); + $state = $this->createState(['file_path' => $filePath]); + $task->initialize($state); + + [$outputs, $keys] = $this->iterate($task, $state); + + self::assertSame([1, 'two', ['three' => 3]], $outputs); + self::assertSame([0, 1, 2], $keys); + } + + public function testInputIsIgnoredAndFileIsReadAgainOnNextExecution(): void + { + $filePath = $this->dump("- a\n- b\n"); + $task = new YamlReaderTask(); + $state = $this->createState(['file_path' => $filePath]); + $task->initialize($state); + + self::assertSame([['a', 'b'], [0, 1]], $this->iterate($task, $state, 'ignored')); + self::assertSame([['a', 'b'], [0, 1]], $this->iterate($task, $state, ['ignored'])); + } + + /** + * @return iterable + */ + public static function emptyRootProvider(): iterable + { + yield 'empty mapping' => ['{}']; + yield 'empty sequence' => ['[]']; + } + + #[DataProvider('emptyRootProvider')] + public function testEmptyRootIsSkipped(string $content): void + { + $task = new YamlReaderTask(); + $state = $this->createState(['file_path' => $this->dump($content)]); + $task->initialize($state); + + $task->execute($state); + + self::assertTrue($state->isSkipped()); + self::assertFalse($task->next($state)); + self::assertSame([], $state->getErrorContext()); + } + + /** + * @return iterable + */ + public static function notArrayRootProvider(): iterable + { + yield 'empty file' => ['']; + yield 'scalar string' => ['foo']; + yield 'scalar int' => ['42']; + yield 'null' => ['~']; + } + + #[DataProvider('notArrayRootProvider')] + public function testNotArrayRootThrows(string $content): void + { + $filePath = $this->dump($content); + $task = new YamlReaderTask(); + $state = $this->createState(['file_path' => $filePath]); + $task->initialize($state); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage("File content is not an array: {$filePath}"); + + $task->execute($state); + } + + public function testInvalidYamlThrows(): void + { + $task = new YamlReaderTask(); + $state = $this->createState(['file_path' => $this->dump("foo: [a, b\n")]); + $task->initialize($state); + + $this->expectException(ParseException::class); + + $task->execute($state); + } + + public function testMissingFileThrowsAtInitialization(): void + { + $filePath = $this->tmpDir.'/missing.yaml'; + $task = new YamlReaderTask(); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("File not found: {$filePath}"); + + $task->initialize($this->createState(['file_path' => $filePath])); + } + + public function testFilePathIsRequired(): void + { + $task = new YamlReaderTask(); + + $this->expectException(MissingOptionsException::class); + + $task->initialize($this->createState([])); + } + + public function testFilePathMustBeAString(): void + { + $task = new YamlReaderTask(); + + $this->expectException(InvalidOptionsException::class); + + $task->initialize($this->createState(['file_path' => ['foo.yaml']])); + } + + private function dump(string $content): string + { + $filePath = $this->tmpDir.\DIRECTORY_SEPARATOR.uniqid('file_', true).'.yaml'; + file_put_contents($filePath, $content); + + return $filePath; + } + + /** + * Mimics the ProcessManager loop over an iterable task and returns the non-skipped outputs and their keys. + * + * @return array{list, list} + */ + private function iterate(YamlReaderTask $task, ProcessState $state, mixed $input = null): array + { + $outputs = []; + $keys = []; + $state->setInput($input); + do { + $state->setSkipped(false); + $task->execute($state); + if (!$state->isSkipped()) { + $outputs[] = $state->getOutput(); + $keys[] = $state->getErrorContext()['iterator_key'] ?? null; + } + } while ($task->next($state)); + + return [$outputs, $keys]; + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('read', YamlReaderTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/File/Yaml/YamlWriterTaskTest.php b/tests/Task/File/Yaml/YamlWriterTaskTest.php new file mode 100644 index 00000000..3f2ea99c --- /dev/null +++ b/tests/Task/File/Yaml/YamlWriterTaskTest.php @@ -0,0 +1,159 @@ + [ + 'name' => 'Foo', + 'tags' => ['a', 'b'], + ], + ]; + + private string $tmpDir; + + protected function setUp(): void + { + $this->tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('yaml_writer_test_', true); + (new Filesystem())->mkdir($this->tmpDir); + } + + protected function tearDown(): void + { + (new Filesystem())->remove($this->tmpDir); + } + + public function testWritesTheInputAndOutputsTheFilePath(): void + { + $filePath = $this->tmpDir.'/file.yaml'; + $state = $this->execute(['file_path' => $filePath], self::DATA); + + self::assertSame($filePath, $state->getOutput()); + self::assertSame("foo:\n name: Foo\n tags:\n - a\n - b\n", file_get_contents($filePath)); + self::assertSame(self::DATA, Yaml::parseFile($filePath)); + } + + /** + * @return iterable + */ + public static function inlineProvider(): iterable + { + yield 'inline at root' => [0, '{ foo: { name: Foo, tags: [a, b] } }']; + yield 'inline at first level' => [1, "foo: { name: Foo, tags: [a, b] }\n"]; + yield 'inline at second level' => [2, "foo:\n name: Foo\n tags: [a, b]\n"]; + } + + #[DataProvider('inlineProvider')] + public function testInlineOptionIsUsed(int $inline, string $expected): void + { + $filePath = $this->tmpDir.'/file.yaml'; + $this->execute(['file_path' => $filePath, 'inline' => $inline], self::DATA); + + self::assertSame($expected, file_get_contents($filePath)); + } + + public function testEachExecutionOverwritesTheFile(): void + { + $filePath = $this->tmpDir.'/file.yaml'; + $task = new YamlWriterTask(); + $state = $this->createState(['file_path' => $filePath]); + $task->initialize($state); + + $state->setInput(['first' => 1]); + $task->execute($state); + $state->setInput(['second' => 2]); + $task->execute($state); + + self::assertSame("second: 2\n", file_get_contents($filePath)); + } + + public function testScalarInputIsDumped(): void + { + $filePath = $this->tmpDir.'/file.yaml'; + $this->execute(['file_path' => $filePath], 'foo'); + + self::assertSame('foo', file_get_contents($filePath)); + } + + public function testFilePathIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + (new YamlWriterTask())->initialize($this->createState([])); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'file_path not a string' => [['file_path' => 42]]; + yield 'inline not an int' => [['file_path' => '/tmp/file.yaml', 'inline' => '2']]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrow(array $options): void + { + $this->expectException(InvalidOptionsException::class); + + (new YamlWriterTask())->initialize($this->createState($options)); + } + + private function execute(array $options, mixed $input): ProcessState + { + $task = new YamlWriterTask(); + $state = $this->createState($options); + $state->setInput($input); + $task->initialize($state); + $task->execute($state); + + return $state; + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('write', YamlWriterTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/FilterTaskTest.php b/tests/Task/FilterTaskTest.php new file mode 100644 index 00000000..63d20541 --- /dev/null +++ b/tests/Task/FilterTaskTest.php @@ -0,0 +1,175 @@ +> + */ + private function items(): array + { + return [ + ['key1' => 'value1', 'key2' => 'value2', 'key3' => ['something']], + ['key1' => 'value1b', 'key2' => 'value2b', 'key3' => ['something']], + ['key1' => 'value1c', 'key2' => 'value2c', 'key3' => []], + ]; + } + + /** + * @return iterable, list}> + */ + public static function filterProvider(): iterable + { + yield 'no condition' => [[], [0, 1, 2]]; + yield 'match' => [['match' => ['[key1]' => 'value1']], [0]]; + yield 'match several keys' => [['match' => ['[key1]' => 'value1b', '[key2]' => 'value2b']], [1]]; + yield 'match several keys, one failing' => [['match' => ['[key1]' => 'value1b', '[key2]' => 'value2']], []]; + yield 'not_match' => [['not_match' => ['[key1]' => 'value1']], [1, 2]]; + yield 'empty' => [['empty' => ['[key3]' => null]], [2]]; + yield 'not_empty' => [['not_empty' => ['[key3]' => null]], [0, 1]]; + yield 'match_regexp' => [['match_regexp' => ['[key1]' => '/^value1[bc]$/']], [1, 2]]; + yield 'not_match_regexp' => [['not_match_regexp' => ['[key1]' => '/^value1[bc]$/']], [0]]; + yield 'missing key is null on match' => [['match' => ['[missing]' => null]], [0, 1, 2]]; + yield 'missing key is empty' => [['empty' => ['[missing]' => null]], [0, 1, 2]]; + yield 'missing key is not not_empty' => [['not_empty' => ['[missing]' => null]], []]; + yield 'combined conditions' => [ + ['not_empty' => ['[key3]' => null], 'not_match' => ['[key1]' => 'value1']], + [1], + ]; + } + + /** + * @param list $expectedKept + */ + #[DataProvider('filterProvider')] + public function testInputsAreFiltered(array $options, array $expectedKept): void + { + $items = $this->items(); + $kept = []; + foreach ($items as $index => $item) { + $state = $this->execute($options, $item); + if ($state->isSkipped()) { + self::assertSame($item, $state->getErrorOutput()); + self::assertNull($state->getOutput()); + } else { + self::assertSame($item, $state->getOutput()); + self::assertFalse($state->hasErrorOutput()); + $kept[] = $index; + } + } + + self::assertSame($expectedKept, $kept); + } + + public function testMatchIsStrict(): void + { + self::assertTrue($this->execute(['match' => ['[id]' => 1]], ['id' => '1'])->isSkipped()); + self::assertFalse($this->execute(['match' => ['[id]' => 1]], ['id' => 1])->isSkipped()); + self::assertFalse($this->execute(['not_match' => ['[id]' => 1]], ['id' => '1'])->isSkipped()); + } + + public function testObjectPropertiesAreRead(): void + { + $input = (object) ['status' => 'active', 'sku' => 'ABC']; + + $state = $this->execute(['match' => ['status' => 'active'], 'not_empty' => ['sku' => null]], $input); + self::assertFalse($state->isSkipped()); + self::assertSame($input, $state->getOutput()); + + $state = $this->execute(['match' => ['status' => 'inactive']], $input); + self::assertTrue($state->isSkipped()); + self::assertSame($input, $state->getErrorOutput()); + } + + public function testUnreadableObjectPropertyIsNull(): void + { + $input = new \stdClass(); + + self::assertFalse($this->execute(['match' => ['missing' => null]], $input)->isSkipped()); + self::assertFalse($this->execute(['empty' => ['missing' => null]], $input)->isSkipped()); + } + + /** + * @return iterable, mixed, bool}> + */ + public static function scalarProvider(): iterable + { + yield 'empty path matches whole value' => [['match' => ['' => 'foo']], 'foo', false]; + yield 'empty path does not match whole value' => [['match' => ['' => 'bar']], 'foo', true]; + yield 'empty path regexp' => [['match_regexp' => ['' => '/^fo+$/']], 'foo', false]; + yield 'empty path empty' => [['empty' => ['' => null]], '', false]; + yield 'empty path not_empty' => [['not_empty' => ['' => null]], 0, true]; + yield 'other path on scalar is null' => [['match' => ['[key]' => null]], 'foo', false]; + yield 'other path on scalar is empty' => [['not_empty' => ['[key]' => null]], 'foo', true]; + } + + #[DataProvider('scalarProvider')] + public function testScalarInput(array $options, mixed $input, bool $expectedSkipped): void + { + self::assertSame($expectedSkipped, $this->execute($options, $input)->isSkipped()); + } + + public function testNonArrayConditionIsRejected(): void + { + $this->expectException(InvalidOptionsException::class); + $this->execute(['match' => 'foo'], []); + } + + public function testUnknownConditionIsRejected(): void + { + $this->expectException(UndefinedOptionsException::class); + $this->execute(['equals' => []], []); + } + + private function execute(array $options, mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('filter', FilterTask::class, $options)); + $state->setInput($input); + $state->reset(false); + + $task = new FilterTask(); + $task->initialize($state); + $task->execute($state); + + return $state; + } +} diff --git a/tests/Task/GroupByAggregateIterableTaskTest.php b/tests/Task/GroupByAggregateIterableTaskTest.php new file mode 100644 index 00000000..518d2292 --- /dev/null +++ b/tests/Task/GroupByAggregateIterableTaskTest.php @@ -0,0 +1,144 @@ +createTask(['[type]', '[code]']); + + $outputs = $this->aggregate($task, $state, [ + ['type' => 'A', 'code' => 1, 'v' => 'x'], + ['type' => 'B', 'code' => 1, 'v' => 'z'], + ['type' => 'A', 'code' => 1, 'v' => 'y'], + ]); + + self::assertNull($state->getException()); + self::assertSame([ + 'A-1' => ['type' => 'A', 'code' => 1, 'v' => 'y'], + 'B-1' => ['type' => 'B', 'code' => 1, 'v' => 'z'], + ], $outputs); + } + + public function testObjectInputsAreReadWithPropertyAccessor(): void + { + [$task, $state] = $this->createTask(['type']); + $first = (object) ['type' => 'A']; + $second = (object) ['type' => 'B']; + + $outputs = $this->aggregate($task, $state, [$first, $second]); + + self::assertSame(['A' => $first, 'B' => $second], $outputs); + } + + public function testEmptyAccessorsGroupEverythingUnderAnEmptyKey(): void + { + [$task, $state] = $this->createTask([]); + + $outputs = $this->aggregate($task, $state, [['v' => 1], ['v' => 2]]); + + self::assertSame(['' => ['v' => 2]], $outputs); + } + + public function testUnreadablePropertySetsExceptionWithErrorContext(): void + { + [$task, $state] = $this->createTask(['type', 'missing']); + $state->setInput((object) ['type' => 'A']); + + $task->execute($state); + + self::assertInstanceOf(NoSuchPropertyException::class, $state->getException()); + self::assertSame(['property' => 'missing'], $state->getErrorContext()); + + // The failed input is not aggregated + $task->proceed($state); + self::assertTrue($state->isSkipped()); + } + + public function testProceedWithoutInputIsSkipped(): void + { + [$task, $state] = $this->createTask(['[type]']); + + $task->proceed($state); + + self::assertTrue($state->isSkipped()); + self::assertNull($state->getOutput()); + } + + public function testGroupByOptionIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->createTask(null); + } + + public function testGroupByOptionMustBeAnArray(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->createTask('[type]'); + } + + /** + * @return array{GroupByAggregateIterableTask, ProcessState} + */ + private function createTask(mixed $groupBy): array + { + $options = null === $groupBy ? [] : [GroupByAggregateIterableTask::GROUP_BY_OPTION => $groupBy]; + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setSkipped(false); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('group', GroupByAggregateIterableTask::class, $options)); + + $task = new GroupByAggregateIterableTask(PropertyAccess::createPropertyAccessor()); + $task->initialize($state); + + return [$task, $state]; + } + + private function aggregate(GroupByAggregateIterableTask $task, ProcessState $state, array $inputs): mixed + { + foreach ($inputs as $input) { + $state->setInput($input); + $task->execute($state); + } + $task->proceed($state); + self::assertFalse($state->isSkipped()); + + return $state->getOutput(); + } +} diff --git a/tests/Task/InputAggregatorTaskTest.php b/tests/Task/InputAggregatorTaskTest.php new file mode 100644 index 00000000..4ef28066 --- /dev/null +++ b/tests/Task/InputAggregatorTaskTest.php @@ -0,0 +1,198 @@ + 'a', 'branch_b' => 'b']; + + public function testTaskIsSkippedUntilEveryInputIsReceived(): void + { + $task = new InputAggregatorTask(); + $options = ['input_codes' => self::INPUT_CODES]; + + $state = $this->receive($task, $options, 'branch_a', 'A'); + self::assertTrue($state->isSkipped()); + self::assertNull($state->getOutput()); + + $state = $this->receive($task, $options, 'branch_b', 'B'); + self::assertFalse($state->isSkipped()); + self::assertSame(['a' => 'A', 'b' => 'B'], $state->getOutput()); + } + + public function testBufferIsClearedAfterOutput(): void + { + $task = new InputAggregatorTask(); + $options = ['input_codes' => self::INPUT_CODES]; + + $this->receive($task, $options, 'branch_a', 'A1'); + $this->receive($task, $options, 'branch_b', 'B1'); + + $state = $this->receive($task, $options, 'branch_b', 'B2'); + self::assertTrue($state->isSkipped()); + + $state = $this->receive($task, $options, 'branch_a', 'A2'); + self::assertSame(['b' => 'B2', 'a' => 'A2'], $state->getOutput()); + } + + public function testOverriddenInputClearsBufferByDefault(): void + { + $task = new InputAggregatorTask(); + $options = ['input_codes' => ['branch_a' => 'a', 'branch_b' => 'b', 'branch_c' => 'c']]; + + $this->receive($task, $options, 'branch_a', 'A1'); + $this->receive($task, $options, 'branch_b', 'B1'); + // Receiving "a" again drops every buffered input, including "b" + $this->receive($task, $options, 'branch_a', 'A2'); + + $state = $this->receive($task, $options, 'branch_c', 'C1'); + self::assertTrue($state->isSkipped()); + + $state = $this->receive($task, $options, 'branch_b', 'B2'); + self::assertSame(['a' => 'A2', 'c' => 'C1', 'b' => 'B2'], $state->getOutput()); + } + + public function testOverriddenInputThrowsWhenCleaningIsDisabled(): void + { + $task = new InputAggregatorTask(); + $options = ['input_codes' => self::INPUT_CODES, 'clean_input_on_override' => false]; + + $this->receive($task, $options, 'branch_a', 'A1'); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("The output from input 'a' has already been defined"); + + $this->receive($task, $options, 'branch_a', 'A2'); + } + + public function testKeptInputsAreReusedForNextOutputs(): void + { + $task = new InputAggregatorTask(); + $options = ['input_codes' => self::INPUT_CODES, 'keep_inputs' => ['a']]; + + $this->receive($task, $options, 'branch_a', 'A'); + $state = $this->receive($task, $options, 'branch_b', 'B1'); + self::assertSame(['a' => 'A', 'b' => 'B1'], $state->getOutput()); + + $state = $this->receive($task, $options, 'branch_b', 'B2'); + self::assertFalse($state->isSkipped()); + self::assertSame(['a' => 'A', 'b' => 'B2'], $state->getOutput()); + } + + public function testSeveralParentsCanTargetTheSameKey(): void + { + $task = new InputAggregatorTask(); + $options = ['input_codes' => ['branch_a' => 'value', 'branch_b' => 'value']]; + + $state = $this->receive($task, $options, 'branch_b', 'B'); + + self::assertSame(['value' => 'B'], $state->getOutput()); + } + + public function testTaskWithoutPreviousStateThrows(): void + { + $task = new InputAggregatorTask(); + $state = $this->createState(['input_codes' => self::INPUT_CODES]); + $task->initialize($state); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('This task cannot be used without a previous task'); + + $task->execute($state); + } + + public function testUnmappedPreviousTaskThrows(): void + { + $task = new InputAggregatorTask(); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Task 'unknown' is not mapped in the input_codes option"); + + $this->receive($task, ['input_codes' => self::INPUT_CODES], 'unknown', 'X'); + } + + public function testInputCodesOptionIsRequired(): void + { + $task = new InputAggregatorTask(); + + $this->expectException(MissingOptionsException::class); + + $task->initialize($this->createState([])); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'input_codes not an array' => [['input_codes' => 'branch_a']]; + yield 'clean_input_on_override not a bool' => [['input_codes' => [], 'clean_input_on_override' => 'yes']]; + yield 'keep_inputs not an array' => [['input_codes' => [], 'keep_inputs' => 'a']]; + } + + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsAreRejected(array $options): void + { + $task = new InputAggregatorTask(); + + $this->expectException(InvalidOptionsException::class); + + $task->initialize($this->createState($options)); + } + + private function receive(InputAggregatorTask $task, array $options, string $previousTaskCode, mixed $input): ProcessState + { + $previousState = $this->createState([], $previousTaskCode); + $state = $this->createState($options); + $state->setPreviousState($previousState); + $state->setInput($input); + + $task->initialize($state); + $task->execute($state); + + return $state; + } + + private function createState(array $options, string $code = 'aggregate'): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setSkipped(false); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration($code, 'aggregate' === $code ? InputAggregatorTask::class : DummyTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/InputIteratorTaskTest.php b/tests/Task/InputIteratorTaskTest.php new file mode 100644 index 00000000..e6af3bf2 --- /dev/null +++ b/tests/Task/InputIteratorTaskTest.php @@ -0,0 +1,142 @@ + + */ + public static function iterableInputProvider(): iterable + { + yield 'list' => [[1, 2, 3]]; + yield 'associative array' => [['a' => 1, 'b' => 2, 'c' => 3]]; + yield 'iterator' => [new \ArrayIterator(['a' => 1, 'b' => 2, 'c' => 3])]; + yield 'iterator aggregate' => [new \ArrayObject([1, 2, 3])]; + } + + #[DataProvider('iterableInputProvider')] + public function testEachValueIsOutput(mixed $input): void + { + $task = new InputIteratorTask(); + $state = $this->createState(); + $task->initialize($state); + + self::assertSame([1, 2, 3], $this->iterate($task, $state, $input)); + } + + public function testGeneratorInputIsIterated(): void + { + $task = new InputIteratorTask(); + $state = $this->createState(); + $task->initialize($state); + + $generator = (static function (): \Generator { + yield 'x'; + yield 'y'; + })(); + + self::assertSame(['x', 'y'], $this->iterate($task, $state, $generator)); + } + + public function testIteratorResetsForEachNewInput(): void + { + $task = new InputIteratorTask(); + $state = $this->createState(); + $task->initialize($state); + + self::assertSame([1, 2], $this->iterate($task, $state, [1, 2])); + self::assertSame([3, 4], $this->iterate($task, $state, [3, 4])); + } + + public function testEmptyInputIsSkipped(): void + { + $task = new InputIteratorTask(); + $state = $this->createState(); + $task->initialize($state); + + self::assertSame([], $this->iterate($task, $state, new \ArrayIterator([]))); + self::assertFalse($task->next($state)); + } + + /** + * @return iterable + */ + public static function invalidInputProvider(): iterable + { + yield 'null' => [null]; + yield 'string' => ['foo']; + yield 'int' => [42]; + yield 'object' => [new \stdClass()]; + } + + #[DataProvider('invalidInputProvider')] + public function testNonIterableInputThrows(mixed $input): void + { + $task = new InputIteratorTask(); + $state = $this->createState(); + $task->initialize($state); + $state->setInput($input); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Cannot create iterator from input'); + + $task->execute($state); + } + + private function iterate(InputIteratorTask $task, ProcessState $state, mixed $input): array + { + $outputs = []; + $state->setInput($input); + do { + $state->setSkipped(false); + $task->execute($state); + if (!$state->isSkipped()) { + $outputs[] = $state->getOutput(); + } + } while ($task->next($state)); + + return $outputs; + } + + private function createState(): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('iterate', InputIteratorTask::class, [])); + + return $state; + } +} diff --git a/tests/Task/Process/ProcessExecutorTaskTest.php b/tests/Task/Process/ProcessExecutorTaskTest.php new file mode 100644 index 00000000..01c02c38 --- /dev/null +++ b/tests/Task/Process/ProcessExecutorTaskTest.php @@ -0,0 +1,196 @@ +createMock(ProcessManager::class); + $processManager->expects(self::once()) + ->method('execute') + ->with('child', ['id' => 1], []) + ->willReturn([1, 2, 3, 4]); + + $state = $this->execute($processManager, ['process' => 'child'], ['id' => 1]); + + self::assertSame([1, 2, 3, 4], $state->getOutput()); + self::assertFalse($state->isSkipped()); + } + + public function testEachInputExecutesTheSubProcess(): void + { + $processManager = $this->createMock(ProcessManager::class); + $processManager->expects(self::exactly(2)) + ->method('execute') + ->willReturnCallback(static fn (string $code, mixed $input): string => $code.':'.$input); + + $state = $this->createState(['process' => 'child'], 'a'); + $task = $this->createTask($processManager); + $task->initialize($state); + $outputs = []; + foreach (['a', 'b'] as $input) { + $state->setInput($input); + $task->execute($state); + $outputs[] = $state->getOutput(); + } + + self::assertSame(['child:a', 'child:b'], $outputs); + } + + public function testNullSubProcessOutputIsForwarded(): void + { + $processManager = $this->createMock(ProcessManager::class); + $processManager->expects(self::once())->method('execute')->willReturn(null); + + $state = $this->execute($processManager, ['process' => 'child'], 'foo'); + + self::assertNull($state->getOutput()); + } + + public function testContextOptionIsPassedToTheSubProcess(): void + { + $processManager = $this->createMock(ProcessManager::class); + $processManager->expects(self::once()) + ->method('execute') + ->with('child', 'foo', ['source' => 'import.csv', 'mode' => 'full']) + ->willReturn('done'); + + $state = $this->execute( + $processManager, + ['process' => 'child', 'context' => ['source' => '{{ source }}', 'mode' => 'full']], + 'foo', + ['source' => 'import.csv', 'other' => 'not forwarded'], + ); + + self::assertSame('done', $state->getOutput()); + } + + public function testProcessCodeIsContextualized(): void + { + $processManager = $this->createMock(ProcessManager::class); + $processManager->expects(self::once())->method('execute')->with('child', 'foo', [])->willReturn('done'); + + $state = $this->execute($processManager, ['process' => '{{ sub }}'], 'foo', ['sub' => 'child']); + + self::assertSame('done', $state->getOutput()); + } + + public function testSubProcessExceptionIsPropagated(): void + { + $processManager = $this->createMock(ProcessManager::class); + $processManager->expects(self::once())->method('execute')->willThrowException(new \RuntimeException('Sub-process failed')); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Sub-process failed'); + $this->execute($processManager, ['process' => 'child'], 'foo'); + } + + public function testUnknownProcessThrowsAtInitialization(): void + { + $processManager = $this->createMock(ProcessManager::class); + $processManager->expects(self::never())->method('execute'); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('Unknown process unknown'); + $this->createTask($processManager)->initialize($this->createState(['process' => 'unknown'], 'foo')); + } + + /** + * @return iterable, class-string<\Throwable>}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'missing process' => [[], MissingOptionsException::class]; + yield 'process not a string' => [['process' => 42], InvalidOptionsException::class]; + yield 'context not an array' => [['process' => 'child', 'context' => 'foo'], InvalidOptionsException::class]; + yield 'unknown option' => [['process' => 'child', 'unknown' => true], UndefinedOptionsException::class]; + } + + /** + * @param array $options + * @param class-string<\Throwable> $exception + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrowAtInitialization(array $options, string $exception): void + { + $this->expectException($exception); + $this->createTask($this->createStub(ProcessManager::class))->initialize($this->createState($options, 'foo')); + } + + /** + * @param array $options + * @param array $context + */ + private function execute(ProcessManager $processManager, array $options, mixed $input, array $context = []): ProcessState + { + $state = $this->createState($options, $input, $context); + $task = $this->createTask($processManager); + $task->initialize($state); + $task->execute($state); + + return $state; + } + + private function createTask(ProcessManager $processManager): ProcessExecutorTask + { + return new ProcessExecutorTask( + $processManager, + new ProcessConfigurationRegistry(['child' => []], 'stop'), + new NullLogger(), + ); + } + + /** + * @param array $options + * @param array $context + */ + private function createState(array $options, mixed $input, array $context = []): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext($context); + $state->setTaskConfiguration(new TaskConfiguration('executor', ProcessExecutorTask::class, $options)); + $state->reset(false); + $state->setInput($input); + + return $state; + } +} diff --git a/tests/Task/PropertyGetterTaskTest.php b/tests/Task/PropertyGetterTaskTest.php new file mode 100644 index 00000000..c8acb459 --- /dev/null +++ b/tests/Task/PropertyGetterTaskTest.php @@ -0,0 +1,126 @@ + + */ + public static function readableProvider(): iterable + { + yield 'array index' => ['[sku]', ['sku' => 'ABC', 'name' => 'Foo'], 'ABC']; + yield 'nested array index' => ['[product][sku]', ['product' => ['sku' => 'ABC']], 'ABC']; + yield 'array value' => ['[tags]', ['tags' => ['a', 'b']], ['a', 'b']]; + yield 'missing array index' => ['[missing]', ['sku' => 'ABC'], null]; + yield 'object property' => ['path', (object) ['path' => '/tmp/foo.csv'], '/tmp/foo.csv']; + yield 'object then array' => ['data[sku]', (object) ['data' => ['sku' => 'ABC']], 'ABC']; + } + + #[DataProvider('readableProvider')] + public function testValueIsReadAtPropertyPath(string $property, mixed $input, mixed $expected): void + { + $state = $this->execute($property, $input); + + self::assertNull($state->getException()); + self::assertSame([], $state->getErrorContext()); + self::assertSame($expected, $state->getOutput()); + } + + public function testValueIsReadThroughGetter(): void + { + $input = new class { + public function getName(): string + { + return 'Foo'; + } + }; + + $state = $this->execute('name', $input); + + self::assertNull($state->getException()); + self::assertSame('Foo', $state->getOutput()); + } + + public function testMissingObjectPropertySetsExceptionWithErrorContext(): void + { + $state = $this->execute('missing', new \stdClass()); + + self::assertInstanceOf(NoSuchPropertyException::class, $state->getException()); + self::assertSame(['property' => 'missing'], $state->getErrorContext()); + self::assertNull($state->getOutput()); + } + + public function testPropertyPathOnArraySetsExceptionWithErrorContext(): void + { + // A property path (not an index) cannot be read on an array + $state = $this->execute('sku', ['sku' => 'ABC']); + + self::assertInstanceOf(NoSuchPropertyException::class, $state->getException()); + self::assertSame(['property' => 'sku'], $state->getErrorContext()); + self::assertNull($state->getOutput()); + } + + public function testMissingPropertyOptionIsRejected(): void + { + $this->expectException(MissingOptionsException::class); + $this->execute(null, []); + } + + public function testNonStringPropertyOptionIsRejected(): void + { + $this->expectException(InvalidOptionsException::class); + $this->execute(['sku'], []); + } + + private function execute(mixed $property, mixed $input): ProcessState + { + $options = null === $property ? [] : ['property' => $property]; + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('get', PropertyGetterTask::class, $options)); + $state->setInput($input); + $state->reset(false); + + $task = new PropertyGetterTask(new NullLogger(), PropertyAccess::createPropertyAccessor()); + $task->initialize($state); + $task->execute($state); + + return $state; + } +} diff --git a/tests/Task/Reporting/LoggerTaskTest.php b/tests/Task/Reporting/LoggerTaskTest.php new file mode 100644 index 00000000..d13bd61a --- /dev/null +++ b/tests/Task/Reporting/LoggerTaskTest.php @@ -0,0 +1,196 @@ +}> */ + private array $records = []; + + public function testDefaultOptionsLogTheInputAtDebugLevel(): void + { + $state = $this->execute([], ['id' => 123]); + + self::assertSame( + [['level' => LogLevel::DEBUG, 'message' => 'Log state input', 'context' => ['input' => ['id' => 123]]]], + $this->records + ); + self::assertSame(['id' => 123], $state->getOutput()); + } + + /** + * @return iterable + */ + public static function inputProvider(): iterable + { + yield 'string' => ['foo']; + yield 'array' => [['foo' => 'bar']]; + yield 'object' => [new \ArrayObject(['foo' => 'bar'])]; + yield 'null' => [null]; + } + + #[DataProvider('inputProvider')] + public function testInputIsForwardedUnchanged(mixed $input): void + { + $state = $this->execute([], $input); + + self::assertSame($input, $state->getOutput()); + self::assertFalse($state->isSkipped()); + } + + public function testLevelAndMessageAreUsed(): void + { + $this->execute(['level' => LogLevel::WARNING, 'message' => 'DEMO LOGGER'], 'foo'); + + self::assertCount(1, $this->records); + self::assertSame(LogLevel::WARNING, $this->records[0]['level']); + self::assertSame('DEMO LOGGER', $this->records[0]['message']); + } + + public function testContextPathsAreReadOnTheState(): void + { + $this->execute(['context' => ['input', 'context']], 'foo', ['file' => 'import.csv']); + + self::assertSame(['input' => 'foo', 'context' => ['file' => 'import.csv']], $this->records[0]['context']); + } + + public function testEmptyContextLogsNoValue(): void + { + $this->execute(['context' => []], 'foo'); + + self::assertSame([], $this->records[0]['context']); + } + + public function testReferenceIsAddedToTheLogContext(): void + { + $this->execute(['reference' => 'ref-1'], 'foo'); + + self::assertSame(['input' => 'foo', 'reference' => 'ref-1'], $this->records[0]['context']); + } + + public function testReferenceIsContextualized(): void + { + $this->execute(['context' => [], 'reference' => '{{ file }}'], 'foo', ['file' => 'import.csv']); + + self::assertSame(['reference' => 'import.csv'], $this->records[0]['context']); + } + + public function testEmptyReferenceIsNotAddedToTheLogContext(): void + { + $this->execute(['reference' => ''], 'foo'); + + self::assertSame(['input' => 'foo'], $this->records[0]['context']); + } + + public function testUnreadableContextPathThrows(): void + { + $this->expectException(NoSuchPropertyException::class); + $this->execute(['context' => ['unknownProperty']], 'foo'); + } + + /** + * @return iterable, class-string<\Throwable>}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'level not a string' => [['level' => 100], InvalidOptionsException::class]; + yield 'message not a string' => [['message' => ['foo']], InvalidOptionsException::class]; + yield 'context not an array' => [['context' => 'input'], InvalidOptionsException::class]; + yield 'reference not a string' => [['reference' => 42], InvalidOptionsException::class]; + yield 'unknown option' => [['unknown' => true], UndefinedOptionsException::class]; + } + + /** + * @param array $options + * @param class-string<\Throwable> $exception + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrowAtInitialization(array $options, string $exception): void + { + $this->expectException($exception); + $this->createTask()->initialize($this->createState($options, 'foo')); + } + + /** + * @param array $options + * @param array $context + */ + private function execute(array $options, mixed $input, array $context = []): ProcessState + { + $state = $this->createState($options, $input, $context); + $task = $this->createTask(); + $task->initialize($state); + $task->execute($state); + + return $state; + } + + private function createTask(): LoggerTask + { + $logger = new class(function (array $record): void { + $this->records[] = $record; + }) extends AbstractLogger { + public function __construct(private readonly \Closure $onLog) + { + } + + public function log($level, string|\Stringable $message, array $context = []): void + { + ($this->onLog)(['level' => $level, 'message' => (string) $message, 'context' => $context]); + } + }; + + return new LoggerTask($logger, PropertyAccess::createPropertyAccessor()); + } + + /** + * @param array $options + * @param array $context + */ + private function createState(array $options, mixed $input, array $context = []): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext($context); + $state->setTaskConfiguration(new TaskConfiguration('log', LoggerTask::class, $options)); + $state->reset(false); + $state->setInput($input); + + return $state; + } +} diff --git a/tests/Task/RowAggregatorTaskTest.php b/tests/Task/RowAggregatorTaskTest.php new file mode 100644 index 00000000..cefdd93b --- /dev/null +++ b/tests/Task/RowAggregatorTaskTest.php @@ -0,0 +1,143 @@ + 'order_id', + 'aggregate_columns' => ['product', 'qty'], + 'aggregation_key' => 'lines', + ]; + + public function testRowsAreGroupedByColumn(): void + { + $state = $this->createState(self::OPTIONS); + $task = new RowAggregatorTask(new NullLogger()); + $task->initialize($state); + + foreach ([ + ['order_id' => 1, 'customer' => 'X', 'product' => 'A', 'qty' => 2], + ['order_id' => 2, 'customer' => 'Y', 'product' => 'C', 'qty' => 1], + ['order_id' => 1, 'customer' => 'Z', 'product' => 'B', 'qty' => 3], + ] as $input) { + $state->setInput($input); + $task->execute($state); + } + $task->proceed($state); + + self::assertSame([ + // The non-aggregated columns come from the first row of the group + ['order_id' => 1, 'customer' => 'X', 'lines' => [['product' => 'A', 'qty' => 2], ['product' => 'B', 'qty' => 3]]], + ['order_id' => 2, 'customer' => 'Y', 'lines' => [['product' => 'C', 'qty' => 1]]], + ], $state->getOutput()); + } + + public function testProceedWithoutInputOutputsAnEmptyList(): void + { + $state = $this->createState(self::OPTIONS); + $task = new RowAggregatorTask(new NullLogger()); + $task->initialize($state); + + $task->proceed($state); + + self::assertSame([], $state->getOutput()); + } + + public function testMissingAggregateByColumnThrows(): void + { + $state = $this->createState(self::OPTIONS); + $task = new RowAggregatorTask(new NullLogger()); + $task->initialize($state); + $state->setInput(['customer' => 'X', 'product' => 'A', 'qty' => 2]); + + $this->expectException(InvalidProcessConfigurationException::class); + $this->expectExceptionMessage("Array aggregator exception: missing column 'order_id'"); + + $task->execute($state); + } + + public function testMissingAggregateColumnThrows(): void + { + $state = $this->createState(self::OPTIONS); + $task = new RowAggregatorTask(new NullLogger()); + $task->initialize($state); + $state->setInput(['order_id' => 1, 'product' => 'A']); + + $this->expectException(InvalidProcessConfigurationException::class); + $this->expectExceptionMessage('Array aggregator exception: missing column qty'); + + $task->execute($state); + } + + /** + * @return iterable, class-string<\Throwable>}> + */ + public static function invalidOptionsProvider(): iterable + { + foreach (array_keys(self::OPTIONS) as $option) { + $options = self::OPTIONS; + unset($options[$option]); + yield "missing {$option}" => [$options, MissingOptionsException::class]; + } + yield 'aggregate_by not a string' => [['aggregate_by' => ['order_id']] + self::OPTIONS, InvalidOptionsException::class]; + yield 'aggregate_columns not an array' => [['aggregate_columns' => 'product'] + self::OPTIONS, InvalidOptionsException::class]; + yield 'aggregation_key not a string' => [['aggregation_key' => 1] + self::OPTIONS, InvalidOptionsException::class]; + } + + /** + * @param class-string<\Throwable> $exception + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsAreRejected(array $options, string $exception): void + { + $task = new RowAggregatorTask(new NullLogger()); + + $this->expectException($exception); + + $task->initialize($this->createState($options)); + } + + private function createState(array $options): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('aggregate', RowAggregatorTask::class, $options)); + + return $state; + } +} diff --git a/tests/Task/Serialization/DenormalizerTaskTest.php b/tests/Task/Serialization/DenormalizerTaskTest.php new file mode 100644 index 00000000..0368754c --- /dev/null +++ b/tests/Task/Serialization/DenormalizerTaskTest.php @@ -0,0 +1,179 @@ +execute(['class' => DenormalizerTaskTestDto::class], ['name' => 'Foo', 'price' => 12]); + + $output = $state->getOutput(); + self::assertInstanceOf(DenormalizerTaskTestDto::class, $output); + self::assertSame('Foo', $output->name); + self::assertSame(12, $output->price); + } + + public function testListOfObjectsIsDenormalized(): void + { + $state = $this->execute( + ['class' => DenormalizerTaskTestDto::class.'[]'], + [['name' => 'Foo', 'price' => 1], ['name' => 'Bar', 'price' => 2]], + ); + + $output = $state->getOutput(); + self::assertIsArray($output); + self::assertCount(2, $output); + self::assertContainsOnlyInstancesOf(DenormalizerTaskTestDto::class, $output); + self::assertSame('Bar', $output[1]->name); + } + + public function testOptionsArePassedToTheDenormalizer(): void + { + $denormalizer = $this->createMock(DenormalizerInterface::class); + $denormalizer->expects(self::once()) + ->method('denormalize') + ->with(['foo' => 'bar'], 'App\Foo', 'json', ['groups' => ['import']]) + ->willReturn('denormalized'); + + $state = $this->execute( + ['class' => 'App\Foo', 'format' => 'json', 'context' => ['groups' => ['import']]], + ['foo' => 'bar'], + $denormalizer, + ); + + self::assertSame('denormalized', $state->getOutput()); + } + + public function testDefaultFormatAndContextArePassedToTheDenormalizer(): void + { + $denormalizer = $this->createMock(DenormalizerInterface::class); + $denormalizer->expects(self::once()) + ->method('denormalize') + ->with('input', 'App\Foo', null, []) + ->willReturn('denormalized'); + + $state = $this->execute(['class' => 'App\Foo'], 'input', $denormalizer); + + self::assertSame('denormalized', $state->getOutput()); + } + + public function testContextIsUsedByTheDenormalizer(): void + { + $existing = new DenormalizerTaskTestDto(); + $existing->price = 99; + + $state = $this->execute( + ['class' => DenormalizerTaskTestDto::class, 'context' => [AbstractNormalizer::OBJECT_TO_POPULATE => $existing]], + ['name' => 'Foo'], + ); + + self::assertSame($existing, $state->getOutput()); + self::assertSame('Foo', $existing->name); + self::assertSame(99, $existing->price); + } + + public function testDenormalizationFailureIsPropagated(): void + { + $this->expectException(NotNormalizableValueException::class); + $this->execute(['class' => DenormalizerTaskTestDto::class], ['name' => 'Foo', 'price' => 'not an int']); + } + + /** + * @return iterable, class-string<\Throwable>}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'missing class' => [[], MissingOptionsException::class]; + yield 'class not a string' => [['class' => 42], InvalidOptionsException::class]; + yield 'format not a string' => [['class' => 'App\Foo', 'format' => 42], InvalidOptionsException::class]; + yield 'context not an array' => [['class' => 'App\Foo', 'context' => 'foo'], InvalidOptionsException::class]; + yield 'unknown option' => [['class' => 'App\Foo', 'unknown' => true], UndefinedOptionsException::class]; + } + + /** + * @param array $options + * @param class-string<\Throwable> $exception + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrowAtInitialization(array $options, string $exception): void + { + $task = new DenormalizerTask($this->createStub(DenormalizerInterface::class)); + + $this->expectException($exception); + $task->initialize($this->createState($options, null)); + } + + /** + * @param array $options + */ + private function execute(array $options, mixed $input, ?DenormalizerInterface $denormalizer = null): ProcessState + { + $state = $this->createState($options, $input); + $task = new DenormalizerTask($denormalizer ?? new Serializer([new ArrayDenormalizer(), new ObjectNormalizer()])); + $task->initialize($state); + $task->execute($state); + + return $state; + } + + /** + * @param array $options + */ + private function createState(array $options, mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('denormalize', DenormalizerTask::class, $options)); + $state->reset(false); + $state->setInput($input); + + return $state; + } +} + +final class DenormalizerTaskTestDto +{ + public ?string $name = null; + + public ?int $price = null; +} diff --git a/tests/Task/SkipEmptyTaskTest.php b/tests/Task/SkipEmptyTaskTest.php new file mode 100644 index 00000000..f03267df --- /dev/null +++ b/tests/Task/SkipEmptyTaskTest.php @@ -0,0 +1,85 @@ + + */ + public static function emptyInputProvider(): iterable + { + yield 'null' => [null]; + yield 'false' => [false]; + yield 'int zero' => [0]; + yield 'float zero' => [0.0]; + yield 'string zero' => ['0']; + yield 'empty string' => ['']; + yield 'empty array' => [[]]; + } + + #[DataProvider('emptyInputProvider')] + public function testEmptyInputIsSkipped(mixed $input): void + { + $state = $this->execute($input); + + self::assertTrue($state->isSkipped()); + } + + /** + * @return iterable + */ + public static function nonEmptyInputProvider(): iterable + { + yield 'true' => [true]; + yield 'int' => [1]; + yield 'string' => ['foo']; + yield 'blank string' => [' ']; + yield 'array' => [['foo']]; + yield 'array of empty value' => [[null]]; + yield 'empty object' => [new \stdClass()]; + } + + #[DataProvider('nonEmptyInputProvider')] + public function testNonEmptyInputIsPassedToOutput(mixed $input): void + { + $state = $this->execute($input); + + self::assertFalse($state->isSkipped()); + self::assertSame($input, $state->getOutput()); + } + + private function execute(mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setInput($input); + $state->reset(false); + + (new SkipEmptyTask())->execute($state); + + return $state; + } +} diff --git a/tests/Task/SplitJoinLineTaskTest.php b/tests/Task/SplitJoinLineTaskTest.php new file mode 100644 index 00000000..3fd958db --- /dev/null +++ b/tests/Task/SplitJoinLineTaskTest.php @@ -0,0 +1,169 @@ +createTask(['split_columns' => ['category', 'tag'], 'join_column' => 'value']); + + $outputs = $this->iterate($task, $state, ['category' => 'A,B,C', 'tag' => 'x,y', 'name' => 'Item1']); + + self::assertSame([ + ['name' => 'Item1', 'value' => 'A'], + ['name' => 'Item1', 'value' => 'B'], + ['name' => 'Item1', 'value' => 'C'], + ['name' => 'Item1', 'value' => 'x'], + ['name' => 'Item1', 'value' => 'y'], + ], $outputs); + } + + public function testCustomSplitCharacter(): void + { + [$task, $state] = $this->createTask(['split_columns' => ['assets'], 'join_column' => 'asset', 'split_character' => '|']); + + $outputs = $this->iterate($task, $state, ['product' => 'toto', 'assets' => 'a|b,c']); + + self::assertSame([ + ['product' => 'toto', 'asset' => 'a'], + ['product' => 'toto', 'asset' => 'b,c'], + ], $outputs); + } + + public function testJoinColumnCanOverrideAnExistingColumn(): void + { + [$task, $state] = $this->createTask(['split_columns' => ['codes'], 'join_column' => 'name']); + + $outputs = $this->iterate($task, $state, ['name' => 'Item1', 'codes' => '1,2']); + + self::assertSame([['name' => '1'], ['name' => '2']], $outputs); + } + + public function testNonStringValuesAreCastToString(): void + { + [$task, $state] = $this->createTask(['split_columns' => ['id', 'empty'], 'join_column' => 'value']); + + $outputs = $this->iterate($task, $state, ['id' => 42, 'empty' => null]); + + self::assertSame([['value' => '42'], ['value' => '']], $outputs); + } + + public function testIterationRestartsForEachNewInput(): void + { + [$task, $state] = $this->createTask(['split_columns' => ['assets'], 'join_column' => 'asset']); + + self::assertSame( + [['product' => 'toto', 'asset' => 'a'], ['product' => 'toto', 'asset' => 'b']], + $this->iterate($task, $state, ['product' => 'toto', 'assets' => 'a,b']) + ); + self::assertSame( + [['product' => 'tata', 'asset' => 'e'], ['product' => 'tata', 'asset' => 'f']], + $this->iterate($task, $state, ['product' => 'tata', 'assets' => 'e,f']) + ); + } + + public function testEmptySplitColumnsIsSkipped(): void + { + [$task, $state] = $this->createTask(['split_columns' => [], 'join_column' => 'value']); + + self::assertSame([], $this->iterate($task, $state, ['name' => 'Item1'])); + } + + public function testMissingSplitColumnThrows(): void + { + [$task, $state] = $this->createTask(['split_columns' => ['category', 'tag'], 'join_column' => 'value']); + $state->setInput(['category' => 'A']); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Missing column tag'); + + $task->execute($state); + } + + /** + * @return iterable, class-string<\Throwable>}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'missing split_columns' => [['join_column' => 'value'], MissingOptionsException::class]; + yield 'missing join_column' => [['split_columns' => ['a']], MissingOptionsException::class]; + yield 'split_columns not an array' => [['split_columns' => 'a', 'join_column' => 'value'], InvalidOptionsException::class]; + yield 'join_column not a string' => [['split_columns' => ['a'], 'join_column' => 1], InvalidOptionsException::class]; + } + + /** + * @param class-string<\Throwable> $exception + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsAreRejected(array $options, string $exception): void + { + $this->expectException($exception); + + $this->createTask($options); + } + + /** + * @return array{SplitJoinLineTask, ProcessState} + */ + private function createTask(array $options): array + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('split', SplitJoinLineTask::class, $options)); + + $task = new SplitJoinLineTask(); + $task->initialize($state); + + return [$task, $state]; + } + + private function iterate(SplitJoinLineTask $task, ProcessState $state, mixed $input): array + { + $outputs = []; + $state->setInput($input); + do { + $state->setSkipped(false); + $task->execute($state); + if (!$state->isSkipped()) { + $outputs[] = $state->getOutput(); + } + } while ($task->next($state)); + + return $outputs; + } +} diff --git a/tests/Task/StopTaskTest.php b/tests/Task/StopTaskTest.php new file mode 100644 index 00000000..a1f436c2 --- /dev/null +++ b/tests/Task/StopTaskTest.php @@ -0,0 +1,46 @@ +setInput(['ignored']); + $state->reset(false); + self::assertFalse($state->isStopped()); + self::assertFalse($state->getProcessHistory()->isFailed()); + + (new StopTask())->execute($state); + + self::assertTrue($state->isStopped()); + self::assertTrue($state->getProcessHistory()->isFailed()); + self::assertSame(ProcessHistory::STATE_FAILED, $state->getProcessHistory()->getState()); + self::assertNotNull($state->getProcessHistory()->getEndDate()); + self::assertNull($state->getOutput()); + self::assertNull($state->getException()); + } +} diff --git a/tests/Task/TransformerTaskTest.php b/tests/Task/TransformerTaskTest.php new file mode 100644 index 00000000..ac70be48 --- /dev/null +++ b/tests/Task/TransformerTaskTest.php @@ -0,0 +1,217 @@ + 'bar']; + + self::assertSame($input, $this->execute([], $input)->getOutput()); + self::assertSame($input, $this->execute(['transformers' => []], $input)->getOutput()); + } + + public function testSingleTransformer(): void + { + $state = $this->execute([ + 'transformers' => [ + 'callback' => ['callback' => 'json_decode', 'right_parameters' => [true]], + ], + ], '{"foo":"bar"}'); + + self::assertNull($state->getException()); + self::assertSame(['foo' => 'bar'], $state->getOutput()); + } + + public function testSimpleMapping(): void + { + $state = $this->execute([ + 'transformers' => [ + 'mapping' => ['mapping' => ['field' => ['code' => '.']]], + ], + ], 'value'); + + self::assertSame(['field' => 'value'], $state->getOutput()); + } + + public function testMappingWithSubTransformers(): void + { + $state = $this->execute([ + 'transformers' => [ + 'mapping' => [ + 'mapping' => [ + 'name' => ['code' => '[firstname]', 'transformers' => ['trim' => null]], + ], + ], + ], + ], ['firstname' => ' John ']); + + self::assertSame(['name' => 'John'], $state->getOutput()); + } + + public function testSameTransformerCanBeChainedWithSuffixes(): void + { + $state = $this->execute([ + 'transformers' => [ + 'callback#1' => ['callback' => 'array_filter'], + 'callback#reverse' => ['callback' => 'array_reverse'], + ], + ], [3, null, 4, 2]); + + self::assertSame([2, 4, 3], $state->getOutput()); + } + + public function testNonConfigurableTransformerAcceptsNullOptions(): void + { + $state = $this->execute(['transformers' => ['array_last' => null]], [1, 2, 3]); + + self::assertSame(3, $state->getOutput()); + } + + public function testTransformerFailureSetsExceptionWithErrorContext(): void + { + $state = $this->execute([ + 'transformers' => [ + 'callback#1' => ['callback' => 'intval'], + 'callback#2' => ['callback' => 'intdiv', 'right_parameters' => [0]], + ], + ], ' 1 '); + + $exception = $state->getException(); + self::assertInstanceOf(TransformerException::class, $exception); + self::assertInstanceOf(\DivisionByZeroError::class, $exception->getPrevious()); + self::assertSame("Transformation 'callback#2' have failed: Division by zero", $exception->getMessage()); + self::assertSame(['error' => 'Division by zero'], $state->getErrorContext()); + self::assertNull($state->getOutput()); + } + + public function testMissingMappedPropertyFails(): void + { + $state = $this->execute([ + 'transformers' => [ + 'mapping' => ['mapping' => ['field' => ['code' => 'missing']]], + ], + ], (object) ['other' => 'value']); + + self::assertInstanceOf(TransformerException::class, $state->getException()); + self::assertInstanceOf(NoSuchPropertyException::class, $state->getException()->getPrevious()); + self::assertNull($state->getOutput()); + } + + public function testUnknownTransformerIsRejectedAtInitialization(): void + { + $this->expectException(MissingTransformerException::class); + $this->expectExceptionMessage('No transformer with code : unknown'); + + $this->execute(['transformers' => ['unknown' => null]], 'value'); + } + + public function testSuffixOfUnknownTransformerIsNotStripped(): void + { + $this->expectException(MissingTransformerException::class); + $this->expectExceptionMessage('No transformer with code : unknown#1'); + + $this->execute(['transformers' => ['unknown#1' => null]], 'value'); + } + + public function testNonConfigurableTransformerCannotHaveOptions(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Transformer array_last should not have options'); + + $this->execute(['transformers' => ['array_last' => ['foo' => 'bar']]], [1]); + } + + public function testScalarTransformerOptionsAreRejected(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Options for transformer trim#1 are invalid : found string, expected array or null'); + + $this->execute(['transformers' => ['trim#1' => 'x']], 'value'); + } + + public function testInvalidTransformerOptionsAreRejected(): void + { + $this->expectException(MissingOptionsException::class); + + $this->execute(['transformers' => ['callback' => []]], 'value'); + } + + public function testTransformersOptionMustBeAnArray(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->execute(['transformers' => 'trim'], 'value'); + } + + private function execute(array $options, mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('transform', TransformerTask::class, $options)); + $state->setInput($input); + + $registry = new TransformerRegistry(); + $registry->addTransformer(new ArrayLastTransformer()); + $registry->addTransformer(new CallbackTransformer()); + $registry->addTransformer(new TrimTransformer()); + $registry->addTransformer(new MappingTransformer($registry, new NullLogger(), PropertyAccess::createPropertyAccessor())); + + $task = new TransformerTask(new NullLogger(), $registry); + $task->initialize($state); + $task->execute($state); + + return $state; + } +} diff --git a/tests/Task/Validation/ValidatorTaskTest.php b/tests/Task/Validation/ValidatorTaskTest.php new file mode 100644 index 00000000..9c9e8829 --- /dev/null +++ b/tests/Task/Validation/ValidatorTaskTest.php @@ -0,0 +1,304 @@ +}> */ + private array $records = []; + + /** + * Same scenario as the legacy kernel-based test (test.validator_task). + */ + public function testValidInputIsForwardedUnchanged(): void + { + $input = [ + 'int_field' => 42, + 'any_field' => 'hello', + 'choice_field' => 'Some random value 1', + ]; + + $state = $this->execute(['constraints' => $this->collectionConstraints()], $input); + + self::assertSame($input, $state->getOutput()); + self::assertFalse($state->isSkipped()); + self::assertFalse($state->hasErrorOutput()); + self::assertSame([], $this->records); + } + + public function testInvalidInputThrowsAndLogsEachViolationAtCriticalLevelByDefault(): void + { + $input = ['int_field' => 'not an int', 'any_field' => 'hello', 'choice_field' => 'unknown']; + + try { + $this->execute(['constraints' => $this->collectionConstraints()], $input); + self::fail('An exception should have been thrown'); + } catch (\UnexpectedValueException $e) { + self::assertSame('2 constraint violations detected on validation', $e->getMessage()); + } + + self::assertCount(2, $this->records); + self::assertSame([LogLevel::CRITICAL, LogLevel::CRITICAL], array_column($this->records, 'level')); + self::assertSame( + ['property' => '[int_field]', 'violation_code' => Assert\Type::INVALID_TYPE_ERROR, 'invalid_value' => 'not an int'], + $this->records[0]['context'] + ); + self::assertSame('[choice_field]', $this->records[1]['context']['property']); + self::assertSame('unknown', $this->records[1]['context']['invalid_value']); + self::assertSame(Assert\Choice::NO_SUCH_CHOICE_ERROR, $this->records[1]['context']['violation_code']); + } + + public function testErrorOutputViolationsSkipsTheTaskAndSendsViolationsToTheErrorOutput(): void + { + $state = $this->execute(['constraints' => [['NotBlank' => null]], 'error_output_violations' => true], ''); + + self::assertTrue($state->isSkipped()); + self::assertNull($state->getOutput()); + $violations = $state->getErrorOutput(); + self::assertInstanceOf(ConstraintViolationListInterface::class, $violations); + self::assertCount(1, $violations); + self::assertSame(NotBlank::IS_BLANK_ERROR, $violations->get(0)->getCode()); + self::assertCount(1, $this->records); + } + + public function testErrorOutputViolationsDoesNothingSpecialOnValidInput(): void + { + $state = $this->execute(['constraints' => [['NotBlank' => null]], 'error_output_violations' => true], 'foo'); + + self::assertSame('foo', $state->getOutput()); + self::assertFalse($state->isSkipped()); + self::assertFalse($state->hasErrorOutput()); + } + + /** + * @return iterable + */ + public static function logErrorsProvider(): iterable + { + yield 'warning' => [LogLevel::WARNING, LogLevel::WARNING]; + yield 'debug' => [LogLevel::DEBUG, LogLevel::DEBUG]; + yield 'emergency' => [LogLevel::EMERGENCY, LogLevel::EMERGENCY]; + yield 'true means critical' => [true, LogLevel::CRITICAL]; + yield 'false disables logging' => [false, null]; + } + + #[DataProvider('logErrorsProvider')] + public function testLogErrorsSetsTheLogLevel(string|bool $logErrors, ?string $expectedLevel): void + { + $state = $this->execute( + ['constraints' => [['NotBlank' => null]], 'error_output_violations' => true, 'log_errors' => $logErrors], + '', + ); + + self::assertTrue($state->isSkipped()); + self::assertSame(null === $expectedLevel ? [] : [$expectedLevel], array_column($this->records, 'level')); + } + + public function testConstraintsOptionsAndNestedConstraintsAreBuilt(): void + { + $constraints = [ + ['Collection' => [ + 'allowExtraFields' => true, + 'fields' => [ + 'sku' => [['NotBlank' => null]], + 'price' => [['Type' => 'numeric'], ['PositiveOrZero' => null]], + ], + ]], + ]; + + $valid = $this->execute(['constraints' => $constraints], ['sku' => 'A1', 'price' => 10, 'extra' => true]); + self::assertSame(['sku' => 'A1', 'price' => 10, 'extra' => true], $valid->getOutput()); + + $invalid = $this->execute( + ['constraints' => $constraints, 'error_output_violations' => true], + ['sku' => '', 'price' => -1], + ); + $violations = $invalid->getErrorOutput(); + self::assertInstanceOf(ConstraintViolationListInterface::class, $violations); + self::assertCount(2, $violations); + self::assertSame('[sku]', $violations->get(0)->getPropertyPath()); + self::assertSame('[price]', $violations->get(1)->getPropertyPath()); + } + + public function testConstraintCanBeReferencedByFqcn(): void + { + $state = $this->execute( + ['constraints' => [[NotBlank::class => null]], 'error_output_violations' => true], + '', + ); + + self::assertTrue($state->isSkipped()); + } + + public function testNullConstraintsUseTheInputClassMetadata(): void + { + $state = $this->execute(['error_output_violations' => true], new ValidatorTaskTestEntity()); + + self::assertTrue($state->isSkipped()); + $violations = $state->getErrorOutput(); + self::assertInstanceOf(ConstraintViolationListInterface::class, $violations); + self::assertCount(1, $violations); + self::assertSame('name', $violations->get(0)->getPropertyPath()); + } + + public function testValidEntityIsForwardedUnchanged(): void + { + $entity = new ValidatorTaskTestEntity(); + $entity->name = 'Foo'; + $entity->sku = 'A1'; + + $state = $this->execute(['groups' => ['Default', 'import']], $entity); + + self::assertSame($entity, $state->getOutput()); + } + + public function testGroupsOptionSelectsTheValidatedConstraints(): void + { + $entity = new ValidatorTaskTestEntity(); + $entity->name = 'Foo'; + + $default = $this->execute(['error_output_violations' => true], $entity); + self::assertFalse($default->isSkipped()); + self::assertSame($entity, $default->getOutput()); + + $import = $this->execute(['groups' => ['import'], 'error_output_violations' => true], $entity); + self::assertTrue($import->isSkipped()); + $violations = $import->getErrorOutput(); + self::assertInstanceOf(ConstraintViolationListInterface::class, $violations); + self::assertCount(1, $violations); + self::assertSame('sku', $violations->get(0)->getPropertyPath()); + } + + /** + * @return iterable, class-string<\Throwable>}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'unknown log level' => [['log_errors' => 'verbose'], InvalidOptionsException::class]; + yield 'groups not an array' => [['groups' => 'import'], InvalidOptionsException::class]; + yield 'constraints not an array' => [['constraints' => 'NotBlank'], InvalidOptionsException::class]; + yield 'error_output_violations not a bool' => [['error_output_violations' => 1], InvalidOptionsException::class]; + yield 'unknown option' => [['unknown' => true], UndefinedOptionsException::class]; + } + + /** + * @param array $options + * @param class-string<\Throwable> $exception + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrowAtInitialization(array $options, string $exception): void + { + $this->expectException($exception); + $this->createTask()->initialize($this->createState($options, null)); + } + + /** + * @return array + */ + private function collectionConstraints(): array + { + return [ + ['Collection' => [ + 'fields' => [ + 'int_field' => [['NotNull' => null], ['Type' => 'int']], + 'any_field' => [['NotBlank' => null]], + 'choice_field' => [['Choice' => ['choices' => ['Some random value 1', 'Some random value 2']]]], + ], + ]], + ]; + } + + /** + * @param array $options + */ + private function execute(array $options, mixed $input): ProcessState + { + $state = $this->createState($options, $input); + $task = $this->createTask(); + $task->initialize($state); + $task->execute($state); + + return $state; + } + + private function createTask(): ValidatorTask + { + $logger = new class(function (array $record): void { + $this->records[] = $record; + }) extends AbstractLogger { + public function __construct(private readonly \Closure $onLog) + { + } + + public function log($level, string|\Stringable $message, array $context = []): void + { + ($this->onLog)(['level' => $level, 'message' => (string) $message, 'context' => $context]); + } + }; + + return new ValidatorTask($logger, Validation::createValidatorBuilder()->enableAttributeMapping()->getValidator()); + } + + /** + * @param array $options + */ + private function createState(array $options, mixed $input): ProcessState + { + $processConfiguration = new ProcessConfiguration('test', []); + $state = new ProcessState($processConfiguration, new ProcessHistory($processConfiguration)); + $state->setContextualOptionResolver(new ContextualOptionResolver()); + $state->setContext([]); + $state->setTaskConfiguration(new TaskConfiguration('validate', ValidatorTask::class, $options)); + $state->reset(false); + $state->setInput($input); + + return $state; + } +} + +final class ValidatorTaskTestEntity +{ + #[NotBlank] + public ?string $name = null; + + #[NotBlank(groups: ['import'])] + public ?string $sku = null; +} diff --git a/tests/Transformer/Array/ArrayLastTransformerTest.php b/tests/Transformer/Array/ArrayLastTransformerTest.php new file mode 100644 index 00000000..68207e00 --- /dev/null +++ b/tests/Transformer/Array/ArrayLastTransformerTest.php @@ -0,0 +1,57 @@ +getCode()); + } + + /** + * @return iterable, mixed}> + */ + public static function lastElementProvider(): iterable + { + yield 'list' => [['foo', 'bar', 'baz'], 'baz']; + yield 'single element' => [['foo'], 'foo']; + yield 'associative array' => [['a' => 1, 'b' => 2], 2]; + yield 'numeric keys not in order' => [[5 => 'x', 2 => 'y'], 'y']; + yield 'null last element' => [['foo', null], null]; + yield 'array last element' => [['foo', ['bar']], ['bar']]; + } + + /** + * @param array $value + */ + #[DataProvider('lastElementProvider')] + public function testTransform(array $value, mixed $expected): void + { + self::assertSame($expected, (new ArrayLastTransformer())->transform($value)); + } + + public function testNonArrayInputThrows(): void + { + $this->expectException(\TypeError::class); + + // @phpstan-ignore method.resultUnused (the call is expected to throw) + (new ArrayLastTransformer())->transform('foo'); + } +} diff --git a/tests/Transformer/Array/ArrayMapTransformerTest.php b/tests/Transformer/Array/ArrayMapTransformerTest.php new file mode 100644 index 00000000..b60a5b81 --- /dev/null +++ b/tests/Transformer/Array/ArrayMapTransformerTest.php @@ -0,0 +1,157 @@ +createTransformer()->getCode()); + } + + public function testTransformersAreAppliedToEachElementAndKeysArePreserved(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'transformers' => [ + 'callback#trim' => ['callback' => 'trim'], + 'callback#upper' => ['callback' => 'strtoupper'], + ], + ]); + + self::assertSame( + ['a' => 'FOO', 3 => 'BAR'], + $transformer->transform(['a' => ' foo ', 3 => 'bar '], $options) + ); + } + + public function testTraversableInputIsAccepted(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'transformers' => ['callback' => ['callback' => 'strtoupper']], + ]); + + self::assertSame(['x' => 'A', 'y' => 'B'], $transformer->transform(new \ArrayIterator(['x' => 'a', 'y' => 'b']), $options)); + } + + public function testEmptyTransformersReturnTheElementsUnchanged(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, []); + + self::assertSame([1, null, 'a'], $transformer->transform([1, null, 'a'], $options)); + } + + public function testNullElementsAreKeptByDefault(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'transformers' => ['callback' => ['callback' => [self::class, 'nullIfEmpty']]], + ]); + + self::assertSame([0 => 'a', 1 => null, 2 => 'b'], $transformer->transform(['a', '', 'b'], $options)); + } + + public function testSkipNullRemovesNullTransformedElements(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'skip_null' => true, + 'transformers' => ['callback' => ['callback' => [self::class, 'nullIfEmpty']]], + ]); + + self::assertSame([0 => 'a', 2 => 'b'], $transformer->transform(['a', '', 'b'], $options)); + } + + public function testFailingTransformerReportsTheElementKey(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'transformers' => ['callback' => ['callback' => [self::class, 'failOnBar']]], + ]); + + $this->expectException(TransformerException::class); + $this->expectExceptionMessage("For target property 'second', transformation 'callback' have failed: bar is not allowed"); + + $transformer->transform(['first' => 'foo', 'second' => 'bar'], $options); + } + + public function testNonIterableInputThrows(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, []); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Input value must be an array or traversable'); + + $transformer->transform('foo', $options); + } + + public function testSkipNullMustBeABoolean(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions($this->createTransformer(), ['skip_null' => 'yes']); + } + + public static function nullIfEmpty(string $value): ?string + { + return '' === $value ? null : $value; + } + + public static function failOnBar(string $value): string + { + if ('bar' === $value) { + throw new \RuntimeException('bar is not allowed'); + } + + return $value; + } + + private function createTransformer(): ArrayMapTransformer + { + $registry = new TransformerRegistry(); + $registry->addTransformer(new CallbackTransformer()); + + return new ArrayMapTransformer($registry); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(ArrayMapTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/Array/ArrayUnsetTransformerTest.php b/tests/Transformer/Array/ArrayUnsetTransformerTest.php new file mode 100644 index 00000000..65bf6520 --- /dev/null +++ b/tests/Transformer/Array/ArrayUnsetTransformerTest.php @@ -0,0 +1,91 @@ +getCode()); + } + + /** + * @return iterable, string|int, array}> + */ + public static function unsetProvider(): iterable + { + yield 'string key' => [['id' => 1, 'temporary_field' => 'foo'], 'temporary_field', ['id' => 1]]; + yield 'int key' => [['a', 'b', 'c'], 1, [0 => 'a', 2 => 'c']]; + yield 'numeric string key' => [['a', 'b'], '0', [1 => 'b']]; + yield 'missing key' => [['id' => 1], 'missing', ['id' => 1]]; + yield 'null value' => [['id' => 1, 'foo' => null], 'foo', ['id' => 1]]; + } + + /** + * @param array $value + * @param array $expected + */ + #[DataProvider('unsetProvider')] + public function testTransform(array $value, string|int $key, array $expected): void + { + $transformer = new ArrayUnsetTransformer(); + + self::assertSame($expected, $transformer->transform($value, $this->resolveOptions($transformer, ['key' => $key]))); + } + + public function testNonArrayInputThrows(): void + { + $transformer = new ArrayUnsetTransformer(); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Given value is not an array'); + + $transformer->transform(new \ArrayObject(['id' => 1]), $this->resolveOptions($transformer, ['key' => 'id'])); + } + + public function testKeyIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions(new ArrayUnsetTransformer(), []); + } + + public function testKeyMustBeAStringOrAnInt(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions(new ArrayUnsetTransformer(), ['key' => 1.5]); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(ArrayUnsetTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/CallbackTransformerTest.php b/tests/Transformer/CallbackTransformerTest.php new file mode 100644 index 00000000..af0d9d5a --- /dev/null +++ b/tests/Transformer/CallbackTransformerTest.php @@ -0,0 +1,139 @@ +getCode()); + } + + /** + * @return iterable, string, mixed}> + */ + public static function callbackProvider(): iterable + { + yield 'php function' => [['callback' => 'strtoupper'], 'foo', 'FOO']; + yield 'static method as array' => [['callback' => [self::class, 'doCallback']], '3', '3']; + yield 'static method as string' => [['callback' => self::class.'::doCallback'], '3', '3']; + yield 'left parameters' => [ + ['callback' => [self::class, 'doCallback'], 'left_parameters' => [1, 2]], + '3', + '1-2-3', + ]; + yield 'right parameters' => [ + ['callback' => [self::class, 'doCallback'], 'right_parameters' => [4, 5]], + '3', + '3-4-5', + ]; + yield 'left and right parameters' => [ + ['callback' => [self::class, 'doCallback'], 'left_parameters' => [1, 2], 'right_parameters' => [4, 5]], + '3', + '1-2-3-4-5', + ]; + yield 'value in second position' => [ + ['callback' => 'explode', 'left_parameters' => [',']], + 'a,b', + ['a', 'b'], + ]; + yield 'extra right parameter' => [ + ['callback' => 'json_decode', 'right_parameters' => [true]], + '{"a":1}', + ['a' => 1], + ]; + } + + /** + * @param array $options + */ + #[DataProvider('callbackProvider')] + public function testTransform(array $options, mixed $value, mixed $expected): void + { + $transformer = new CallbackTransformer(); + + self::assertSame($expected, $transformer->transform($value, $this->resolveOptions($transformer, $options))); + } + + public function testAdditionalParametersAreUsedAsRightParameters(): void + { + $transformer = new CallbackTransformer(); + $options = $this->resolveOptions($transformer, [ + 'callback' => [self::class, 'doCallback'], + 'additional_parameters' => [7, 8], + ]); + + self::assertSame('6-7-8', $transformer->transform('6', $options)); + } + + public function testAdditionalParametersAreIgnoredWhenRightParametersAreSet(): void + { + $transformer = new CallbackTransformer(); + $options = $this->resolveOptions($transformer, [ + 'callback' => [self::class, 'doCallback'], + 'right_parameters' => [4], + 'additional_parameters' => [7, 8], + ]); + + self::assertSame('6-4', $transformer->transform('6', $options)); + } + + public function testCallbackIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions(new CallbackTransformer(), []); + } + + public function testNonCallableCallbackIsRejected(): void + { + $this->expectException(InvalidOptionsException::class); + $this->expectExceptionMessage('Callback option must be callable'); + + $this->resolveOptions(new CallbackTransformer(), ['callback' => 'not_a_function']); + } + + public function testClosureCallbackIsRejected(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions(new CallbackTransformer(), ['callback' => strtoupper(...)]); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(CallbackTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/ConvertValueTransformerTest.php b/tests/Transformer/ConvertValueTransformerTest.php new file mode 100644 index 00000000..d424a791 --- /dev/null +++ b/tests/Transformer/ConvertValueTransformerTest.php @@ -0,0 +1,192 @@ + 'text', + 'NUMERIQUE' => 'number', + 1 => 'one', + '1.5' => 'one and a half', + '' => 'empty', + 'null_value' => null, + ]; + + /** + * @return iterable + */ + public static function mappedValueProvider(): iterable + { + yield 'string key' => ['TEXTE', 'text']; + yield 'int key' => [1, 'one']; + yield 'numeric string matches int key' => ['1', 'one']; + yield 'empty string key' => ['', 'empty']; + yield 'null mapped value' => ['null_value', null]; + } + + #[DataProvider('mappedValueProvider')] + public function testMappedValueIsConverted(mixed $value, mixed $expected): void + { + self::assertSame($expected, $this->transform($value, [])); + } + + public function testNullAlwaysReturnsNull(): void + { + self::assertNull($this->transform(null, [])); + self::assertNull($this->transform(null, ['map' => [], 'auto_cast' => true])); + } + + public function testMissingValueThrowsByDefault(): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Missing value in map 'DATE'"); + + $this->transform('DATE', []); + } + + public function testMissingValueReturnsNullWithIgnoreMissing(): void + { + self::assertNull($this->transform('DATE', ['ignore_missing' => true])); + } + + public function testMissingValueIsKeptWithKeepMissing(): void + { + self::assertSame('DATE', $this->transform('DATE', ['keep_missing' => true])); + self::assertSame(42, $this->transform(42, ['keep_missing' => true])); + } + + public function testKeepMissingTakesPrecedenceOverIgnoreMissing(): void + { + self::assertSame('DATE', $this->transform('DATE', ['keep_missing' => true, 'ignore_missing' => true])); + } + + /** + * @return iterable + */ + public static function invalidKeyProvider(): iterable + { + yield 'float' => [1.5, 'double']; + yield 'bool' => [true, 'boolean']; + yield 'object' => [new \stdClass(), 'object']; + yield 'array' => [['TEXTE'], 'array']; + } + + #[DataProvider('invalidKeyProvider')] + public function testInvalidKeyThrowsWithoutAutoCast(mixed $value, string $type): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Value of type {$type} is not a valid array index, set auto_cast to true to cast it to a string"); + + $this->transform($value, []); + } + + /** + * @return iterable + */ + public static function autoCastProvider(): iterable + { + yield 'float' => [1.5, 'one and a half']; + yield 'true' => [true, 'one']; + yield 'false' => [false, 'empty']; + yield 'stringable' => [new class implements \Stringable { + public function __toString(): string + { + return 'NUMERIQUE'; + } + }, 'number']; + } + + #[DataProvider('autoCastProvider')] + public function testAutoCastConvertsInvalidKeyToString(mixed $value, mixed $expected): void + { + self::assertSame($expected, $this->transform($value, ['auto_cast' => true])); + } + + public function testAutoCastKeepsCastValueWhenMissing(): void + { + self::assertSame('2.5', $this->transform(2.5, ['auto_cast' => true, 'keep_missing' => true])); + } + + public function testArrayIsRejectedEvenWithAutoCast(): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Unexpected input of type 'array' in convert_value transformer"); + + $this->transform(['TEXTE'], ['auto_cast' => true]); + } + + public function testMapIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions([]); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'map not an array' => [['map' => 'foo']]; + yield 'ignore_missing not a bool' => [['map' => [], 'ignore_missing' => 1]]; + yield 'keep_missing not a bool' => [['map' => [], 'keep_missing' => 'yes']]; + yield 'auto_cast not a bool' => [['map' => [], 'auto_cast' => null]]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrow(array $options): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions($options); + } + + public function testGetCode(): void + { + self::assertSame('convert_value', (new ConvertValueTransformer())->getCode()); + } + + /** + * @param array $options + */ + private function transform(mixed $value, array $options): mixed + { + return (new ConvertValueTransformer())->transform($value, $this->resolveOptions($options + ['map' => self::MAP])); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(array $options): array + { + $resolver = new OptionsResolver(); + (new ConvertValueTransformer())->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/EvaluatorTransformerTest.php b/tests/Transformer/EvaluatorTransformerTest.php new file mode 100644 index 00000000..174c5b20 --- /dev/null +++ b/tests/Transformer/EvaluatorTransformerTest.php @@ -0,0 +1,171 @@ +resolveOptions($transformer, ['expression' => 'price * quantity']); + + self::assertSame('price * quantity', $options['expression']); + self::assertSame(30, $transformer->transform(['price' => 10, 'quantity' => 3], $options)); + self::assertSame(7.5, $transformer->transform(['price' => 2.5, 'quantity' => 3], $options)); + } + + public function testExpressionIsParsedOnceWhenVariablesAreDefined(): void + { + $transformer = new EvaluatorTransformer(); + $options = $this->resolveOptions($transformer, [ + 'expression' => 'price * quantity', + 'variables' => ['price', 'quantity'], + ]); + + self::assertInstanceOf(ParsedExpression::class, $options['expression']); + self::assertSame(30, $transformer->transform(['price' => 10, 'quantity' => 3], $options)); + self::assertSame(4, $transformer->transform(['price' => 2, 'quantity' => 2], $options)); + } + + public function testParsedExpressionIsAccepted(): void + { + $transformer = new EvaluatorTransformer(); + $expression = (new ExpressionLanguage())->parse('name ~ "!"', ['name']); + $options = $this->resolveOptions($transformer, ['expression' => $expression]); + + self::assertSame($expression, $options['expression']); + self::assertSame('foo!', $transformer->transform(['name' => 'foo'], $options)); + } + + /** + * @return iterable, mixed}> + */ + public static function expressionProvider(): iterable + { + yield 'comparison' => ['value > 10', ['value' => 12], true]; + yield 'ternary' => ['value ? "yes" : "no"', ['value' => false], 'no']; + yield 'array access' => ['item["name"]', ['item' => ['name' => 'foo']], 'foo']; + yield 'constant expression with empty input' => ['1 + 1', [], 2]; + yield 'built-in function' => ['constant("PHP_INT_MAX")', [], \PHP_INT_MAX]; + } + + /** + * @param array $value + */ + #[DataProvider('expressionProvider')] + public function testTransform(string $expression, array $value, mixed $expected): void + { + $transformer = new EvaluatorTransformer(); + + self::assertSame($expected, $transformer->transform($value, $this->resolveOptions($transformer, ['expression' => $expression]))); + } + + public function testUndeclaredVariableThrowsWhenOptionsAreResolved(): void + { + $transformer = new EvaluatorTransformer(); + + $this->expectException(SyntaxError::class); + $this->expectExceptionMessage('Variable "quantity" is not valid'); + + $this->resolveOptions($transformer, ['expression' => 'price * quantity', 'variables' => ['price']]); + } + + public function testUndefinedVariableThrowsOnEvaluation(): void + { + $transformer = new EvaluatorTransformer(); + $options = $this->resolveOptions($transformer, ['expression' => 'price * quantity']); + + $this->expectException(SyntaxError::class); + $this->expectExceptionMessage('Variable "quantity" is not valid'); + + $transformer->transform(['price' => 10], $options); + } + + public function testBundleExpressionFunctionsAreNotAvailable(): void + { + $transformer = new EvaluatorTransformer(); + $options = $this->resolveOptions($transformer, ['expression' => 'preg_match("/a/", value)']); + + $this->expectException(SyntaxError::class); + $this->expectExceptionMessage('The function "preg_match" does not exist'); + + $transformer->transform(['value' => 'abc'], $options); + } + + public function testNonArrayInputThrowsTypeError(): void + { + $transformer = new EvaluatorTransformer(); + $options = $this->resolveOptions($transformer, ['expression' => '1 + 1']); + + $this->expectException(\TypeError::class); + + $transformer->transform('not an array', $options); + } + + public function testExpressionIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions(new EvaluatorTransformer(), []); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'expression not a string' => [['expression' => 42]]; + yield 'variables not an array' => [['expression' => '1', 'variables' => 'foo']]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrow(array $options): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions(new EvaluatorTransformer(), $options); + } + + public function testGetCode(): void + { + self::assertSame('evaluator', (new EvaluatorTransformer())->getCode()); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(EvaluatorTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/MappingTransformerTest.php b/tests/Transformer/MappingTransformerTest.php new file mode 100644 index 00000000..6fd7beee --- /dev/null +++ b/tests/Transformer/MappingTransformerTest.php @@ -0,0 +1,521 @@ +createTransformer()->getCode()); + } + + public function testMappingIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions($this->createTransformer(), []); + } + + public function testSimpleMappingFromOneArrayToAnother(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'field2' => ['code' => '[field]'], + ], + ]); + + self::assertSame(['field2' => 'value'], $transformer->transform(['field' => 'value'], $options)); + } + + public function testSourcePropertyDefaultsToTargetProperty(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + '[label]' => null, + ], + ]); + + self::assertSame(['label' => 'foo'], $transformer->transform(['label' => 'foo', 'other' => 1], $options)); + } + + public function testMissingPropertyThrowsWhenNotIgnored(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'field2' => ['code' => 'missing'], + ], + ]); + + $this->expectException(NoSuchPropertyException::class); + + $transformer->transform((object) ['field' => 'value'], $options); + } + + public function testMissingPropertyIsLogged(): void + { + $logger = $this->createCollectingLogger(); + $transformer = $this->createTransformer($logger); + $options = $this->resolveOptions($transformer, [ + 'ignore_missing' => true, + 'mapping' => [ + 'field2' => ['code' => 'missing'], + ], + ]); + + $transformer->transform((object) ['field' => 'value'], $options); + + self::assertCount(1, $logger->records); + self::assertSame('Mapping exception', $logger->records[0]['message']); + self::assertSame('missing', $logger->records[0]['context']['srcKey']); + } + + public function testGlobalIgnoreMissingSkipsMissingProperties(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'ignore_missing' => true, + 'mapping' => [ + 'field2' => ['code' => 'missing'], + 'field3' => ['code' => 'field'], + ], + ]); + + self::assertSame(['field3' => 'value'], $transformer->transform((object) ['field' => 'value'], $options)); + } + + public function testPropertyIgnoreMissingSkipsOnlyThisProperty(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'field2' => ['code' => 'missing', 'ignore_missing' => true], + 'field3' => ['code' => 'missing'], + ], + ]); + + $this->expectException(NoSuchPropertyException::class); + + $transformer->transform((object) ['field' => 'value'], $options); + } + + public function testMultipleSourcesBuildAnArray(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'slug' => ['code' => ['name' => '[name]', 'id' => '[id]']], + ], + ]); + + self::assertSame( + ['slug' => ['name' => 'foo', 'id' => 12]], + $transformer->transform(['name' => 'foo', 'id' => 12], $options) + ); + } + + public function testMultipleSourcesInSequence(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'out' => ['code' => ['[field1]', '[field2]', '[field3]']], + ], + ]); + + self::assertSame( + ['out' => ['a', 'b', 'c']], + $transformer->transform(['field1' => 'a', 'field2' => 'b', 'field3' => 'c'], $options) + ); + } + + public function testMultipleSourcesSkipOnlyMissingKeysWhenIgnored(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'out' => ['code' => ['a' => 'field', 'b' => 'missing'], 'ignore_missing' => true], + ], + ]); + + self::assertSame(['out' => ['a' => 'value']], $transformer->transform((object) ['field' => 'value'], $options)); + } + + public function testMultipleSourcesThrowOnMissingKeyWhenNotIgnored(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'out' => ['code' => ['a' => 'field', 'b' => 'missing']], + ], + ]); + + $this->expectException(NoSuchPropertyException::class); + + $transformer->transform((object) ['field' => 'value'], $options); + } + + public function testDotSourceReturnsTheWholeInput(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'out' => ['code' => '.'], + ], + ]); + + self::assertSame(['out' => ['value' => 'ok']], $transformer->transform(['value' => 'ok'], $options)); + } + + public function testDotSourceInsideAListOfSources(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'out' => ['code' => ['some_field' => '[field]', 'full' => '.']], + ], + ]); + + self::assertSame( + ['out' => ['some_field' => 'ok', 'full' => ['field' => 'ok']]], + $transformer->transform(['field' => 'ok'], $options) + ); + } + + public function testDeepTargetPropertyPathBuildsANestedArray(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + '[field1][field2][field3]' => ['code' => '[value]'], + ], + ]); + + self::assertSame( + ['field1' => ['field2' => ['field3' => 'ok']]], + $transformer->transform(['value' => 'ok'], $options) + ); + } + + public function testConstantTakesPrecedenceOverSetNullAndCode(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'required' => ['constant' => true, 'set_null' => true, 'code' => 'missing'], + ], + ]); + + self::assertSame(['required' => true], $transformer->transform([], $options)); + } + + public function testSetNullTakesPrecedenceOverCode(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'reference' => ['set_null' => true, 'code' => 'missing'], + ], + ]); + + self::assertSame(['reference' => null], $transformer->transform(new \stdClass(), $options)); + } + + public function testNumericTargetPropertiesAreCastToString(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 0 => ['constant' => 'a'], + 1 => ['constant' => 'b'], + ], + ]); + + self::assertSame(['a', 'b'], $transformer->transform([], $options)); + } + + public function testTransformersAreAppliedToTheSourceValue(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'code' => [ + 'code' => '[Code]', + 'transformers' => [ + 'callback' => ['callback' => 'strtolower'], + ], + ], + ], + ]); + + self::assertSame(['code' => 'abc'], $transformer->transform(['Code' => 'ABC'], $options)); + } + + public function testSameSubTransformerCanBeUsedMultipleTimesWithSuffixes(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'field2' => [ + 'code' => '[field]', + 'transformers' => [ + 'callback#1' => ['callback' => 'array_filter'], + 'callback#2' => ['callback' => 'array_reverse'], + 'callback#3' => ['callback' => 'array_values'], + ], + ], + ], + ]); + + self::assertSame(['field2' => [2, 4, 3]], $transformer->transform(['field' => [3, null, 4, 2]], $options)); + } + + public function testFailingTransformerReportsTheTargetProperty(): void + { + $logger = $this->createCollectingLogger(); + $transformer = $this->createTransformer($logger); + $options = $this->resolveOptions($transformer, [ + 'mapping' => [ + 'target' => [ + 'code' => '[source]', + 'transformers' => [ + 'callback' => ['callback' => [self::class, 'failingCallback']], + ], + ], + ], + ]); + + try { + $transformer->transform(['source' => 'foo'], $options); + self::fail('A TransformerException should have been thrown'); + } catch (TransformerException $exception) { + self::assertSame( + "For target property 'target', transformation 'callback' have failed: failing callback", + $exception->getMessage() + ); + } + + self::assertCount(1, $logger->records); + self::assertSame('Transformation exception', $logger->records[0]['message']); + self::assertSame('failing callback', $logger->records[0]['context']['message']); + } + + public function testInitialValueIsUsedAsDestination(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'initial_value' => ['existing' => 1], + 'mapping' => [ + 'field2' => ['code' => '[field]'], + ], + ]); + + self::assertSame( + ['existing' => 1, 'field2' => 'value'], + $transformer->transform(['field' => 'value'], $options) + ); + } + + public function testInitialValueCanBeAnObject(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'initial_value' => (object) ['field2' => null], + 'mapping' => [ + 'field2' => ['code' => '[field]'], + ], + ]); + + $result = $transformer->transform(['field' => 'value'], $options); + + self::assertEquals((object) ['field2' => 'value'], $result); + } + + public function testKeepInputCopiesAnArrayInput(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'keep_input' => true, + 'mapping' => [ + '[field2]' => ['code' => '[field]'], + ], + ]); + $input = ['field' => 'value']; + + self::assertSame(['field' => 'value', 'field2' => 'value'], $transformer->transform($input, $options)); + self::assertSame(['field' => 'value'], $input); + } + + public function testKeepInputModifiesAnObjectInPlace(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'keep_input' => true, + 'mapping' => [ + 'address.flag' => ['code' => 'address.postCode'], + ], + ]); + $input = (object) ['address' => (object) ['postCode' => '69005', 'flag' => null]]; + + $result = $transformer->transform($input, $options); + + self::assertSame($input, $result); + self::assertSame('69005', $input->address->flag); + } + + public function testKeepInputCannotBeCombinedWithInitialValue(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'keep_input' => true, + 'initial_value' => ['foo' => 'bar'], + 'mapping' => [], + ]); + + $this->expectException(InvalidOptionsException::class); + $this->expectExceptionMessage('The options "initial_value" and "keep_input" can\'t be both enabled.'); + + $transformer->transform([], $options); + } + + public function testNonWritableObjectPropertyThrows(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'initial_value' => new \ArrayIterator(), + 'mapping' => [ + 'field2' => ['constant' => 'value'], + ], + ]); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Property 'field2' is not writable"); + + $transformer->transform([], $options); + } + + public function testMergeCallbackIsUsedToWriteValues(): void + { + $destination = new \ArrayObject(); + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'initial_value' => $destination, + 'merge_callback' => static function (\ArrayObject $result, string $property, mixed $value): void { + $result[$property] = strtoupper((string) $value); + }, + 'mapping' => [ + 'field2' => ['code' => '[field]'], + ], + ]); + + $result = $transformer->transform(['field' => 'value'], $options); + + self::assertSame($destination, $result); + self::assertSame(['field2' => 'VALUE'], $destination->getArrayCopy()); + } + + public function testMergeCallbackCanModifyAnArrayDestinationByReference(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'merge_callback' => static function (array &$result, string $property, mixed $value): void { + $result['merged_'.$property] = $value; + }, + 'mapping' => [ + 'field2' => ['code' => '[field]'], + ], + ]); + + self::assertSame(['merged_field2' => 'value'], $transformer->transform(['field' => 'value'], $options)); + } + + public function testInvalidMappingOptionIsRejected(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions($this->createTransformer(), [ + 'mapping' => [ + 'field' => ['set_null' => 'yes'], + ], + ]); + } + + public static function failingCallback(): never + { + throw new \RuntimeException('failing callback'); + } + + private function createTransformer(?LoggerInterface $logger = null): MappingTransformer + { + $registry = new TransformerRegistry(); + $registry->addTransformer(new CallbackTransformer()); + + return new MappingTransformer( + $registry, + $logger ?? new NullLogger(), + PropertyAccess::createPropertyAccessor() + ); + } + + /** + * @return AbstractLogger&object{records: list}>} + */ + private function createCollectingLogger(): AbstractLogger + { + return new class extends AbstractLogger { + /** @var list}> */ + public array $records = []; + + public function log($level, \Stringable|string $message, array $context = []): void + { + $this->records[] = ['level' => $level, 'message' => (string) $message, 'context' => $context]; + } + }; + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(MappingTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/Object/InstantiateTransformerTest.php b/tests/Transformer/Object/InstantiateTransformerTest.php new file mode 100644 index 00000000..53336787 --- /dev/null +++ b/tests/Transformer/Object/InstantiateTransformerTest.php @@ -0,0 +1,118 @@ +getCode()); + } + + public function testListIsPassedAsPositionalArguments(): void + { + $transformer = new InstantiateTransformer(); + $options = $this->resolveOptions($transformer, ['class' => \DateTimeImmutable::class]); + + $result = $transformer->transform(['2024-01-02 03:04:05', new \DateTimeZone('Europe/Paris')], $options); + + self::assertInstanceOf(\DateTimeImmutable::class, $result); + self::assertSame('2024-01-02T03:04:05+01:00', $result->format(\DATE_ATOM)); + } + + public function testStringKeysArePassedAsNamedArguments(): void + { + $transformer = new InstantiateTransformer(); + $options = $this->resolveOptions($transformer, ['class' => \DateTimeImmutable::class]); + + $result = $transformer->transform(['timezone' => new \DateTimeZone('UTC'), 'datetime' => '2024-01-02'], $options); + + self::assertInstanceOf(\DateTimeImmutable::class, $result); + self::assertSame('2024-01-02T00:00:00+00:00', $result->format(\DATE_ATOM)); + } + + public function testEmptyArrayCallsTheConstructorWithoutArguments(): void + { + $transformer = new InstantiateTransformer(); + $options = $this->resolveOptions($transformer, ['class' => \ArrayObject::class]); + + $result = $transformer->transform([], $options); + + self::assertInstanceOf(\ArrayObject::class, $result); + self::assertCount(0, $result); + } + + public function testEachCallCreatesANewInstance(): void + { + $transformer = new InstantiateTransformer(); + $options = $this->resolveOptions($transformer, ['class' => \ArrayObject::class]); + + self::assertNotSame($transformer->transform([], $options), $transformer->transform([], $options)); + } + + public function testNonArrayInputThrows(): void + { + $transformer = new InstantiateTransformer(); + $options = $this->resolveOptions($transformer, ['class' => \ArrayObject::class]); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Input value must be an array for transformer instantiate'); + + $transformer->transform('foo', $options); + } + + public function testUnknownClassThrows(): void + { + $transformer = new InstantiateTransformer(); + $options = $this->resolveOptions($transformer, ['class' => 'App\Unknown\Foo']); + + $this->expectException(\ReflectionException::class); + + $transformer->transform([], $options); + } + + public function testClassIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions(new InstantiateTransformer(), []); + } + + public function testClassMustBeAString(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions(new InstantiateTransformer(), ['class' => new \ArrayObject()]); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(InstantiateTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/Object/PropertyAccessorTransformerTest.php b/tests/Transformer/Object/PropertyAccessorTransformerTest.php new file mode 100644 index 00000000..c0effa66 --- /dev/null +++ b/tests/Transformer/Object/PropertyAccessorTransformerTest.php @@ -0,0 +1,168 @@ +createTransformer()->getCode()); + } + + /** + * @return iterable + */ + public static function readProvider(): iterable + { + yield 'array key' => [['key' => 'foo'], '[key]', 'foo']; + yield 'numeric array key' => [['a', 'b', 'c'], '[2]', 'c']; + yield 'nested array keys' => [['a' => ['b' => 'foo']], '[a][b]', 'foo']; + yield 'object property' => [(object) ['name' => 'foo'], 'name', 'foo']; + yield 'nested object property' => [(object) ['a' => (object) ['b' => 'foo']], 'a.b', 'foo']; + yield 'mixed object and array' => [(object) ['a' => ['b' => 'foo']], 'a[b]', 'foo']; + } + + #[DataProvider('readProvider')] + public function testTransform(mixed $value, string $propertyPath, mixed $expected): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property_path' => $propertyPath]); + + self::assertSame($expected, $transformer->transform($value, $options)); + } + + public function testNullInputThrowsByDefault(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property_path' => 'name']); + + $this->expectException(\TypeError::class); + + $transformer->transform(null, $options); + } + + public function testNullInputReturnsNullWithIgnoreNull(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property_path' => 'name', 'ignore_null' => true]); + + self::assertNull($transformer->transform(null, $options)); + } + + public function testMissingPropertyThrowsByDefault(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property_path' => 'missing']); + + $this->expectException(NoSuchPropertyException::class); + + $transformer->transform(new \stdClass(), $options); + } + + public function testMissingPropertyReturnsNullWithIgnoreMissing(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property_path' => 'missing', 'ignore_missing' => true]); + + self::assertNull($transformer->transform(new \stdClass(), $options)); + } + + public function testMissingIndexThrowsWithAStrictAccessor(): void + { + $transformer = $this->createTransformer( + PropertyAccess::createPropertyAccessorBuilder()->enableExceptionOnInvalidIndex()->getPropertyAccessor() + ); + $options = $this->resolveOptions($transformer, ['property_path' => '[address][city]']); + + $this->expectException(NoSuchIndexException::class); + + $transformer->transform(['address' => []], $options); + } + + public function testMissingIndexReturnsNullWithIgnoreMissing(): void + { + $transformer = $this->createTransformer( + PropertyAccess::createPropertyAccessorBuilder()->enableExceptionOnInvalidIndex()->getPropertyAccessor() + ); + $options = $this->resolveOptions($transformer, ['property_path' => '[address][city]', 'ignore_missing' => true]); + + self::assertNull($transformer->transform(['address' => []], $options)); + } + + public function testMissingIndexReturnsNullWithTheDefaultAccessor(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property_path' => '[missing]']); + + self::assertNull($transformer->transform([], $options)); + } + + public function testPropertyPathIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions($this->createTransformer(), []); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'property_path not a string' => [['property_path' => 1]]; + yield 'ignore_null not a bool' => [['property_path' => 'a', 'ignore_null' => 'yes']]; + yield 'ignore_missing not a bool' => [['property_path' => 'a', 'ignore_missing' => 1]]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsAreRejected(array $options): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions($this->createTransformer(), $options); + } + + private function createTransformer(?PropertyAccessorInterface $accessor = null): PropertyAccessorTransformer + { + return new PropertyAccessorTransformer($accessor ?? PropertyAccess::createPropertyAccessor()); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(PropertyAccessorTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/Object/RecursivePropertySetterTransformerTest.php b/tests/Transformer/Object/RecursivePropertySetterTransformerTest.php new file mode 100644 index 00000000..9914ef76 --- /dev/null +++ b/tests/Transformer/Object/RecursivePropertySetterTransformerTest.php @@ -0,0 +1,260 @@ +createTransformer()->getCode()); + } + + public function testPropertiesArePropagatedToArrayItems(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => '[items]', + 'set_properties' => [ + '[parentId]' => '[id]', + '[parentName]' => '[name]', + ], + ]); + + $result = $transformer->transform( + ['id' => 1, 'name' => 'Parent', 'items' => [['label' => 'A'], ['label' => 'B']]], + $options + ); + + self::assertSame([ + ['label' => 'A', 'parentId' => 1, 'parentName' => 'Parent'], + ['label' => 'B', 'parentId' => 1, 'parentName' => 'Parent'], + ], $result); + } + + public function testObjectItemsAreModifiedInPlace(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => 'items', + 'set_properties' => ['parentId' => 'id'], + ]); + $item = new \stdClass(); + $item->label = 'A'; + $item->parentId = null; + $input = (object) ['id' => 7, 'items' => [$item]]; + + $result = $transformer->transform($input, $options); + + self::assertIsArray($result); + self::assertSame($item, $result[0]); + self::assertSame(7, $item->parentId); + } + + public function testMissingPropertyIsAddedToStdClassItems(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => 'items', + 'set_properties' => ['parentId' => 'id'], + ]); + + $result = $transformer->transform((object) ['id' => 7, 'items' => [(object) ['label' => 'A']]], $options); + + self::assertEquals([(object) ['label' => 'A', 'parentId' => 7]], $result); + } + + public function testTraversableCollectionIsSupported(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => '[items]', + 'set_properties' => ['[parentId]' => '[id]'], + ]); + + $result = $transformer->transform(['id' => 1, 'items' => new \ArrayObject([['label' => 'A']])], $options); + + self::assertInstanceOf(\ArrayObject::class, $result); + self::assertSame([['label' => 'A', 'parentId' => 1]], $result->getArrayCopy()); + } + + public function testNonWritableItemPropertyThrows(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => '[items]', + 'set_properties' => ['parentId' => '[id]'], + ]); + + $this->expectException(NoSuchPropertyException::class); + + $transformer->transform(['id' => 1, 'items' => [new \ArrayIterator()]], $options); + } + + public function testNullInputThrowsByDefault(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => 'items', + 'set_properties' => [], + ]); + + $this->expectException(\TypeError::class); + + $transformer->transform(null, $options); + } + + public function testNullInputReturnsNullWithIgnoreNull(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => 'items', + 'set_properties' => [], + 'ignore_null' => true, + ]); + + self::assertNull($transformer->transform(null, $options)); + } + + public function testNonIterableCollectionThrows(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => '[items]', + 'set_properties' => [], + ]); + + $this->expectException(TransformerException::class); + $this->expectExceptionMessage("Transformation '[items]' have failed"); + + $transformer->transform(['items' => 'foo'], $options); + } + + public function testMissingCollectionThrowsByDefault(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => 'items', + 'set_properties' => [], + ]); + + $this->expectException(NoSuchPropertyException::class); + + $transformer->transform(new \stdClass(), $options); + } + + public function testMissingCollectionReturnsNullWithIgnoreMissing(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => 'items', + 'set_properties' => [], + 'ignore_missing' => true, + ]); + + self::assertNull($transformer->transform(new \stdClass(), $options)); + } + + public function testNullSourceValueThrowsByDefault(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => '[items]', + 'set_properties' => ['[parentId]' => '[id]'], + ]); + + $this->expectException(TransformerException::class); + $this->expectExceptionMessage("Transformation '[id]' have failed"); + + $transformer->transform(['id' => null, 'items' => [[]]], $options); + } + + public function testNullSourceValueIsSetWithIgnoreNull(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => '[items]', + 'set_properties' => ['[parentId]' => '[id]'], + 'ignore_null' => true, + ]); + + self::assertSame( + [['parentId' => null]], + $transformer->transform(['id' => null, 'items' => [[]]], $options) + ); + } + + public function testMissingSourceValueThrowsByDefault(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => 'items', + 'set_properties' => ['[parentId]' => 'missing'], + ]); + + $this->expectException(NoSuchPropertyException::class); + + $transformer->transform((object) ['items' => [[]]], $options); + } + + public function testMissingSourceValueIsSetAsNullWithIgnoreMissing(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'iterator' => 'items', + 'set_properties' => ['[parentId]' => 'missing'], + 'ignore_missing' => true, + ]); + + self::assertSame( + [['label' => 'A', 'parentId' => null]], + $transformer->transform((object) ['items' => [['label' => 'A']]], $options) + ); + } + + public function testRequiredOptions(): void + { + $this->expectException(MissingOptionsException::class); + $this->expectExceptionMessage('The required options "iterator", "set_properties" are missing.'); + + $this->resolveOptions($this->createTransformer(), []); + } + + private function createTransformer(): RecursivePropertySetterTransformer + { + return new RecursivePropertySetterTransformer(PropertyAccess::createPropertyAccessor()); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(RecursivePropertySetterTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/Serialization/DenormalizeTransformerTest.php b/tests/Transformer/Serialization/DenormalizeTransformerTest.php new file mode 100644 index 00000000..4b68fba1 --- /dev/null +++ b/tests/Transformer/Serialization/DenormalizeTransformerTest.php @@ -0,0 +1,159 @@ +createTransformer()->getCode()); + } + + public function testValueIsDenormalizedIntoTheGivenClass(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['class' => \DateTimeImmutable::class]); + + $result = $transformer->transform('2024-01-02T03:04:05+00:00', $options); + + self::assertInstanceOf(\DateTimeImmutable::class, $result); + self::assertSame('2024-01-02T03:04:05+00:00', $result->format(\DATE_ATOM)); + } + + public function testCollectionClassIsSupported(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['class' => \DateTimeImmutable::class.'[]']); + + $result = $transformer->transform(['a' => '2024-01-02', 'b' => '2024-02-03'], $options); + + self::assertIsArray($result); + self::assertSame(['a', 'b'], array_keys($result)); + self::assertContainsOnlyInstancesOf(\DateTimeImmutable::class, $result); + } + + public function testContextIsPassedToTheDenormalizer(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'class' => \DateTimeImmutable::class, + 'context' => [DateTimeNormalizer::FORMAT_KEY => 'd/m/Y H:i', DateTimeNormalizer::TIMEZONE_KEY => 'UTC'], + ]); + + $result = $transformer->transform('02/01/2024 03:04', $options); + + self::assertInstanceOf(\DateTimeImmutable::class, $result); + self::assertSame('2024-01-02T03:04:00+00:00', $result->format(\DATE_ATOM)); + } + + public function testClassFormatAndContextArePassedToTheDenormalizer(): void + { + $denormalizer = new class implements DenormalizerInterface { + public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): array + { + return ['data' => $data, 'type' => $type, 'format' => $format, 'context' => $context]; + } + + public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool + { + return true; + } + + public function getSupportedTypes(?string $format): array + { + return ['*' => true]; + } + }; + $transformer = new DenormalizeTransformer($denormalizer); + $options = $this->resolveOptions($transformer, [ + 'class' => 'App\Foo', + 'format' => 'json', + 'context' => ['foo' => 'bar'], + ]); + + self::assertSame( + ['data' => ['a' => 1], 'type' => 'App\Foo', 'format' => 'json', 'context' => ['foo' => 'bar']], + $transformer->transform(['a' => 1], $options) + ); + } + + public function testInvalidValueThrows(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['class' => \DateTimeImmutable::class]); + + $this->expectException(NotNormalizableValueException::class); + + $transformer->transform('not a date', $options); + } + + public function testClassIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions($this->createTransformer(), []); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'class not a string' => [['class' => 1]]; + yield 'format not a string' => [['class' => 'Foo', 'format' => 1]]; + yield 'context not an array' => [['class' => 'Foo', 'context' => 'foo']]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsAreRejected(array $options): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions($this->createTransformer(), $options); + } + + private function createTransformer(): DenormalizeTransformer + { + return new DenormalizeTransformer(new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer()])); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(DenormalizeTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/Serialization/NormalizeTransformerTest.php b/tests/Transformer/Serialization/NormalizeTransformerTest.php new file mode 100644 index 00000000..286f48b0 --- /dev/null +++ b/tests/Transformer/Serialization/NormalizeTransformerTest.php @@ -0,0 +1,148 @@ +createTransformer()->getCode()); + } + + public function testObjectIsNormalizedWithDefaultOptions(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, []); + + self::assertSame( + ['name' => 'foo', 'tags' => ['a', 'b']], + $transformer->transform((object) ['name' => 'foo', 'tags' => ['a', 'b']], $options) + ); + } + + public function testNestedObjectsAreNormalized(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, []); + + self::assertSame( + ['date' => '2024-01-02T00:00:00+00:00'], + $transformer->transform( + (object) ['date' => new \DateTimeImmutable('2024-01-02', new \DateTimeZone('UTC'))], + $options + ) + ); + } + + public function testContextIsPassedToTheNormalizer(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'context' => [AbstractNormalizer::ATTRIBUTES => ['name']], + ]); + + self::assertSame(['name' => 'foo'], $transformer->transform(new class { + public string $name = 'foo'; + public string $secret = 'bar'; + }, $options)); + } + + public function testFormatAndContextArePassedToTheNormalizer(): void + { + $normalizer = new class implements NormalizerInterface { + public function normalize(mixed $data, ?string $format = null, array $context = []): array + { + return ['data' => $data, 'format' => $format, 'context' => $context]; + } + + public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool + { + return true; + } + + public function getSupportedTypes(?string $format): array + { + return ['*' => true]; + } + }; + $transformer = new NormalizeTransformer($normalizer); + $options = $this->resolveOptions($transformer, ['format' => 'json', 'context' => ['foo' => 'bar']]); + + self::assertSame( + ['data' => 'value', 'format' => 'json', 'context' => ['foo' => 'bar']], + $transformer->transform('value', $options) + ); + } + + public function testUnsupportedValueThrows(): void + { + $transformer = new NormalizeTransformer(new Serializer([new DateTimeNormalizer()])); + $options = $this->resolveOptions($transformer, []); + + $this->expectException(NotNormalizableValueException::class); + + $transformer->transform(new \stdClass(), $options); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'format not a string' => [['format' => 1]]; + yield 'context not an array' => [['context' => 'foo']]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsAreRejected(array $options): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions($this->createTransformer(), $options); + } + + private function createTransformer(): NormalizeTransformer + { + return new NormalizeTransformer(new Serializer([new DateTimeNormalizer(), new ObjectNormalizer()])); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(NormalizeTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/String/PregMatchTransformerTest.php b/tests/Transformer/String/PregMatchTransformerTest.php new file mode 100644 index 00000000..19163b23 --- /dev/null +++ b/tests/Transformer/String/PregMatchTransformerTest.php @@ -0,0 +1,130 @@ +, mixed, array}> + */ + public static function transformProvider(): iterable + { + yield 'groups' => [['pattern' => '/(foo)(bar)(baz)/'], 'foobarbaz', ['foobarbaz', 'foo', 'bar', 'baz']]; + yield 'named groups' => [['pattern' => '/(?[a-z]+)-(?\d+)/'], 'abc-12', ['abc-12', 'word' => 'abc', 'abc', 'num' => '12', '12']]; + yield 'no match' => [['pattern' => '/\d+/'], 'abc', []]; + yield 'int input is cast' => [['pattern' => '/^(\d)(\d)$/'], 42, ['42', '4', '2']]; + yield 'zero string is not empty' => [['pattern' => '/\d/'], '0', ['0']]; + yield 'offset capture flag' => [ + ['pattern' => '/(foo)(bar)(baz)/', 'flags' => \PREG_OFFSET_CAPTURE], + 'foobarbaz', + [['foobarbaz', 0], ['foo', 0], ['bar', 3], ['baz', 6]], + ]; + yield 'offset' => [['pattern' => '/\d+/', 'offset' => 3], 'a1b22c333', ['22']]; + yield 'mode_all' => [['pattern' => '/\d+/', 'mode_all' => true], 'a1b22c333', [['1', '22', '333']]]; + yield 'mode_all with groups' => [['pattern' => '/([a-z])(\d+)/', 'mode_all' => true], 'a1b22', [['a1', 'b22'], ['a', 'b'], ['1', '22']]]; + yield 'mode_all without match' => [['pattern' => '/\d+/', 'mode_all' => true], 'abc', [[]]]; + yield 'mode_all with set order flag' => [ + ['pattern' => '/([a-z])(\d+)/', 'mode_all' => true, 'flags' => \PREG_SET_ORDER], + 'a1b22', + [['a1', 'a', '1'], ['b22', 'b', '22']], + ]; + yield 'mode_all with offset' => [['pattern' => '/\d+/', 'mode_all' => true, 'offset' => 3], 'a1b22c333', [['22', '333']]]; + } + + /** + * @param array $options + * @param array $expected + */ + #[DataProvider('transformProvider')] + public function testTransform(array $options, mixed $value, array $expected): void + { + $transformer = new PregMatchTransformer(); + + self::assertSame($expected, $transformer->transform($value, $this->resolveOptions($transformer, $options))); + } + + /** + * @return iterable + */ + public static function emptyValueProvider(): iterable + { + yield 'null' => [null]; + yield 'empty string' => ['']; + } + + #[DataProvider('emptyValueProvider')] + public function testEmptyValueReturnsNull(mixed $value): void + { + $transformer = new PregMatchTransformer(); + $options = $this->resolveOptions($transformer, ['pattern' => '/.*/']); + + self::assertNull($transformer->transform($value, $options)); + self::assertNull($transformer->transform($value, $this->resolveOptions($transformer, ['pattern' => '/.*/', 'mode_all' => true]))); + } + + public function testPatternIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions(new PregMatchTransformer(), []); + } + + /** + * @return iterable}> + */ + public static function invalidOptionsProvider(): iterable + { + yield 'pattern not a string' => [['pattern' => ['/a/']]]; + yield 'flags not an int' => [['pattern' => '/a/', 'flags' => '1']]; + yield 'offset not an int' => [['pattern' => '/a/', 'offset' => '1']]; + yield 'mode_all not a bool' => [['pattern' => '/a/', 'mode_all' => 1]]; + } + + /** + * @param array $options + */ + #[DataProvider('invalidOptionsProvider')] + public function testInvalidOptionsThrow(array $options): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions(new PregMatchTransformer(), $options); + } + + public function testGetCode(): void + { + self::assertSame('preg_match', (new PregMatchTransformer())->getCode()); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(PregMatchTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +} diff --git a/tests/Transformer/UnsetTransformerTest.php b/tests/Transformer/UnsetTransformerTest.php new file mode 100644 index 00000000..7e8621bd --- /dev/null +++ b/tests/Transformer/UnsetTransformerTest.php @@ -0,0 +1,162 @@ + 1, + 'to_unset' => 1, + 'to_test' => 2, + ]; + + public function testGetCode(): void + { + self::assertSame('unset', $this->createTransformer()->getCode()); + } + + public function testSimpleUnset(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property' => 'to_unset']); + + self::assertSame(['other' => 1, 'to_test' => 2], $transformer->transform(self::INPUT, $options)); + } + + /** + * @return iterable, array, bool}> + */ + public static function conditionProvider(): iterable + { + yield 'match met' => [['match' => ['[to_test]' => 2]], self::INPUT, true]; + yield 'match not met' => [['match' => ['[to_test]' => 3]], self::INPUT, false]; + yield 'not_match met' => [['not_match' => ['[to_test]' => 3]], self::INPUT, true]; + yield 'not_match not met' => [['not_match' => ['[to_test]' => 2]], self::INPUT, false]; + yield 'match null not met' => [['match' => ['[to_test]' => null]], self::INPUT, false]; + yield 'match null met' => [['match' => ['[to_test]' => null]], ['to_unset' => 1, 'to_test' => null], true]; + yield 'empty met' => [['empty' => ['[to_test]' => null]], ['to_unset' => 1, 'to_test' => ''], true]; + yield 'empty not met' => [['empty' => ['[to_test]' => null]], self::INPUT, false]; + yield 'not_empty met' => [['not_empty' => ['[to_test]' => null]], self::INPUT, true]; + yield 'match_regexp met' => [['match_regexp' => ['[to_test]' => '/^\d$/']], self::INPUT, true]; + yield 'not_match_regexp not met' => [['not_match_regexp' => ['[to_test]' => '/^\d$/']], self::INPUT, false]; + yield 'all conditions must be met' => [ + ['match' => ['[to_test]' => 2], 'not_empty' => ['[other]' => null], 'empty' => ['[other]' => null]], + self::INPUT, + false, + ]; + } + + /** + * @param array $condition + * @param array $input + */ + #[DataProvider('conditionProvider')] + public function testConditionalUnset(array $condition, array $input, bool $shouldUnset): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property' => 'to_unset', 'condition' => $condition]); + + $result = $transformer->transform($input, $options); + + self::assertSame(!$shouldUnset, \array_key_exists('to_unset', $result)); + unset($input['to_unset']); + self::assertSame($input, array_diff_key($result, ['to_unset' => true])); + } + + public function testNonArrayInputThrows(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property' => 'to_unset']); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Given value must be an array'); + + $transformer->transform('not an array', $options); + } + + public function testMissingPropertyThrows(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, ['property' => 'to_unset']); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Property to_unset does not exists'); + + $transformer->transform(['no property found'], $options); + } + + public function testMissingPropertyThrowsEvenWhenConditionIsNotMet(): void + { + $transformer = $this->createTransformer(); + $options = $this->resolveOptions($transformer, [ + 'property' => 'missing', + 'condition' => ['match' => ['[to_test]' => 'never']], + ]); + + $this->expectException(\UnexpectedValueException::class); + + $transformer->transform(self::INPUT, $options); + } + + public function testPropertyIsRequired(): void + { + $this->expectException(MissingOptionsException::class); + + $this->resolveOptions($this->createTransformer(), []); + } + + public function testPropertyMustBeAString(): void + { + $this->expectException(InvalidOptionsException::class); + + $this->resolveOptions($this->createTransformer(), ['property' => 1]); + } + + public function testUnknownConditionIsRejected(): void + { + $this->expectException(UndefinedOptionsException::class); + + $this->resolveOptions($this->createTransformer(), ['property' => 'a', 'condition' => ['unknown' => []]]); + } + + private function createTransformer(): UnsetTransformer + { + return new UnsetTransformer(PropertyAccess::createPropertyAccessor()); + } + + /** + * @param array $options + * + * @return array + */ + private function resolveOptions(UnsetTransformer $transformer, array $options): array + { + $resolver = new OptionsResolver(); + $transformer->configureOptions($resolver); + + return $resolver->resolve($options); + } +}