diff --git a/CHANGELOG.md b/CHANGELOG.md index 34a933c8..e1fbab42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Latest ------ ## Changes +* [#275](https://github.com/cleverage/process-bundle/issues/275) The tasks are fetched from a service locator built at compile time from the services referenced by the process configurations (new `TaskRegistry`, `cleverage_process.registry.task`, and internal `TaskLocatorCompilerPass`) instead of the whole service container: a task service can be private. `ProcessManager` and `ProcessHelpCommand` get the registry as a new optional last constructor argument; not passing it is deprecated (the tasks are then fetched from the container), and fetching a task service not referenced by the process configurations known at compile time falls back on the container with a deprecation. Both fallbacks will be removed in v6.0 (#114). Update documentation, add tests. * [#278](https://github.com/cleverage/process-bundle/issues/278) The container no longer fails to compile when the Symfony serializer or validator is not enabled: the tasks and transformers depending on them (`NormalizerTask`, `DenormalizerTask`, `SerializerTask`, `DeserializerTask`, `normalize` and `denormalize` transformers, `ValidatorTask`) are replaced by services failing with an explicit message when they are used (new internal `UnavailableServicesCompilerPass`). `CheckSerializerCompilerPass` is no longer used and deprecated. Update documentation, add tests. * [#272](https://github.com/cleverage/process-bundle/issues/272) DependencyInjection: autoconfiguration of the services implementing `TaskInterface` (`public`, not shared, `monolog.logger` tag on `cleverage_process_task`) and `TransformerInterface` (`cleverage.transformer` tag, `monolog.logger` tag on `cleverage_process_transformer`): the `_instanceof` rules or explicit tags are no longer needed with `autoconfigure: true`; a setting explicitly defined on a service wins. Add FQCN aliases to autowire `ProcessManager`, `ProcessConfigurationRegistry`, `TransformerRegistry` and `ContextualOptionResolver`. Update documentation, add tests. * [#274](https://github.com/cleverage/process-bundle/issues/274) CI: test the lowest versions allowed by `composer.json` (`--prefer-lowest`, PHP 8.2). Fix the lower bounds it revealed: require `psr/log` `^2|^3` (`Logger\AbstractLogger` and the loggers of the tests use the typed `LoggerInterface` signatures, a fatal error with `psr/log` 1) and `monolog/monolog` `^3` (the `Logger\*Processor` classes use `Monolog\LogRecord`, Monolog 3 only: a `TypeError` on every log of the `cleverage_process*` channels with Monolog 2). diff --git a/config/services/command.yaml b/config/services/command.yaml index 947bce64..605446db 100644 --- a/config/services/command.yaml +++ b/config/services/command.yaml @@ -25,3 +25,4 @@ services: arguments: - '@cleverage_process.registry.process_configuration' - '@service_container' + - '@cleverage_process.registry.task' diff --git a/config/services/manager.yaml b/config/services/manager.yaml index 94a7f9c0..1739b5f7 100644 --- a/config/services/manager.yaml +++ b/config/services/manager.yaml @@ -10,6 +10,7 @@ services: - '@cleverage_process.context.contextual_option_resolver' - '@event_dispatcher' - !tagged_iterator cleverage_process.stop_checker + - '@cleverage_process.registry.task' CleverAge\ProcessBundle\Manager\ProcessManager: alias: cleverage_process.manager.process diff --git a/config/services/registry.yaml b/config/services/registry.yaml index a18f3366..de7e140d 100644 --- a/config/services/registry.yaml +++ b/config/services/registry.yaml @@ -14,3 +14,12 @@ services: public: false CleverAge\ProcessBundle\Registry\TransformerRegistry: alias: cleverage_process.registry.transformer + + cleverage_process.registry.task: + class: CleverAge\ProcessBundle\Registry\TaskRegistry + public: false + arguments: + - ~ # Service locator of the task services, see TaskLocatorCompilerPass + - '@service_container' # Deprecated fallback, removed in v6.0 + CleverAge\ProcessBundle\Registry\TaskRegistry: + alias: cleverage_process.registry.task diff --git a/docs/01-quick_start.md b/docs/01-quick_start.md index 43ba15dc..a227baba 100644 --- a/docs/01-quick_start.md +++ b/docs/01-quick_start.md @@ -77,9 +77,8 @@ clever_age_process: When creating custom tasks and transformers, you can use Symfony automatic registration. With autoconfiguration (`autoconfigure: true`, set in the `_defaults` of the Symfony skeleton, so the default `App\:` resource is enough), the bundle configures them: -- services implementing `CleverAge\ProcessBundle\Model\TaskInterface` are `public` (the process manager fetches tasks - from the container) and not shared (no data shared between task usages), with a `monolog.logger` tag on the - `cleverage_process_task` channel; +- services implementing `CleverAge\ProcessBundle\Model\TaskInterface` are not shared (no data shared between task + usages), with a `monolog.logger` tag on the `cleverage_process_task` channel; - services implementing `CleverAge\ProcessBundle\Transformer\TransformerInterface` get the `cleverage.transformer` tag (needed by the transformer registry) and a `monolog.logger` tag on the `cleverage_process_transformer` channel. @@ -99,7 +98,6 @@ services: resource: '../src/Task/*' autowire: true shared: false # Important to avoid shared data between task usages - public: true # Needed by the Process Manager to fetch tasks from the container tags: - { name: monolog.logger, channel: cleverage_process_task } # Optional, see logging ``` diff --git a/docs/03-custom_tasks.md b/docs/03-custom_tasks.md index 5bab561a..eeaa385f 100644 --- a/docs/03-custom_tasks.md +++ b/docs/03-custom_tasks.md @@ -9,8 +9,12 @@ create your own. As stated before, tasks are simple services implementing `CleverAge\ProcessBundle\Model\TaskInterface`, so you can design them like any other service, with only small specificities: -- the service must be **public**: the process manager fetches it from the container using the `service` reference of - the task configuration (with or without the leading `@`) +- the service does **not need to be public**: the process manager fetches it, using the `service` reference of the + task configuration (a service id or alias, with or without the leading `@`, see + [task definition](reference/02-task_definition.md#task-attributes)), from a service locator built from the process + configurations when the container is compiled. Only a service that is not referenced by these configurations (e.g. a + configuration added at runtime) is fetched from the service container, which requires a public service and is + deprecated - the service should **not be shared** ([`shared: false`](https://symfony.com/doc/current/service_container/shared.html)) Most of the time you don't want a task declared in a process to share some data with another declaration using the @@ -19,9 +23,9 @@ create one instance (keeping values in every attribute of your class). With `sha each time a task configuration is initialized. With autoconfiguration (`autoconfigure: true`, set in the `_defaults` of the Symfony skeleton), the bundle applies -these settings to every service implementing `TaskInterface`: `public: true`, `shared: false` and a `monolog.logger` -tag on the `cleverage_process_task` channel (see [logging](#logging)). A setting explicitly defined on the service -wins (e.g. `shared: true`). +these settings to every service implementing `TaskInterface`: `shared: false` and a `monolog.logger` tag on the +`cleverage_process_task` channel (see [logging](#logging)), as well as `public: true`, only kept for the deprecated +fallback on the service container. A setting explicitly defined on the service wins (e.g. `shared: true`). ```yaml # config/services.yaml @@ -40,7 +44,6 @@ services: App\Task\: resource: '../src/Task/*' autowire: true - public: true shared: false tags: - { name: monolog.logger, channel: cleverage_process_task } @@ -274,7 +277,6 @@ services: App\Task\: resource: '../src/Task/*' autowire: true - public: true shared: false tags: - { name: monolog.logger, channel: cleverage_process_task } diff --git a/docs/05-good_practices.md b/docs/05-good_practices.md index 63ea38cb..b71b9d99 100644 --- a/docs/05-good_practices.md +++ b/docs/05-good_practices.md @@ -17,7 +17,7 @@ in several places, declare it once as a [generic transformer](reference/03-gener ## Declare tasks as non-shared services -Task services must be `public: true` and should be `shared: false`: a task often keeps state in its properties (an +Task services should be `shared: false`: a task often keeps state in its properties (an open file, a buffer, a counter...). A shared service would share this state between two tasks using the same service in a process, or between two executions of a process in the same PHP process (sub-processes, workers, tests). See [service declaration](03-custom_tasks.md#service-declaration). diff --git a/docs/cookbooks/01-common_setup.md b/docs/cookbooks/01-common_setup.md index 1ecedf4e..6328e7f8 100644 --- a/docs/cookbooks/01-common_setup.md +++ b/docs/cookbooks/01-common_setup.md @@ -5,7 +5,7 @@ Task & transformer declaration ------------------------------ With autoconfiguration (`autoconfigure: true`, set in the `_defaults` of the Symfony skeleton), nothing more is needed: -the bundle makes the services implementing `CleverAge\ProcessBundle\Model\TaskInterface` public and not shared, tags +the bundle makes the services implementing `CleverAge\ProcessBundle\Model\TaskInterface` not shared, tags the ones implementing `CleverAge\ProcessBundle\Transformer\TransformerInterface` with `cleverage.transformer`, and binds both to their logging channel (`monolog.logger` tags). @@ -17,7 +17,6 @@ services: App\Task\: resource: '../src/Task/*' autowire: true - public: true shared: false tags: - { name: monolog.logger, channel: cleverage_process_task } @@ -25,7 +24,6 @@ services: App\Transformer\: resource: '../src/Transformer/*' autowire: true - public: false tags: - { name: cleverage.transformer } - { name: monolog.logger, channel: cleverage_process_transformer } @@ -44,7 +42,6 @@ it is located in your sources (`_instanceof` only applies to the services define services: _instanceof: CleverAge\ProcessBundle\Model\TaskInterface: - public: true shared: false tags: - { name: monolog.logger, channel: cleverage_process_task } diff --git a/docs/reference/02-task_definition.md b/docs/reference/02-task_definition.md index 5a43c7a9..36243957 100644 --- a/docs/reference/02-task_definition.md +++ b/docs/reference/02-task_definition.md @@ -20,8 +20,27 @@ YAML Configuration Task attributes --------------- -**service**: required, reference to the service used for the task, with or without a leading `@`. The service must be -public and implement `CleverAge\ProcessBundle\Model\TaskInterface`. +**service**: required, reference to the service used for the task: a service **id** or a service **alias**, with or +without a leading `@` (quote the value when it starts with `@`, as YAML requires). The service must implement +`CleverAge\ProcessBundle\Model\TaskInterface`. For instance, the `UnzipTask` of the archive bridge is registered as +`cleverage_archive_process.task.unzip`, with an alias named after its class: these four references are equivalent. + +```yaml +service: '@cleverage_archive_process.task.unzip' # id, with @ +service: cleverage_archive_process.task.unzip # id, without @ +service: '@CleverAge\ArchiveProcessBundle\Task\UnzipTask' # alias, with @ +service: CleverAge\ArchiveProcessBundle\Task\UnzipTask # alias, without @ +``` + +The tasks of this bundle are registered with their class name as id (e.g. `'@CleverAge\ProcessBundle\Task\TransformerTask'`), +the tasks of the bridge bundles with a `cleverage_*_process.task.*` id and an alias named after their class, and your +own task services with any id or alias you choose. With an unknown service, a reference with `@` throws the +`ServiceNotFoundException` of the service container, a reference without `@` an `\UnexpectedValueException` +(`Unable to resolve service reference for Task ''`). + +The services referenced by the process configurations are collected when the container is compiled, so they can be +private (as well as the aliases). Only a service that is not referenced by these configurations (e.g. a configuration +added at runtime) is fetched from the service container, which requires a public service and is deprecated since 5.4. **description**: optional string to describe a task, displayed in process help (should not exceed one line). diff --git a/src/CleverAgeProcessBundle.php b/src/CleverAgeProcessBundle.php index d8d7df9d..c9cfa6ca 100644 --- a/src/CleverAgeProcessBundle.php +++ b/src/CleverAgeProcessBundle.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle; use CleverAge\ProcessBundle\DependencyInjection\Compiler\RegistryCompilerPass; +use CleverAge\ProcessBundle\DependencyInjection\Compiler\TaskLocatorCompilerPass; use CleverAge\ProcessBundle\DependencyInjection\Compiler\UnavailableServicesCompilerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; @@ -32,6 +33,7 @@ public function build(ContainerBuilder $container): void ); $container->addCompilerPass(new UnavailableServicesCompilerPass()); + $container->addCompilerPass(new TaskLocatorCompilerPass()); } #[\Override] diff --git a/src/Command/ProcessHelpCommand.php b/src/Command/ProcessHelpCommand.php index 2a6b0cd7..c0060f68 100644 --- a/src/Command/ProcessHelpCommand.php +++ b/src/Command/ProcessHelpCommand.php @@ -20,6 +20,7 @@ use CleverAge\ProcessBundle\Model\IterableTaskInterface; use CleverAge\ProcessBundle\Model\TaskInterface; use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry; +use CleverAge\ProcessBundle\Registry\TaskRegistry; use CleverAge\ProcessBundle\Task\Process\ProcessExecutorTask; use CleverAge\ProcessBundle\Task\Process\ProcessLauncherTask; use Psr\Container\ContainerInterface; @@ -59,11 +60,26 @@ class ProcessHelpCommand extends Command protected const INDENT_SIZE = 4; + protected TaskRegistry $taskRegistry; + public function __construct( protected ProcessConfigurationRegistry $processConfigRegistry, protected ContainerInterface $container, + ?TaskRegistry $taskRegistry = null, ) { parent::__construct(); + if (!$taskRegistry instanceof TaskRegistry) { + trigger_deprecation( + 'cleverage/process-bundle', + '5.4', + 'Not passing a "%s" to "%s::__construct()" is deprecated: the tasks are fetched from the service container. The argument will be required in v6.0.', + TaskRegistry::class, + self::class, + ); + // Same behaviour as before the task registry: any service of the container + $taskRegistry = new TaskRegistry($this->container, $this->container); + } + $this->taskRegistry = $taskRegistry; } protected function configure(): void @@ -534,21 +550,6 @@ protected function getTaskDescription(TaskConfiguration $task): string protected function getTaskService(TaskConfiguration $taskConfiguration): TaskInterface { - // Duplicate code from \CleverAge\ProcessBundle\Manager\ProcessManager::initialize - // @todo Refactor this using a Registry with this feature: - // https://symfony.com/doc/current/service_container/service_subscribers_locators.html - $serviceReference = $taskConfiguration->getServiceReference(); - if (str_starts_with($serviceReference, '@')) { - $task = $this->container->get(ltrim($serviceReference, '@')); - } elseif ($this->container->has($serviceReference)) { - $task = $this->container->get($serviceReference); - } else { - throw new \UnexpectedValueException("Unable to resolve service reference for Task '{$taskConfiguration->getCode()}'"); - } - if (!$task instanceof TaskInterface) { - throw new \UnexpectedValueException("Service defined in Task '{$taskConfiguration->getCode()}' is not a TaskInterface"); - } - - return $task; + return $this->taskRegistry->getTask($taskConfiguration); } } diff --git a/src/DependencyInjection/Compiler/TaskLocatorCompilerPass.php b/src/DependencyInjection/Compiler/TaskLocatorCompilerPass.php new file mode 100644 index 00000000..0e8cef9b --- /dev/null +++ b/src/DependencyInjection/Compiler/TaskLocatorCompilerPass.php @@ -0,0 +1,53 @@ +hasDefinition('cleverage_process.registry.task') + || !$container->hasDefinition('cleverage_process.registry.process_configuration')) { + return; + } + + $configurations = $container->getParameterBag()->resolveValue( + $container->getDefinition('cleverage_process.registry.process_configuration')->getArgument(0) + ); + $services = []; + foreach (\is_array($configurations) ? $configurations : [] as $configuration) { + foreach ($configuration['tasks'] ?? [] as $task) { + $id = ltrim((string) ($task['service'] ?? ''), '@'); + // Unknown services keep failing at runtime, with the same message + if ('' !== $id && $container->has($id)) { + $services[$id] = new Reference($id); + } + } + } + + $container->getDefinition('cleverage_process.registry.task') + ->replaceArgument(0, ServiceLocatorTagPass::register($container, $services)); + } +} diff --git a/src/Manager/ProcessManager.php b/src/Manager/ProcessManager.php index 3c2ce0a4..2ea3579a 100644 --- a/src/Manager/ProcessManager.php +++ b/src/Manager/ProcessManager.php @@ -32,6 +32,7 @@ use CleverAge\ProcessBundle\Model\ProcessStopCheckerInterface; use CleverAge\ProcessBundle\Model\TaskInterface; use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry; +use CleverAge\ProcessBundle\Registry\TaskRegistry; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -60,6 +61,8 @@ class ProcessManager protected ?TaskConfiguration $taskConfiguration = null; + protected TaskRegistry $taskRegistry; + /** * @param iterable $stopCheckers */ @@ -71,7 +74,20 @@ public function __construct( protected ContextualOptionResolver $contextualOptionResolver, protected EventDispatcherInterface $eventDispatcher, protected iterable $stopCheckers = [], + ?TaskRegistry $taskRegistry = null, ) { + if (!$taskRegistry instanceof TaskRegistry) { + trigger_deprecation( + 'cleverage/process-bundle', + '5.4', + 'Not passing a "%s" to "%s::__construct()" is deprecated: the tasks are fetched from the service container. The argument will be required in v6.0.', + TaskRegistry::class, + self::class, + ); + // Same behaviour as before the task registry: any service of the container + $taskRegistry = new TaskRegistry($this->container, $this->container); + } + $this->taskRegistry = $taskRegistry; } public function getProcessHistory(): ?ProcessHistory @@ -250,19 +266,7 @@ protected function initialize(TaskConfiguration $taskConfiguration): void $m .= "but it's error strategy 'stop' implies they will never be reached."; $this->taskLogger->debug($m); } - // @todo Refactor this using a Registry with this feature: - // https://symfony.com/doc/current/service_container/service_subscribers_locators.html - $serviceReference = $taskConfiguration->getServiceReference(); - if (str_starts_with($serviceReference, '@')) { - $task = $this->container->get(ltrim($serviceReference, '@')); - } elseif ($this->container->has($serviceReference)) { - $task = $this->container->get($serviceReference); - } else { - throw new \UnexpectedValueException("Unable to resolve service reference for Task '{$taskConfiguration->getCode()}'"); - } - if (!$task instanceof TaskInterface) { - throw new \UnexpectedValueException("Service defined in Task '{$taskConfiguration->getCode()}' is not a TaskInterface"); - } + $task = $this->taskRegistry->getTask($taskConfiguration); $taskConfiguration->setTask($task); if ($task instanceof InitializableTaskInterface) { diff --git a/src/Registry/TaskRegistry.php b/src/Registry/TaskRegistry.php new file mode 100644 index 00000000..5d77271a --- /dev/null +++ b/src/Registry/TaskRegistry.php @@ -0,0 +1,62 @@ +getServiceReference(); + $id = ltrim($serviceReference, '@'); + if ($this->locator->has($id)) { + $task = $this->locator->get($id); + } elseif ($this->fallbackContainer instanceof ContainerInterface && $this->fallbackContainer->has($id)) { + trigger_deprecation( + 'cleverage/process-bundle', + '5.4', + 'Fetching the service "%s" of the task "%s" from the service container is deprecated: it is not referenced by the process configurations known when the container is compiled. It will not be found anymore in v6.0.', + $id, + $taskConfiguration->getCode(), + ); + $task = $this->fallbackContainer->get($id); + } elseif (str_starts_with($serviceReference, '@') && $this->fallbackContainer instanceof ContainerInterface) { + // Same exception as before the locator for an unknown service referenced with "@" + $task = $this->fallbackContainer->get($id); + } else { + throw new \UnexpectedValueException("Unable to resolve service reference for Task '{$taskConfiguration->getCode()}'"); + } + if (!$task instanceof TaskInterface) { + throw new \UnexpectedValueException("Service defined in Task '{$taskConfiguration->getCode()}' is not a TaskInterface"); + } + + return $task; + } +} diff --git a/tests/Command/ProcessHelpCommandTest.php b/tests/Command/ProcessHelpCommandTest.php new file mode 100644 index 00000000..39e0fd74 --- /dev/null +++ b/tests/Command/ProcessHelpCommandTest.php @@ -0,0 +1,67 @@ +collectDeprecations(static fn (): ProcessHelpCommand => new ProcessHelpCommand(new ProcessConfigurationRegistry([], 'stop'), new Container())) + ); + } + + public function testWithTaskRegistryIsNotDeprecated(): void + { + self::assertSame( + [], + $this->collectDeprecations(static fn (): ProcessHelpCommand => new ProcessHelpCommand(new ProcessConfigurationRegistry([], 'stop'), new Container(), new TaskRegistry(new ServiceLocator([])))) + ); + } + + /** + * @param callable(): mixed $callable + * + * @return list + */ + private function collectDeprecations(callable $callable): array + { + $deprecations = []; + set_error_handler(static function (int $errno, string $errstr) use (&$deprecations): bool { + $deprecations[] = $errstr; + + return true; + }, \E_USER_DEPRECATED); + try { + $callable(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } +} diff --git a/tests/DependencyInjection/Compiler/TaskLocatorCompilerPassTest.php b/tests/DependencyInjection/Compiler/TaskLocatorCompilerPassTest.php new file mode 100644 index 00000000..3c4b9267 --- /dev/null +++ b/tests/DependencyInjection/Compiler/TaskLocatorCompilerPassTest.php @@ -0,0 +1,76 @@ +load([[ + 'configurations' => [ + 'test.first' => ['tasks' => [ + 'dummy' => ['service' => '@'.DummyTask::class], + 'private' => ['service' => 'app.private_task'], + ]], + 'test.second' => ['tasks' => [ + 'dummy_again' => ['service' => DummyTask::class], + 'unknown' => ['service' => '@app.unknown'], + ]], + ], + ]], $container); + // Private services can be fetched from the locator + $container->setDefinition('app.private_task', (new Definition(DummyTask::class))->setPublic(false)); + + (new TaskLocatorCompilerPass())->process($container); + + $locatorReference = $container->getDefinition('cleverage_process.registry.task')->getArgument(0); + self::assertInstanceOf(Reference::class, $locatorReference); + $locator = $container->getDefinition((string) $locatorReference); + self::assertSame(ServiceLocator::class, $locator->getClass()); + $services = $locator->getArgument(0); + self::assertIsArray($services); + // Unknown services are left out: they keep failing at runtime + self::assertSame([DummyTask::class, 'app.private_task'], array_keys($services)); + foreach ($services as $id => $service) { + self::assertInstanceOf(ServiceClosureArgument::class, $service); + self::assertSame($id, (string) $service->getValues()[0]); + } + } + + public function testNothingIsDoneWithoutTheRegistries(): void + { + $container = new ContainerBuilder(); + + (new TaskLocatorCompilerPass())->process($container); + + self::assertFalse($container->hasDefinition('cleverage_process.registry.task')); + } +} diff --git a/tests/Manager/ProcessManagerEndLogTest.php b/tests/Manager/ProcessManagerEndLogTest.php index 4b6ae803..3262f194 100644 --- a/tests/Manager/ProcessManagerEndLogTest.php +++ b/tests/Manager/ProcessManagerEndLogTest.php @@ -27,6 +27,7 @@ use CleverAge\ProcessBundle\Model\ProcessState; use CleverAge\ProcessBundle\Model\TaskInterface; use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry; +use CleverAge\ProcessBundle\Registry\TaskRegistry; use CleverAge\ProcessBundle\Task\ConstantOutputTask; use CleverAge\ProcessBundle\Task\StopTask; use PHPUnit\Framework\TestCase; @@ -40,6 +41,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(ProcessConfigurationRegistry::class)] #[\PHPUnit\Framework\Attributes\CoversClass(ProcessConfiguration::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessFailedException::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(TaskRegistry::class)] #[\PHPUnit\Framework\Attributes\UsesClass(TaskConfiguration::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ContextualOptionResolver::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessEvent::class)] @@ -183,6 +185,7 @@ public function log($level, string|\Stringable $message, array $context = []): v new ProcessConfigurationRegistry(['test.process' => $rawConfiguration], 'stop', $defaultLogLevels), new ContextualOptionResolver(), new EventDispatcher(), + taskRegistry: new TaskRegistry($container), ); } diff --git a/tests/Manager/ProcessManagerInitializationTest.php b/tests/Manager/ProcessManagerInitializationTest.php index d01c7921..a4dc6f12 100644 --- a/tests/Manager/ProcessManagerInitializationTest.php +++ b/tests/Manager/ProcessManagerInitializationTest.php @@ -27,6 +27,7 @@ use CleverAge\ProcessBundle\Model\ProcessState; use CleverAge\ProcessBundle\Model\TaskInterface; use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry; +use CleverAge\ProcessBundle\Registry\TaskRegistry; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; use Symfony\Component\DependencyInjection\Container; @@ -38,6 +39,7 @@ */ #[\PHPUnit\Framework\Attributes\CoversClass(ProcessManager::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessConfiguration::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(TaskRegistry::class)] #[\PHPUnit\Framework\Attributes\UsesClass(TaskConfiguration::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ContextualOptionResolver::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessEvent::class)] @@ -183,6 +185,7 @@ public function execute(ProcessState $state): void $registry, new ContextualOptionResolver(), new EventDispatcher(), + taskRegistry: new TaskRegistry($container), ); } diff --git a/tests/Manager/ProcessManagerStopCheckerTest.php b/tests/Manager/ProcessManagerStopCheckerTest.php index 7c76c3fd..927d0476 100644 --- a/tests/Manager/ProcessManagerStopCheckerTest.php +++ b/tests/Manager/ProcessManagerStopCheckerTest.php @@ -29,6 +29,7 @@ use CleverAge\ProcessBundle\Model\ProcessStopCheckerInterface; use CleverAge\ProcessBundle\Model\TaskInterface; use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry; +use CleverAge\ProcessBundle\Registry\TaskRegistry; use CleverAge\ProcessBundle\Task\AbstractIterableOutputTask; use CleverAge\ProcessBundle\Task\ConstantIterableOutputTask; use PHPUnit\Framework\Attributes\CoversClass; @@ -41,6 +42,7 @@ #[CoversClass(ProcessManager::class)] #[CoversClass(ProcessStoppedException::class)] #[UsesClass(ProcessFailedException::class)] +#[UsesClass(TaskRegistry::class)] #[UsesClass(ProcessConfiguration::class)] #[UsesClass(TaskConfiguration::class)] #[UsesClass(ContextualOptionResolver::class)] @@ -200,6 +202,7 @@ public function execute(ProcessState $state): void new ContextualOptionResolver(), $eventDispatcher, $stopCheckers, + taskRegistry: new TaskRegistry($container), ); } diff --git a/tests/Manager/ProcessManagerStopStrategyTest.php b/tests/Manager/ProcessManagerStopStrategyTest.php index a2399dd6..cc1ad21b 100644 --- a/tests/Manager/ProcessManagerStopStrategyTest.php +++ b/tests/Manager/ProcessManagerStopStrategyTest.php @@ -27,6 +27,7 @@ use CleverAge\ProcessBundle\Model\ProcessState; use CleverAge\ProcessBundle\Model\TaskInterface; use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry; +use CleverAge\ProcessBundle\Registry\TaskRegistry; use CleverAge\ProcessBundle\Task\ConstantOutputTask; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; @@ -36,6 +37,7 @@ #[\PHPUnit\Framework\Attributes\CoversClass(ProcessManager::class)] #[\PHPUnit\Framework\Attributes\CoversClass(ProcessFailedException::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessConfiguration::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(TaskRegistry::class)] #[\PHPUnit\Framework\Attributes\UsesClass(TaskConfiguration::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ContextualOptionResolver::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessEvent::class)] @@ -115,6 +117,7 @@ public function execute(ProcessState $state): void $registry, new ContextualOptionResolver(), new EventDispatcher(), + taskRegistry: new TaskRegistry($container), ); } diff --git a/tests/Manager/ProcessManagerTaskRegistryTest.php b/tests/Manager/ProcessManagerTaskRegistryTest.php new file mode 100644 index 00000000..fedaddc6 --- /dev/null +++ b/tests/Manager/ProcessManagerTaskRegistryTest.php @@ -0,0 +1,141 @@ + */ + private array $deprecations = []; + + public function testTasksAreFetchedWithTheTaskRegistry(): void + { + $processManager = $this->collectDeprecations(fn (): ProcessManager => $this->createProcessManager( + new TaskRegistry(new ServiceLocator(['app.constant' => static fn (): ConstantOutputTask => new ConstantOutputTask()])) + )); + + self::assertSame('ok', $this->collectDeprecations(static fn (): mixed => $processManager->execute('test.process'))); + self::assertSame([], $this->deprecations); + } + + public function testWithoutTaskRegistryTheTasksAreFetchedFromTheContainerWithADeprecation(): void + { + $processManager = $this->collectDeprecations(fn (): ProcessManager => $this->createProcessManager(null)); + + self::assertSame('ok', $this->collectDeprecations(static fn (): mixed => $processManager->execute('test.process'))); + self::assertSame( + ['Since cleverage/process-bundle 5.4: Not passing a "'.TaskRegistry::class.'" to "'.ProcessManager::class.'::__construct()" is deprecated: the tasks are fetched from the service container. The argument will be required in v6.0.'], + $this->deprecations + ); + } + + private function createProcessManager(?TaskRegistry $taskRegistry): ProcessManager + { + $container = new Container(); + $container->set('app.constant', new ConstantOutputTask()); + $registry = new ProcessConfigurationRegistry( + [ + 'test.process' => [ + 'options' => [], + 'entry_point' => null, + 'end_point' => 'constant', + 'description' => '', + 'help' => '', + 'public' => true, + 'tasks' => [ + 'constant' => [ + 'service' => '@app.constant', + 'options' => ['output' => 'ok'], + 'description' => '', + 'help' => '', + 'outputs' => [], + 'errors' => [], + 'error_outputs' => [], + 'error_strategy' => null, + 'log_level' => null, + ], + ], + ], + ], + 'stop' + ); + + return new ProcessManager( + $container, + new ProcessLogger(new NullLogger()), + new TaskLogger(new NullLogger()), + $registry, + new ContextualOptionResolver(), + new EventDispatcher(), + taskRegistry: $taskRegistry, + ); + } + + /** + * @template T + * + * @param callable(): T $callable + * + * @return T + */ + private function collectDeprecations(callable $callable): mixed + { + set_error_handler(function (int $errno, string $errstr): bool { + $this->deprecations[] = $errstr; + + return true; + }, \E_USER_DEPRECATED); + try { + return $callable(); + } finally { + restore_error_handler(); + } + } +} diff --git a/tests/Registry/TaskRegistryTest.php b/tests/Registry/TaskRegistryTest.php new file mode 100644 index 00000000..4b77959c --- /dev/null +++ b/tests/Registry/TaskRegistryTest.php @@ -0,0 +1,139 @@ + */ + private array $deprecations = []; + + /** + * @return iterable + */ + public static function provideServiceReferences(): iterable + { + yield 'with @' => ['@app.task']; + yield 'without @' => ['app.task']; + } + + #[DataProvider('provideServiceReferences')] + public function testTaskIsFetchedFromTheLocator(string $serviceReference): void + { + $registry = new TaskRegistry($this->createLocator(), $this->createContainer()); + + $task = $this->getTask($registry, $serviceReference); + + self::assertInstanceOf(DummyTask::class, $task); + self::assertSame([], $this->deprecations); + } + + public function testLocatorCreatesANewInstanceForEachTask(): void + { + $registry = new TaskRegistry($this->createLocator()); + + self::assertNotSame($this->getTask($registry, '@app.task'), $this->getTask($registry, '@app.task')); + } + + #[DataProvider('provideServiceReferences')] + public function testFallbackOnTheContainerIsDeprecated(string $serviceReference): void + { + $container = $this->createContainer(); + $registry = new TaskRegistry(new ServiceLocator([]), $container); + + $task = $this->getTask($registry, $serviceReference); + + self::assertSame($container->get('app.task'), $task); + self::assertSame( + ['Since cleverage/process-bundle 5.4: Fetching the service "app.task" of the task "task" from the service container is deprecated: it is not referenced by the process configurations known when the container is compiled. It will not be found anymore in v6.0.'], + $this->deprecations + ); + } + + public function testUnknownServiceWithoutAtThrows(): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Unable to resolve service reference for Task 'task'"); + + $this->getTask(new TaskRegistry(new ServiceLocator([]), new Container()), 'app.unknown'); + } + + public function testUnknownServiceWithAtThrowsAsTheContainer(): void + { + // Same exception as before the task registry + $this->expectException(ServiceNotFoundException::class); + + $this->getTask(new TaskRegistry(new ServiceLocator([]), new Container()), '@app.unknown'); + } + + public function testUnknownServiceWithoutFallbackThrows(): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Unable to resolve service reference for Task 'task'"); + + $this->getTask(new TaskRegistry(new ServiceLocator([])), '@app.unknown'); + } + + public function testServiceThatIsNotATaskThrows(): void + { + $registry = new TaskRegistry(new ServiceLocator(['app.task' => static fn (): \stdClass => new \stdClass()])); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Service defined in Task 'task' is not a TaskInterface"); + + $this->getTask($registry, '@app.task'); + } + + /** + * @return ServiceLocator + */ + private function createLocator(): ServiceLocator + { + return new ServiceLocator(['app.task' => static fn (): DummyTask => new DummyTask()]); + } + + private function createContainer(): Container + { + $container = new Container(); + $container->set('app.task', new DummyTask()); + + return $container; + } + + private function getTask(TaskRegistry $registry, string $serviceReference): object + { + set_error_handler(function (int $errno, string $errstr): bool { + $this->deprecations[] = $errstr; + + return true; + }, \E_USER_DEPRECATED); + try { + return $registry->getTask(new TaskConfiguration('task', $serviceReference, [])); + } finally { + restore_error_handler(); + } + } +}