diff --git a/CHANGELOG.md b/CHANGELOG.md index 29ff2d87..29a04902 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ Latest * [#292](https://github.com/cleverage/process-bundle/issues/292) Remove the fallbacks of the task registry on the service container, deprecated since 5.4 (#275): the `$container` argument of the `ProcessManager` constructor is removed and its `TaskRegistryInterface $taskRegistry` argument is required, before `$stopCheckers`; `ProcessHelpCommand` only accepts a `TaskRegistryInterface`; `TaskRegistry` only fetches the tasks from its service locator (a task of a process configuration unknown when the container is compiled is not found). The `service` key of the task configurations is removed, use `task: `. The tasks and transformers of the bundle, and the tasks of the application autoconfigured with `TaskInterface`, are private; `PublicTaskDeprecationCompilerPass` is removed (see `UPGRADE.md`). Update documentation and tests. * [#292](https://github.com/cleverage/process-bundle/issues/292) Reject the process configuration errors deprecated during v5: the `errors` task configuration key is removed (use `error_outputs`), with `TaskConfiguration::getErrors()` and `$logErrors`; an unknown `error_strategy` (#310) and an unknown task reference (#426) fail the container compilation; a task listed several times in the `outputs` / `error_outputs` of a task throws an `InvalidProcessConfigurationException` (#414); a shared service used by several tasks of a process fails the container compilation (#382). The former names of the codes with a dash, with underscores, are no longer found (#412, #475): processes, tasks, generic transformers, transformer codes and contextual options of the generic transformers; `DeprecatedCodeAliases` and the second argument of the `TransformerRegistry` constructor are removed (see `UPGRADE.md`). Update documentation and tests. * [#292](https://github.com/cleverage/process-bundle/issues/292) Remove the classes, methods and options deprecated during v5: `ProcessState::getReturnCode()` / `setReturnCode()` (#503), the `cleverage_process.event_listener.data_queue` service and `DataQueueEventListener` (#311), `CheckSerializerCompilerPass`, the `KernelInterface` argument and the `$kernel` / `$logDir` properties of `CommandRunnerTask`, `ProcessLauncherTask` and `SubprocessInstance` (#318), the `process_options` option of the `process_launcher` task (see `UPGRADE.md`). Update documentation and tests. +* [#292](https://github.com/cleverage/process-bundle/issues/292) Apply the behaviours announced by the deprecations of v5: an exception thrown by the `initialize()` of a task makes the process fail before any task is executed, with a `ProcessFailedException` (#222); the `event_dispatcher` task no longer dispatches its event under the class name of the event too when `event_name` is set (#189); a target property of an array destination that is neither a simple property name nor an index notation (`address.city`) throws an `UnexpectedValueException` in the `mapping` transformer (#117); the `additional_parameters` option of the `callback` transformer is removed, use `right_parameters`; a negative `flush_every` of the `counter` task is rejected (#491) (see `UPGRADE.md`). Update documentation and tests. ## Changes * [#428](https://github.com/cleverage/process-bundle/issues/428) Tests on PHPUnit 12.5 and 13 (PHPUnit 10 and 11 dropped), with the lowest dependencies on PHP 8.3 and 8.5. diff --git a/UPGRADE.md b/UPGRADE.md index d5c4b798..208efca6 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -179,6 +179,24 @@ The former names of the codes with a dash, with underscores instead of dashes, a - the `process_options` option of the `process_launcher` task is removed (deprecated, a non-empty value already threw): remove it from your process configurations, an `UndefinedOptionsException` is thrown otherwise. +### Behaviours announced by the deprecations + +- an exception thrown by the `initialize()` method of a task (e.g. options that cannot be resolved) makes the process + fail before any task is executed, with a `ProcessFailedException` whose previous exception is the one thrown (it was + logged, deprecated since 5.1, and the process only failed when the task was first executed, or ended normally when it + was never reached): fix the configuration of the task; +- the `event_dispatcher` task with an `event_name` no longer dispatches its event under the + `CleverAge\ProcessBundle\Event\EventDispatcherTaskEvent` class name too (deprecated since 5.1): its listeners must + listen to the `event_name`; +- in the `mapping` transformer, a target property of an array destination that is neither a simple property name nor + an index notation (e.g. `address.city`, `address[city]`) throws an `UnexpectedValueException` (it was set as a + literal key, deprecated since 5.2): write `[address.city]` to keep the literal key, or `[address][city]` for a nested + array; +- the `additional_parameters` option of the `callback` transformer is removed (deprecated since 2.0.4): rename it + `right_parameters`, an `UndefinedOptionsException` is thrown otherwise; +- a negative `flush_every` option of the `counter` task is rejected with an `InvalidOptionsException` (it worked as + its absolute value, deprecated since 5.10): use a positive integer. + ## v5.10 ### Stop strategy and error branch ending on a stop diff --git a/docs/02-task_types.md b/docs/02-task_types.md index 090ed5e4..7a97e699 100644 --- a/docs/02-task_types.md +++ b/docs/02-task_types.md @@ -121,14 +121,11 @@ and prepare anything needed for the main execution of the task. All tasks of a p they are configured, before any execution. This is especially useful (for example) when the process starts with heavy tasks before actually uploading a file, to -detect a problem early. Note however that an exception thrown by `initialize` does not abort the process: it is logged -(`critical` level, on the `cleverage_process_task` channel) and the task state is flagged as stopped, then the process -goes on. The failure only surfaces when the task is first reached: for [configurable tasks](#configurable-tasks-and-options), -the options are resolved again and the process fails at that point (upstream tasks may already have run); for other -tasks, the branch stops after this first execution. If the task is never reached, the process ends normally. - -This behaviour is deprecated since 5.1 (an `E_USER_DEPRECATED` error is triggered for each initialization failure): in -v6.0, an initialization failure will make the process fail before any task is executed. +detect a problem early. An exception thrown by `initialize` is logged (`critical` level, on the +`cleverage_process_task` channel) and makes the process fail before any task is executed, with a +`ProcessFailedException` (its previous exception is the one thrown by `initialize`), even when the task would never be +reached. Before v6.0, the process went on: it only failed when the task was first executed. A task whose `initialize` +has failed is not finalized: release what it has already opened (file, connection...) before throwing. ## Configurable tasks and options @@ -138,9 +135,8 @@ behavior. Options are a way to configure a task. Configurable tasks extend `CleverAge\ProcessBundle\Model\AbstractConfigurableTask`. It is an initializable task that relies on [Symfony's OptionsResolver Component](https://symfony.com/doc/current/components/options_resolver.html): - you define the options in the abstract `configureOptions(OptionsResolver $resolver)` method -- options are resolved (and validated) during `initialize`, so a misconfigured task is logged as critical before any - execution; the process itself only fails when the task is first executed (see - [initializable tasks](#initializable-tasks)) +- options are resolved (and validated) during `initialize`, so a misconfigured task makes the process fail before any + execution (see [initializable tasks](#initializable-tasks)) - the options are read from the task `options` configuration, after replacing the `{{ key }}` placeholders with the process context values (see [contextual values](01-quick_start.md#contextual-values)) - in `execute`, use `$this->getOptions($state)` or `$this->getOption($state, 'code')` to read the resolved options diff --git a/docs/03-custom_tasks.md b/docs/03-custom_tasks.md index 916f7d85..556bc4ef 100644 --- a/docs/03-custom_tasks.md +++ b/docs/03-custom_tasks.md @@ -146,10 +146,8 @@ Based on [Symfony's OptionsResolver Component](https://symfony.com/doc/current/c abstract class allows you to implement its `configureOptions` method to add your requirements, default values and normalizers. Options are resolved (once) during the task initialization, and can be read with `getOptions($state)` or `getOption($state, $code)`. If you override `getOptions()`, it must return an `array` (it was typed `?array` before -v6.0). If the resolution fails during initialization, the error is logged and the options are resolved again (failing -the process) when the task is first executed. Going on with the process after an initialization failure is deprecated -since 5.1: in v6.0, the process will fail before any task is executed (see -[initializable tasks](02-task_types.md#initializable-tasks)). +v6.0). If the resolution fails during initialization, the error is logged and the process fails before any task is +executed (see [initializable tasks](02-task_types.md#initializable-tasks)). ```php namespace App\Task; diff --git a/docs/04-advanced_workflow.md b/docs/04-advanced_workflow.md index d796c9a7..a98033f2 100644 --- a/docs/04-advanced_workflow.md +++ b/docs/04-advanced_workflow.md @@ -11,9 +11,9 @@ When a process is executed (with the `cleverage:process:execute` command or with the *main branch*, the group of connected tasks that is actually executed (see [orphan tasks](#orphan-tasks)) 3. **initializes** every task, in the order they are configured: the service is fetched from the task registry and `initialize` is called on [initializable tasks](02-task_types.md#initializable-tasks) (for configurable tasks, this is - where options are validated). An exception thrown by `initialize` is logged as critical and flags the task as - stopped, but does not abort the process: it only fails when this task is first executed. This is deprecated since 5.1 - (an `E_USER_DEPRECATED` error is triggered): in v6.0, the process will fail at this step, before any task is executed + where options are validated). An exception thrown by `initialize` is logged as critical and makes the process fail + at this step, before any task is executed (with a `ProcessFailedException`); the tasks already initialized are + finalized (see [finalizable tasks](02-task_types.md#finalizable-tasks)) 4. gives the process input to the `entry_point` task, if one is defined (otherwise the input is ignored and a warning is logged) 5. **resolves** the tasks of the main branch (see below) @@ -112,7 +112,7 @@ Only one group of connected tasks, the *main branch*, is executed. It is the gro or the `end_point` task if there is no entry point, or else the first configured task. Tasks that are not connected to it (not referenced in any `outputs` or `error_outputs` of the main branch) are never executed: a warning `Task '' is unreachable` is logged for each of them. They are still initialized and finalized, like every task of -the process (so a misconfigured orphan task still logs its initialization error). The `cleverage:process:help` command +the process (so a misconfigured orphan task makes the process fail at the initialization). The `cleverage:process:help` command only displays the main branch. ### Errors and skips diff --git a/docs/reference/tasks/counter_task.md b/docs/reference/tasks/counter_task.md index 0c3485b4..aa082ba7 100644 --- a/docs/reference/tasks/counter_task.md +++ b/docs/reference/tasks/counter_task.md @@ -56,5 +56,5 @@ Notes [Advanced workflow](../../04-advanced_workflow.md)), e.g. once at the end of the upstream iteration and once when the counter itself is resolved. The final count is only outputted by the first call; the next ones are skipped. * `flush_every: 0` is rejected when the options are resolved (`InvalidOptionsException`) since 5.10: it failed on the - first execution (`Modulo by zero`). A negative value works as its absolute value (`-3` as `3`): it is deprecated since - 5.10 and will be rejected in v6.0. + first execution (`Modulo by zero`). A negative value is rejected the same way since v6.0: it worked as its absolute + value (`-3` as `3`), deprecated since 5.10. diff --git a/docs/reference/tasks/event_dispatcher_task.md b/docs/reference/tasks/event_dispatcher_task.md index 5977ade9..1d5b70ff 100644 --- a/docs/reference/tasks/event_dispatcher_task.md +++ b/docs/reference/tasks/event_dispatcher_task.md @@ -67,8 +67,7 @@ public function onDataQueue(EventDispatcherTaskEvent $event): void `CleverAge\ProcessBundle\Event\EventDispatcherTaskEvent`. Every `EventDispatcherTask` without `event_name` then triggers the same listeners. -**Deprecated since 5.1 (deprecation notice), removed in v6.0**: from v4.0 to v5.0, the `event_name` option was ignored and the event was -always dispatched under its class name. To preserve backward compatibility, when `event_name` is set (and differs from the -event class name) and listeners subscribe to `CleverAge\ProcessBundle\Event\EventDispatcherTaskEvent`, the event is also -dispatched under its class name and an `E_USER_DEPRECATED` error is triggered. In v6.0, listen to the configured +Since v6.0, an event dispatched under its `event_name` is no longer dispatched under its class name too: the listeners +of `CleverAge\ProcessBundle\Event\EventDispatcherTaskEvent` are only called by the tasks without `event_name`. From +v4.0 to v5.x, they were also called (deprecated since 5.1) when `event_name` was set: listen to the configured `event_name` instead, or remove the `event_name` option. diff --git a/docs/reference/tasks/folder_browser_task.md b/docs/reference/tasks/folder_browser_task.md index 3b12b6ef..46f20d3c 100644 --- a/docs/reference/tasks/folder_browser_task.md +++ b/docs/reference/tasks/folder_browser_task.md @@ -30,7 +30,7 @@ Options | Code | Type | Required | Default | Description | |-------------------|-----------------------|:--------:|-----------|----------------------------------------------------------------------------------------------------------------| -| `folder_path` | `string` | **X** | | Path of the folder to browse. Must be an existing readable directory (checked at initialization; with process-bundle v5, the process fails when the task is first executed, see [initializable tasks](../../02-task_types.md#initializable-tasks)) | +| `folder_path` | `string` | **X** | | Path of the folder to browse. Must be an existing readable directory (checked at initialization: the process fails before any task is executed, see [initializable tasks](../../02-task_types.md#initializable-tasks)) | | `name_pattern` | `string\|array\|null` | | `null` | Restrict files by name using a pattern (glob, regexp or string) or an array of patterns (see `Finder::name()`) | | `empty_log_level` | `string` | | `warning` | Log level used when no file is found, one of the `Psr\Log\LogLevel` constants | diff --git a/docs/reference/tasks/process_executor_task.md b/docs/reference/tasks/process_executor_task.md index 9642b1cd..15ee1098 100644 --- a/docs/reference/tasks/process_executor_task.md +++ b/docs/reference/tasks/process_executor_task.md @@ -52,7 +52,7 @@ Notes `stop` (default), the parent process fails too; with `skip`, the parent process goes on with the next input (the input is sent to the `error_outputs` of the task, if any). * The `process` option is checked when the task is initialized: with an unknown process, the initialization fails, the - error is logged and, with process-bundle v5, the parent process fails when the task is first executed (see + error is logged and the parent process fails before any of its tasks is executed (see [initializable tasks](../../02-task_types.md#initializable-tasks)). * Executing a process while it is already running, by itself or through its sub-processes (`A → B → A`), is deprecated since 5.6 and will throw an exception in 6.0: a process has only one set of task instances and states, diff --git a/docs/reference/tasks/stop_task.md b/docs/reference/tasks/stop_task.md index c9dad113..a05b75c5 100644 --- a/docs/reference/tasks/stop_task.md +++ b/docs/reference/tasks/stop_task.md @@ -13,12 +13,9 @@ file does not exist. Unlike [DieTask](die_task.md), the stop is handled by the p * `cleverage:process:execute` exits with code 0, and the task running a sub-process ([ProcessExecutorTask](process_executor_task.md)) goes on. -A process that has already failed (e.g. a task whose initialization failed, see the -[initializable tasks](../../02-task_types.md)) stays **failed**: the `StopTask` still stops the flow of the -tasks, but it does not turn the failure into a stop. - -To stop a process because of an error, let the error fail the process instead (error strategy `stop`). A `StopTask` in -the error branch of a task with the `stop` strategy does not turn its failure into a stop: the process fails. +To stop a process because of an error, let the error fail the process instead (error strategy `stop`). A process that +has already failed stays **failed**: a `StopTask` in the error branch of a task with the `stop` strategy still stops the +flow of the tasks, but it does not turn the failure into a stop. Task reference -------------- diff --git a/docs/reference/tasks/yaml_reader_task.md b/docs/reference/tasks/yaml_reader_task.md index 40bf778a..1ff5f131 100644 --- a/docs/reference/tasks/yaml_reader_task.md +++ b/docs/reference/tasks/yaml_reader_task.md @@ -26,7 +26,7 @@ Options | Code | Type | Required | Default | Description | |-------------|----------|:--------:|---------|----------------------------------------------------------------------------------------------------------------------| -| `file_path` | `string` | **X** | | Path of the YAML file to read. An `UnexpectedValueException` is thrown at initialization if the file does not exist (with process-bundle v5, the process fails when the task is first executed, see [initializable tasks](../../02-task_types.md#initializable-tasks)) | +| `file_path` | `string` | **X** | | Path of the YAML file to read. An `UnexpectedValueException` is thrown at initialization if the file does not exist (the process fails before any task is executed, see [initializable tasks](../../02-task_types.md#initializable-tasks)) | Examples -------- diff --git a/docs/reference/transformers/callback_transformer.md b/docs/reference/transformers/callback_transformer.md index e0ab08b2..82d4ba77 100644 --- a/docs/reference/transformers/callback_transformer.md +++ b/docs/reference/transformers/callback_transformer.md @@ -28,7 +28,6 @@ Options | `callback` | `string\|array` | **X** | | A valid PHP callable (e.g. `mb_strtoupper`, `['App\MyClass', 'myStaticMethod']`), checked with `is_callable` | | `left_parameters` | `array` | | `[]` | Parameters passed before the value | | `right_parameters` | `array` | | `[]` | Parameters passed after the value | -| `additional_parameters` | `array` | | `[]` | **Deprecated**: use `right_parameters` instead. Only used when `right_parameters` is empty | Examples -------- diff --git a/docs/reference/transformers/mapping_transformer.md b/docs/reference/transformers/mapping_transformer.md index 36228b35..40e121b1 100644 --- a/docs/reference/transformers/mapping_transformer.md +++ b/docs/reference/transformers/mapping_transformer.md @@ -141,10 +141,10 @@ Notes `NoSuchPropertyException` is thrown (`Cannot read the property "[name]" of a value of type "null": the input must be an array or an object.`). * When a sub-transformer fails, the thrown `TransformerException` reports the target property. -* On an array destination, a target property that is not an index notation is added as a literal key: a simple - property name (e.g. `name`) gives the `name` key. Doing so with a nested path (e.g. `address.city`, `address[city]`) - is deprecated and will throw an `UnexpectedValueException` in v6.0: use `[address.city]` to keep a literal key, or - `[address][city]` to write in a nested array. +* On an array destination, a simple target property name (e.g. `name`) is added as the `name` key. Another target + property that is not an index notation (a nested path, e.g. `address.city`, `address[city]`) throws an + `UnexpectedValueException` since v6.0 (it was added as a literal key, deprecated since 5.2): use `[address.city]` to + keep a literal key, or `[address][city]` to write in a nested array. * A missing property of a `\stdClass` destination is added only for a simple target property name (e.g. `name`): a nested path (e.g. `address.city`) or an index notation (e.g. `[name]`) that is not writable throws an `UnexpectedValueException` (`Property '...' is not writable`), as for any other object. diff --git a/src/Exception/ProcessFailedException.php b/src/Exception/ProcessFailedException.php index 09ec8df7..aa193882 100644 --- a/src/Exception/ProcessFailedException.php +++ b/src/Exception/ProcessFailedException.php @@ -14,7 +14,7 @@ namespace CleverAge\ProcessBundle\Exception; /** - * Thrown when a process is stopped by a task error (error strategy "stop"). + * Thrown when a process is stopped by a task error (error strategy "stop"), or by the initialization failure of a task. * * The original exception is available with getPrevious(). */ diff --git a/src/Manager/ProcessManager.php b/src/Manager/ProcessManager.php index 95b10b38..9afa6997 100644 --- a/src/Manager/ProcessManager.php +++ b/src/Manager/ProcessManager.php @@ -106,14 +106,6 @@ class ProcessManager implements ProcessManagerInterface, ResetInterface */ protected ?\WeakMap $loggedStates = null; - /** - * Tasks whose initialization has failed (deprecated since 5.1), indexed by task configuration (spl_object_id()): - * they stay stopped. - * - * @var array - */ - protected array $failedInitializations = []; - protected ?ProcessHistory $processHistory = null; protected ?TaskConfiguration $taskConfiguration = null; @@ -148,7 +140,6 @@ public function reset(): void $this->locks = []; $this->endPointOutputs = new \WeakMap(); $this->loggedStates = null; - $this->failedInitializations = []; $this->processHistory = null; $this->taskConfiguration = null; } @@ -261,13 +252,11 @@ protected function doExecute(string $processCode, mixed $input = null, array $co try { $this->checkProcess($processConfiguration); - // First initialize the whole stack in a linear way, tasks are initialized in the order they are configured + // First initialize the whole stack in a linear way, tasks are initialized in the order they are configured. + // An initialization failure makes the process fail before any task is executed: the task is not finalized foreach ($processConfiguration->getTaskConfigurations() as $taskConfiguration) { $this->initialize($taskConfiguration); - // A task whose initialization has failed is stopped: it is not finalized if the process fails - if (!$taskConfiguration->getState()->isStopped()) { - $tasksToFinalize[spl_object_id($taskConfiguration)] = $taskConfiguration; - } + $tasksToFinalize[spl_object_id($taskConfiguration)] = $taskConfiguration; } // If defined, set the input of a task @@ -299,7 +288,7 @@ protected function doExecute(string $processCode, mixed $input = null, array $co // Never finalized twice, even if the process fails after this point unset($tasksToFinalize[spl_object_id($taskConfiguration)]); $state = $taskConfiguration->getState(); - // Already failed (initialization failure of a task never reached): not a finalization failure + // Already failed (e.g. a task whose error branch has stopped the process): not a finalization failure $failedBefore = $state->isStopped() && $state->getException() instanceof \Throwable; $this->finalize($taskConfiguration); if (!$failedBefore && !$finalizationError instanceof \Throwable @@ -343,7 +332,6 @@ protected function doExecute(string $processCode, mixed $input = null, array $co foreach ($processConfiguration->getTaskConfigurations() as $taskConfiguration) { $this->removeProcessedIterable($taskConfiguration); $this->removeProcessedBlocking($taskConfiguration); - unset($this->failedInitializations[spl_object_id($taskConfiguration)]); } } @@ -418,16 +406,11 @@ protected function initialize(TaskConfiguration $taskConfiguration): void ]; $this->taskLogger->critical($e->getMessage(), $logContext); $state->stop($e); - $this->failedInitializations[spl_object_id($taskConfiguration)] = $taskConfiguration; - // @deprecated since 5.1, in v6.0 the process will fail right away, before any task is executed - trigger_deprecation( - 'cleverage/process-bundle', - '5.1', - 'The initialization of the task "%s" of the process "%s" has failed with message "%s". Going on with the process after an initialization failure is deprecated: in v6.0, the process will fail before executing any task.', - $taskConfiguration->getCode(), - $state->getProcessConfiguration()->getCode(), - $e->getMessage(), - ); + $this->handleState($state); + + // The process fails before any task is executed. The failing task is kept for the logs of the + // failure, execute() restores the task of the parent process + throw ProcessFailedException::create($state->getProcessConfiguration()->getCode(), $taskConfiguration->getCode(), $e); } } $this->handleState($taskConfiguration->getState()); @@ -544,13 +527,9 @@ protected function processExecution(TaskConfiguration $taskConfiguration, int $e $state = $taskConfiguration->getState(); // A stop only stops the flow it happened in: a later execution of the task (from another root task, by a - // blocking task proceeded or a flushable task flushed after the stop...) goes on. Except for a task whose - // initialization has failed (deprecated), and for an iterable task, whose iteration has been interrupted (it - // would resume it) - if ($state->isStopped() - && !$task instanceof IterableTaskInterface - && !isset($this->failedInitializations[spl_object_id($taskConfiguration)]) - ) { + // blocking task proceeded or a flushable task flushed after the stop...) goes on. Except for an iterable task, + // whose iteration has been interrupted (it would resume it) + if ($state->isStopped() && !$task instanceof IterableTaskInterface) { $state->setStopped(false); } diff --git a/src/Task/CounterTask.php b/src/Task/CounterTask.php index cc6e709c..aa6979ba 100644 --- a/src/Task/CounterTask.php +++ b/src/Task/CounterTask.php @@ -67,19 +67,8 @@ protected function configureOptions(OptionsResolver $resolver): void $resolver->setRequired(['flush_every']); $resolver->setAllowedTypes('flush_every', ['int']); $resolver->setNormalizer('flush_every', static function (Options $options, int $value): int { - // Modulo by zero - if (0 === $value) { - throw new InvalidOptionsException('The option "flush_every" of the counter task must be a positive integer (the count is output every "flush_every" executions), 0 given.'); - } - // Works as its absolute value (sign of the modulo) - if ($value < 0) { - trigger_deprecation( - 'cleverage/process-bundle', - '5.10', - 'A negative "flush_every" option of the counter task (%d) is deprecated, it works as %d: use a positive integer. It will be rejected in v6.0.', - $value, - -$value, - ); + if ($value <= 0) { + throw new InvalidOptionsException(\sprintf('The option "flush_every" of the counter task must be a positive integer (the count is output every "flush_every" executions), %d given.', $value)); } return $value; diff --git a/src/Task/Event/EventDispatcherTask.php b/src/Task/Event/EventDispatcherTask.php index a259e28f..5b1acb4f 100644 --- a/src/Task/Event/EventDispatcherTask.php +++ b/src/Task/Event/EventDispatcherTask.php @@ -42,22 +42,6 @@ public function execute(ProcessState $state): void $event = new EventDispatcherTaskEvent($state); $this->eventDispatcher->dispatch($event, $options['event_name']); - - // @deprecated BC layer since 5.1, remove me in v6.0: from v4.0 to v5.0, the event was only dispatched under its - // class name, even when event_name was set - if (null !== $options['event_name'] - && EventDispatcherTaskEvent::class !== $options['event_name'] - && $this->eventDispatcher->hasListeners(EventDispatcherTaskEvent::class) - ) { - trigger_deprecation( - 'cleverage/process-bundle', - '5.1', - 'Listening to "%s" for an EventDispatcherTask with the "event_name" option set is deprecated and will not work anymore in v6.0, listen to "%s" instead.', - EventDispatcherTaskEvent::class, - $options['event_name'], - ); - $this->eventDispatcher->dispatch($event); - } } protected function configureOptions(OptionsResolver $resolver): void diff --git a/src/Transformer/CallbackTransformer.php b/src/Transformer/CallbackTransformer.php index 6b397a5e..69b12f16 100644 --- a/src/Transformer/CallbackTransformer.php +++ b/src/Transformer/CallbackTransformer.php @@ -24,9 +24,6 @@ */ class CallbackTransformer implements ConfigurableTransformerInterface { - /** Whether the deprecation of "additional_parameters" has been triggered: once */ - private static bool $additionalParametersDeprecated = false; - /** * Must return the transformed $value. * @@ -34,11 +31,6 @@ class CallbackTransformer implements ConfigurableTransformerInterface */ public function transform(mixed $value, array $options = []): mixed { - if ((is_countable($options['additional_parameters']) ? \count($options['additional_parameters']) : 0) - && !(is_countable($options['right_parameters']) ? \count($options['right_parameters']) : 0)) { - $options['right_parameters'] = $options['additional_parameters']; - } - $parameters = $options['left_parameters']; array_push($parameters, $value, ...$options['right_parameters']); @@ -63,29 +55,10 @@ static function (Options $options, $value): callable { [ 'left_parameters' => [], 'right_parameters' => [], - 'additional_parameters' => [], ] ); $resolver->setAllowedTypes('left_parameters', ['array']); $resolver->setAllowedTypes('right_parameters', ['array']); - $resolver->setAllowedTypes('additional_parameters', ['array']); - - $resolver->setNormalizer( - 'additional_parameters', - static function (Options $options, $value) { - // Once: it was triggered each time the options were resolved - if ($value && !self::$additionalParametersDeprecated) { - self::$additionalParametersDeprecated = true; - trigger_deprecation( - 'cleverage/process-bundle', - '2.0.4', - 'The "additional_parameters" option is deprecated. Use "right_parameters" instead.' - ); - } - - return $value; - } - ); } private static function describe(mixed $value): string diff --git a/src/Transformer/MappingTransformer.php b/src/Transformer/MappingTransformer.php index c455d101..1a0df746 100644 --- a/src/Transformer/MappingTransformer.php +++ b/src/Transformer/MappingTransformer.php @@ -33,14 +33,6 @@ class MappingTransformer implements ConfigurableTransformerInterface { use TransformerTrait; - /** - * The target properties whose deprecation (literal key of an array destination) has been triggered: once per - * target property. - * - * @var array - */ - private static array $deprecatedLiteralKeys = []; - public function __construct( TransformerRegistry $transformerRegistry, protected LoggerInterface $logger, @@ -125,19 +117,10 @@ public function transform(mixed $value, array $options = []): mixed $options['merge_callback']($result, $targetProperty, $transformedValue); } elseif ($this->accessor->isWritable($result, $targetProperty)) { $this->accessor->setValue($result, $targetProperty, $transformedValue); - } elseif (\is_array($result)) { - // Once per target property: it was triggered for each transformed item - if (!$this->isSimplePropertyName($targetProperty) && !isset(self::$deprecatedLiteralKeys[$targetProperty])) { - self::$deprecatedLiteralKeys[$targetProperty] = true; - trigger_deprecation( - 'cleverage/process-bundle', - '5.2', - "Setting the target property '%s' as a literal key of an array destination is deprecated, it will throw an \\UnexpectedValueException in v6.0. Use '[%s]' to keep a literal key, or the index notation for nested arrays (e.g. '[a][b]').", - $targetProperty, - $targetProperty - ); - } + } elseif (\is_array($result) && $this->isSimplePropertyName($targetProperty)) { $result[$targetProperty] = $transformedValue; + } elseif (\is_array($result)) { + throw new UnexpectedValueException("The target property '{$targetProperty}' cannot be set in an array destination: use '[{$targetProperty}]' for a literal key, or the index notation for nested arrays (e.g. '[a][b]')."); } elseif ($result instanceof \stdClass && $this->isSimplePropertyName($targetProperty)) { // Only a simple property name can be added to a \stdClass, nested paths are not created $result->{$targetProperty} = $transformedValue; diff --git a/tests/Manager/ProcessManagerFinalizationTest.php b/tests/Manager/ProcessManagerFinalizationTest.php index 32fe2fd4..805e5849 100644 --- a/tests/Manager/ProcessManagerFinalizationTest.php +++ b/tests/Manager/ProcessManagerFinalizationTest.php @@ -166,18 +166,16 @@ public function testTheTasksAreFinalizedWhenTheProcessFails(): void public function testATaskWhoseInitializationHasFailedIsNotFinalizedWhenTheProcessFails(): void { - set_error_handler(static fn (): bool => true, \E_USER_DEPRECATED); - try { - $error = $this->executeFailing([ - 'first' => $this->createTaskConfiguration('@test.finalizable_first', ['bad_init']), - 'bad_init' => $this->createTaskConfiguration('@test.finalizable_bad_init'), - ]); - } finally { - restore_error_handler(); - } + $error = $this->executeFailing([ + 'first' => $this->createTaskConfiguration('@test.finalizable_first', ['bad_init', 'second']), + 'bad_init' => $this->createTaskConfiguration('@test.finalizable_bad_init'), + // Not initialized: the process fails before + 'second' => $this->createTaskConfiguration('@test.finalizable_second'), + ]); self::assertInstanceOf(ProcessFailedException::class, $error); self::assertSame('Invalid configuration', $error->getPrevious()?->getMessage()); + // Initialized before the failure, never executed self::assertSame(['first (first)'], $this->finalized); } diff --git a/tests/Manager/ProcessManagerFlowTest.php b/tests/Manager/ProcessManagerFlowTest.php index b9d77e97..d8f8653b 100644 --- a/tests/Manager/ProcessManagerFlowTest.php +++ b/tests/Manager/ProcessManagerFlowTest.php @@ -226,22 +226,22 @@ public function testAnIterableTaskInterruptedByAStopStaysStopped(): void } /** - * A task whose initialization has failed (deprecated) stays stopped: none of its executions goes on. + * The initialization failure of a task makes the process fail before any task is executed. */ - public function testATaskWhoseInitializationHasFailedStaysStopped(): void + public function testAnInitializationFailureMakesTheProcessFailBeforeAnyExecution(): void { - set_error_handler(static fn (): bool => true, \E_USER_DEPRECATED); try { $this->execute([ 'items' => ['type' => 'iterable', 'items' => [1, 2], 'outputs' => ['bad']], 'bad' => ['type' => 'failed_initialization', 'outputs' => ['after']], 'after' => [], ]); - } finally { - restore_error_handler(); + self::fail('No exception thrown'); + } catch (ProcessFailedException $exception) { + self::assertSame('Invalid configuration', $exception->getPrevious()?->getMessage()); } - self::assertSame(['bad:execute:1'], $this->getExecutions()); + self::assertSame([], $this->getExecutions()); } /** diff --git a/tests/Manager/ProcessManagerInitializationTest.php b/tests/Manager/ProcessManagerInitializationTest.php index c81f56e9..e1c3da8e 100644 --- a/tests/Manager/ProcessManagerInitializationTest.php +++ b/tests/Manager/ProcessManagerInitializationTest.php @@ -28,15 +28,13 @@ use CleverAge\ProcessBundle\Model\TaskInterface; use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry; use CleverAge\ProcessBundle\Registry\TaskRegistry; -use CleverAge\ProcessBundle\Task\StopTask; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\EventDispatcher\EventDispatcher; /** - * An exception thrown by initialize() does not abort the process (deprecated since v5, the process will fail before - * executing any task in v6.0). + * An exception thrown by initialize() makes the process fail before any task is executed. */ #[\PHPUnit\Framework\Attributes\CoversClass(ProcessManager::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessConfiguration::class)] @@ -49,95 +47,78 @@ #[\PHPUnit\Framework\Attributes\UsesClass(ProcessHistory::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessState::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessConfigurationRegistry::class)] -#[\PHPUnit\Framework\Attributes\UsesClass(StopTask::class)] class ProcessManagerInitializationTest extends TestCase { /** @var list */ private array $executedTasks = []; + /** @var list */ + private array $failedTasks = []; + /** @var list */ - private array $endedEvents = []; + private array $failedEvents = []; - /** @var list */ - private array $deprecations = []; + /** @var list */ + private array $endedEvents = []; - public function testInitializationFailureIsDeprecatedAndUpstreamTasksStillRun(): void + public function testInitializationFailureMakesTheProcessFailBeforeAnyTaskIsExecuted(): void { - $processManager = $this->createProcessManager(skipBeforeBadTask: false); + $processManager = $this->createProcessManager(); $exception = null; try { - $this->execute($processManager); + $processManager->execute('test.process'); } catch (\Throwable $exception) { } - self::assertInstanceOf(ProcessFailedException::class, $exception, 'The process should fail when reaching the badly initialized task'); - self::assertStringContainsString('Invalid configuration', $exception->getMessage()); - self::assertSame(['entry', 'bad'], $this->executedTasks); - self::assertSame([$this->getExpectedDeprecation()], $this->deprecations); + self::assertInstanceOf(ProcessFailedException::class, $exception); + self::assertSame('Invalid configuration', $exception->getPrevious()?->getMessage()); + self::assertStringContainsString('test.process', $exception->getMessage()); + self::assertStringContainsString('bad', $exception->getMessage()); + self::assertSame([], $this->executedTasks, 'No task is executed, not even the ones before the failing task'); + self::assertCount(1, $this->failedEvents); + self::assertSame($exception, $this->failedEvents[0]->getProcessError()); + // The logs of the failure are attributed to the task whose initialization has failed + self::assertSame(['bad'], $this->failedTasks); + self::assertSame([], $this->endedEvents); + self::assertNull($processManager->getTaskConfiguration()); } - public function testInitializationFailureOfAnUnreachedTaskIsDeprecated(): void + public function testTheProcessCanBeExecutedAgainAfterAnInitializationFailure(): void { - $processManager = $this->createProcessManager(skipBeforeBadTask: true); - - $this->execute($processManager); - - self::assertSame(['entry'], $this->executedTasks); - self::assertSame([$this->getExpectedDeprecation()], $this->deprecations); + $processManager = $this->createProcessManager(); + + for ($i = 0; $i < 2; ++$i) { + try { + $processManager->execute('test.process'); + self::fail('No exception thrown'); + } catch (ProcessFailedException $exception) { + self::assertSame('Invalid configuration', $exception->getPrevious()?->getMessage()); + } + } + self::assertSame([], $this->executedTasks); } - public function testNoDeprecationWithoutInitializationFailure(): void + public function testTheTasksAreExecutedWithoutInitializationFailure(): void { - $processManager = $this->createProcessManager(skipBeforeBadTask: false, failInitialization: false); + $processManager = $this->createProcessManager(failInitialization: false); - $this->execute($processManager); + $processManager->execute('test.process'); self::assertSame(['entry', 'bad'], $this->executedTasks); - self::assertSame([], $this->deprecations); - } - - public function testStopTaskDoesNotTurnAFailedProcessIntoAStoppedOne(): void - { - $processManager = $this->createProcessManager(skipBeforeBadTask: false, withStopTask: true); - - $this->execute($processManager); - - self::assertSame(['entry'], $this->executedTasks, 'The stop signal still prevents the next tasks from running'); - self::assertSame([$this->getExpectedDeprecation()], $this->deprecations); + self::assertSame([], $this->failedEvents); self::assertCount(1, $this->endedEvents); - self::assertFalse($this->endedEvents[0]->isProcessStopped(), 'The failed process must not be flagged as stopped'); - } - - private function getExpectedDeprecation(): string - { - return 'Since cleverage/process-bundle 5.1: The initialization of the task "bad" of the process "test.process" has failed with message "Invalid configuration". Going on with the process after an initialization failure is deprecated: in v6.0, the process will fail before executing any task.'; - } - - private function execute(ProcessManager $processManager): void - { - set_error_handler(function (int $errno, string $errstr): bool { - $this->deprecations[] = $errstr; - - return true; - }, \E_USER_DEPRECATED); - try { - $processManager->execute('test.process'); - } finally { - restore_error_handler(); - } } - private function createProcessManager(bool $skipBeforeBadTask, bool $failInitialization = true, bool $withStopTask = false): ProcessManager + private function createProcessManager(bool $failInitialization = true): ProcessManager { $recorder = function (string $taskCode): void { $this->executedTasks[] = $taskCode; }; - $entryTask = new readonly class($recorder, $skipBeforeBadTask) implements TaskInterface { + $entryTask = new readonly class($recorder) implements TaskInterface { public function __construct( private \Closure $recorder, - private bool $skip, ) { } @@ -145,7 +126,6 @@ public function execute(ProcessState $state): void { ($this->recorder)('entry'); $state->setOutput('value'); - $state->setSkipped($this->skip); } }; @@ -163,9 +143,6 @@ public function initialize(ProcessState $state): void } } - /** - * Like configurable tasks (options are resolved again), fail again when executed. - */ public function execute(ProcessState $state): void { ($this->recorder)('bad'); @@ -176,7 +153,6 @@ public function execute(ProcessState $state): void $container = new Container(); $container->set('test.entry', $entryTask); $container->set('test.bad', $badTask); - $container->set('test.stop', new StopTask()); $registry = new ProcessConfigurationRegistry( [ @@ -188,9 +164,8 @@ public function execute(ProcessState $state): void 'help' => '', 'public' => true, 'tasks' => [ - 'entry' => $this->createTaskConfiguration('@test.entry', $withStopTask ? ['stop', 'bad'] : ['bad']), + 'entry' => $this->createTaskConfiguration('@test.entry', ['bad']), 'bad' => $this->createTaskConfiguration('@test.bad'), - ...($withStopTask ? ['stop' => $this->createTaskConfiguration('@test.stop')] : []), ], ], ], @@ -201,11 +176,7 @@ public function execute(ProcessState $state): void $eventDispatcher->addListener(ProcessEvent::EVENT_PROCESS_ENDED, function (ProcessEvent $event): void { $this->endedEvents[] = $event; }); - $eventDispatcher->addListener(ProcessEvent::EVENT_PROCESS_FAILED, function (ProcessEvent $event): void { - $this->endedEvents[] = $event; - }); - - return new ProcessManager( + $processManager = new ProcessManager( new ProcessLogger(new NullLogger()), new TaskLogger(new NullLogger()), $registry, @@ -213,6 +184,12 @@ public function execute(ProcessState $state): void $eventDispatcher, taskRegistry: new TaskRegistry($container), ); + $eventDispatcher->addListener(ProcessEvent::EVENT_PROCESS_FAILED, function (ProcessEvent $event) use ($processManager): void { + $this->failedEvents[] = $event; + $this->failedTasks[] = (string) $processManager->getTaskConfiguration()?->getCode(); + }); + + return $processManager; } /** diff --git a/tests/Task/CounterTaskTest.php b/tests/Task/CounterTaskTest.php index df8d99d6..ae9c6856 100644 --- a/tests/Task/CounterTaskTest.php +++ b/tests/Task/CounterTaskTest.php @@ -20,6 +20,7 @@ use CleverAge\ProcessBundle\Model\ProcessHistory; use CleverAge\ProcessBundle\Model\ProcessState; use CleverAge\ProcessBundle\Task\CounterTask; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; @@ -76,36 +77,23 @@ public function testFlushOutputsANewCountAfterNewExecutions(): void } /** - * A modulo by zero failed when executed. + * @return iterable */ - public function testZeroFlushEveryIsRejected(): void + public static function provideInvalidFlushEvery(): iterable { - $this->expectException(InvalidOptionsException::class); - $this->expectExceptionMessage('The option "flush_every" of the counter task must be a positive integer (the count is output every "flush_every" executions), 0 given.'); - - $this->createTask(0); + // A modulo by zero + yield 'zero' => [0]; + // It worked as its absolute value (sign of the modulo) until v6.0 + yield 'negative' => [-2]; } - /** - * A negative value works as its absolute value (sign of the modulo): deprecated. - */ - public function testNegativeFlushEveryIsDeprecated(): void + #[DataProvider('provideInvalidFlushEvery')] + public function testANonPositiveFlushEveryIsRejected(int $flushEvery): void { - $deprecations = []; - set_error_handler(static function (int $errno, string $errstr) use (&$deprecations): bool { - $deprecations[] = $errstr; - - return true; - }, \E_USER_DEPRECATED); - try { - [$task, $state] = $this->createTask(-2); - } finally { - restore_error_handler(); - } + $this->expectException(InvalidOptionsException::class); + $this->expectExceptionMessage("The option \"flush_every\" of the counter task must be a positive integer (the count is output every \"flush_every\" executions), {$flushEvery} given."); - self::assertSame(['Since cleverage/process-bundle 5.10: A negative "flush_every" option of the counter task (-2) is deprecated, it works as 2: use a positive integer. It will be rejected in v6.0.'], $deprecations); - self::assertSame([null, 2, null, 4, null], $this->executeAll($task, $state, 5)); - self::assertSame(5, $this->flush($task, $state)); + $this->createTask($flushEvery); } /** diff --git a/tests/Task/Event/EventDispatcherTaskTest.php b/tests/Task/Event/EventDispatcherTaskTest.php index 3ba23388..871f03be 100644 --- a/tests/Task/Event/EventDispatcherTaskTest.php +++ b/tests/Task/Event/EventDispatcherTaskTest.php @@ -38,9 +38,6 @@ class EventDispatcherTaskTest extends TestCase /** @var list */ private array $calledListeners = []; - /** @var list */ - private array $deprecations = []; - public function testEventIsDispatchedUnderEventName(): void { $dispatcher = $this->createDispatcher(['myapp.myevent']); @@ -48,7 +45,6 @@ public function testEventIsDispatchedUnderEventName(): void $this->execute($dispatcher, ['event_name' => 'myapp.myevent']); self::assertSame(['myapp.myevent'], $this->calledListeners); - self::assertSame([], $this->deprecations); } public function testEventIsDispatchedUnderClassNameWithoutEventName(): void @@ -58,7 +54,6 @@ public function testEventIsDispatchedUnderClassNameWithoutEventName(): void $this->execute($dispatcher, []); self::assertSame([EventDispatcherTaskEvent::class], $this->calledListeners); - self::assertSame([], $this->deprecations); } public function testEventIsDispatchedOnceWhenEventNameIsTheClassName(): void @@ -68,20 +63,18 @@ public function testEventIsDispatchedOnceWhenEventNameIsTheClassName(): void $this->execute($dispatcher, ['event_name' => EventDispatcherTaskEvent::class]); self::assertSame([EventDispatcherTaskEvent::class], $this->calledListeners); - self::assertSame([], $this->deprecations); } - public function testClassNameListenersAreStillCalledWithDeprecation(): void + /** + * From v4.0 to v5.x, the event was also dispatched under its class name when "event_name" was set. + */ + public function testClassNameListenersAreNotCalledWithAnEventName(): void { $dispatcher = $this->createDispatcher(['myapp.myevent', EventDispatcherTaskEvent::class]); $this->execute($dispatcher, ['event_name' => 'myapp.myevent']); - self::assertSame(['myapp.myevent', EventDispatcherTaskEvent::class], $this->calledListeners); - self::assertSame( - ['Since cleverage/process-bundle 5.1: Listening to "'.EventDispatcherTaskEvent::class.'" for an EventDispatcherTask with the "event_name" option set is deprecated and will not work anymore in v6.0, listen to "myapp.myevent" instead.'], - $this->deprecations - ); + self::assertSame(['myapp.myevent'], $this->calledListeners); } public function testPassiveTaskOutputsInput(): void @@ -124,18 +117,9 @@ private function execute(EventDispatcher $dispatcher, array $options, mixed $inp $state->setTaskConfiguration(new TaskConfiguration('dispatch', EventDispatcherTask::class, $options)); $state->setInput($input); - set_error_handler(function (int $errno, string $errstr): bool { - $this->deprecations[] = $errstr; - - return true; - }, \E_USER_DEPRECATED); - try { - $task = new EventDispatcherTask($dispatcher); - $task->initialize($state); - $task->execute($state); - } finally { - restore_error_handler(); - } + $task = new EventDispatcherTask($dispatcher); + $task->initialize($state); + $task->execute($state); return $state; } diff --git a/tests/Transformer/CallbackTransformerTest.php b/tests/Transformer/CallbackTransformerTest.php index af77571f..c8a6e714 100644 --- a/tests/Transformer/CallbackTransformerTest.php +++ b/tests/Transformer/CallbackTransformerTest.php @@ -13,30 +13,22 @@ namespace CleverAge\ProcessBundle\Tests\Transformer; -use CleverAge\ProcessBundle\Tests\IgnoreDeprecationsTrait; use CleverAge\ProcessBundle\Transformer\CallbackTransformer; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; +use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException; use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversClass(CallbackTransformer::class)] class CallbackTransformerTest extends TestCase { - use IgnoreDeprecationsTrait; - public static function doCallback(mixed ...$args): string { return implode('-', $args); } - protected function setUp(): void - { - // The deprecation is triggered once per PHP process - (new \ReflectionProperty(CallbackTransformer::class, 'additionalParametersDeprecated'))->setValue(null, false); - } - /** * @return iterable, string, mixed}> */ @@ -83,60 +75,14 @@ public function testTransform(array $options, mixed $value, mixed $expected): vo self::assertSame($expected, $transformer->transform($value, $this->resolveOptions($transformer, $options))); } - public function testAdditionalParametersAreUsedAsRightParameters(): void - { - $transformer = new CallbackTransformer(); - $options = self::ignoreDeprecations(fn (): array => $this->resolveOptions($transformer, [ - 'callback' => [self::class, 'doCallback'], - 'additional_parameters' => [7, 8], - ])); - - self::assertSame('6-7-8', $transformer->transform('6', $options)); - } - - public function testAdditionalParametersAreDeprecated(): void + public function testAdditionalParametersAreRejected(): void { - $transformer = new CallbackTransformer(); - $deprecations = []; - set_error_handler(static function (int $errno, string $errstr) use (&$deprecations): bool { - $deprecations[] = $errstr; - - return true; - }, \E_USER_DEPRECATED); - try { - $this->resolveOptions($transformer, [ - 'callback' => [self::class, 'doCallback'], - 'additional_parameters' => [7, 8], - ]); - // Once: it was triggered each time the options were resolved - $this->resolveOptions($transformer, [ - 'callback' => [self::class, 'doCallback'], - 'additional_parameters' => [7, 8], - ]); - $this->resolveOptions($transformer, [ - 'callback' => [self::class, 'doCallback'], - 'right_parameters' => [4], - ]); - } finally { - restore_error_handler(); - } - - self::assertSame( - ['Since cleverage/process-bundle 2.0.4: The "additional_parameters" option is deprecated. Use "right_parameters" instead.'], - $deprecations - ); - } + $this->expectException(UndefinedOptionsException::class); - public function testAdditionalParametersAreIgnoredWhenRightParametersAreSet(): void - { - $transformer = new CallbackTransformer(); - $options = self::ignoreDeprecations(fn (): array => $this->resolveOptions($transformer, [ + $this->resolveOptions(new CallbackTransformer(), [ 'callback' => [self::class, 'doCallback'], - 'right_parameters' => [4], 'additional_parameters' => [7, 8], - ])); - - self::assertSame('6-4', $transformer->transform('6', $options)); + ]); } public function testCallbackIsRequired(): void diff --git a/tests/Transformer/MappingTransformerTest.php b/tests/Transformer/MappingTransformerTest.php index 9654d719..84d989af 100644 --- a/tests/Transformer/MappingTransformerTest.php +++ b/tests/Transformer/MappingTransformerTest.php @@ -37,17 +37,6 @@ #[\PHPUnit\Framework\Attributes\UsesClass(TransformerException::class)] class MappingTransformerTest extends TestCase { - /** - * @var list - */ - private array $deprecations = []; - - protected function setUp(): void - { - // The deprecation is triggered once per PHP process - (new \ReflectionProperty(MappingTransformer::class, 'deprecatedLiteralKeys'))->setValue(null, []); - } - public function testMappingIsRequired(): void { $this->expectException(MissingOptionsException::class); @@ -495,7 +484,7 @@ public function testMissingNonSimpleTargetPropertyOfAStdClassThrows(string $targ $transformer->transform([], $options); } - public function testSimpleTargetPropertyIsAddedToAnArrayDestinationWithoutDeprecation(): void + public function testSimpleTargetPropertyIsAddedToAnArrayDestination(): void { $transformer = $this->createTransformer(); $options = $this->resolveOptions($transformer, [ @@ -504,10 +493,9 @@ public function testSimpleTargetPropertyIsAddedToAnArrayDestinationWithoutDeprec ], ]); - $result = $this->transformCollectingDeprecations($transformer, ['field' => 'value'], $options); + $result = $transformer->transform(['field' => 'value'], $options); self::assertSame(['field2' => 'value'], $result); - self::assertSame([], $this->deprecations); } /** @@ -521,7 +509,7 @@ public static function nonSimpleArrayTargetPropertyProvider(): iterable } #[DataProvider('nonSimpleArrayTargetPropertyProvider')] - public function testNonSimpleTargetPropertyOfAnArrayDestinationIsDeprecated(string $targetProperty): void + public function testNonSimpleTargetPropertyOfAnArrayDestinationIsRejected(string $targetProperty): void { $transformer = $this->createTransformer(); $options = $this->resolveOptions($transformer, [ @@ -530,17 +518,13 @@ public function testNonSimpleTargetPropertyOfAnArrayDestinationIsDeprecated(stri ], ]); - $result = $this->transformCollectingDeprecations($transformer, ['field' => 'value'], $options); - // Once per target property: it was triggered for each item - $this->transformCollectingDeprecations($transformer, ['field' => 'other'], $options); + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("The target property '{$targetProperty}' cannot be set in an array destination: use '[{$targetProperty}]' for a literal key, or the index notation for nested arrays (e.g. '[a][b]')."); - self::assertSame([$targetProperty => 'value'], $result); - self::assertSame([ - "Since cleverage/process-bundle 5.2: Setting the target property '{$targetProperty}' as a literal key of an array destination is deprecated, it will throw an \\UnexpectedValueException in v6.0. Use '[{$targetProperty}]' to keep a literal key, or the index notation for nested arrays (e.g. '[a][b]').", - ], $this->deprecations); + $transformer->transform(['field' => 'value'], $options); } - public function testIndexNotationKeepsALiteralKeyWithoutDeprecation(): void + public function testIndexNotationKeepsALiteralKey(): void { $transformer = $this->createTransformer(); $options = $this->resolveOptions($transformer, [ @@ -550,10 +534,9 @@ public function testIndexNotationKeepsALiteralKeyWithoutDeprecation(): void ], ]); - $result = $this->transformCollectingDeprecations($transformer, ['field' => 'value'], $options); + $result = $transformer->transform(['field' => 'value'], $options); self::assertSame(['field2.child' => 'value', 'field3' => ['child' => 'value']], $result); - self::assertSame([], $this->deprecations); } public function testKeepInputCopiesAnArrayInput(): void @@ -699,23 +682,6 @@ public function log($level, \Stringable|string $message, array $context = []): v }; } - /** - * @param array $options - */ - private function transformCollectingDeprecations(MappingTransformer $transformer, mixed $value, array $options): mixed - { - set_error_handler(function (int $errno, string $errstr): bool { - $this->deprecations[] = $errstr; - - return true; - }, \E_USER_DEPRECATED); - try { - return $transformer->transform($value, $options); - } finally { - restore_error_handler(); - } - } - /** * @param array $options *