Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ Latest
------

## Changes
* [#463](https://github.com/cleverage/process-bundle/issues/463) Error messages give the fix: a "Did you mean" suggestion for an unknown process (with a hint about `cleverage:process:list`), transformer, task code (with a hint about `#[AsTask]` / the `cleverage.task` tag) or output format (with the valid formats); the `key:value` format of an invalid context; the value of a `callback` that is not callable; a task given as a list (e.g. `outputs` badly indented) instead of `Unrecognized option "0"`; "neither" for a task without `task` nor `service`. New `ProcessConfigurationRegistry::getProcessCodes()`. Add tests.
* [#461](https://github.com/cleverage/process-bundle/issues/461) `cleverage:process:execute`: an input (`--input`, `--input-from-stdin`) given to a process without `entry_point` is reported on the error output of the command (only logged as a warning, not displayed without `-v`). Update documentation, add tests.
* [#444](https://github.com/cleverage/process-bundle/issues/444) New `exclusive` option of the processes (`false` by default): an execution of an exclusive process fails with the new `ProcessAlreadyRunningException` while another execution of it is running (same PHP process, or another one sharing the lock store), dispatched as any process failure. Backed by symfony/lock (new `suggest`, required by an exclusive process when the container is compiled): `ProcessManager` takes an optional `LockFactory` (`lock.factory`), the lock is named `cleverage_process.exclusive.<process_code>`, has a TTL of 300 seconds refreshed before the tasks, and is released at the end of the process or by the reset of the services. New `ProcessConfiguration::isExclusive()`. Update documentation, add tests.
* [#443](https://github.com/cleverage/process-bundle/issues/443) Documentation: two executions of the same process can run at the same time (cron, user interface, scheduler, Messenger workers); make the outputs unique and the writes idempotent, or lock the execution.
Expand Down
9 changes: 6 additions & 3 deletions src/Command/ExecuteProcessCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace CleverAge\ProcessBundle\Command;

use CleverAge\ProcessBundle\Configuration\DidYouMean;
use CleverAge\ProcessBundle\Configuration\TaskConfiguration;
use CleverAge\ProcessBundle\Event\ConsoleProcessEvent;
use CleverAge\ProcessBundle\Exception\InvalidArgumentException;
Expand Down Expand Up @@ -94,7 +95,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
// Checked before executing anything: a wrong option must not be detected once the work is done
foreach ($input->getArgument('processCodes') as $code) {
if (!$this->processRegistry->hasProcessConfiguration($code)) {
throw new InvalidConfigurationException("Unknown process {$code}");
throw new InvalidConfigurationException(\sprintf('Unknown process %s.%s The processes are listed by the cleverage:process:list command.', $code, DidYouMean::suggest($code, $this->processRegistry->getProcessCodes())));
}
}
$this->checkOutputFormat($input);
Expand Down Expand Up @@ -135,7 +136,7 @@ protected function parseContextValues(InputInterface $input): array
preg_match($pattern, (string) $contextValue, $parts);
if (3 !== \count($parts)
|| $parts[0] !== $contextValue) {
throw new InvalidArgumentException(\sprintf('Invalid context %s', $contextValue));
throw new InvalidArgumentException(\sprintf('Invalid context %s: expected key:value, e.g. -c date:2024-01-01 (the value is parsed as YAML)', $contextValue));
}
$context[$parts[1]] = $parser->parse($parts[2]);
}
Expand Down Expand Up @@ -181,7 +182,9 @@ protected function checkOutputFormat(InputInterface $input): void
throw new InvalidArgumentException("The 'dump' output format requires the VarDumper component: run \"composer require symfony/var-dumper\"");
}

throw new InvalidArgumentException(\sprintf("Cannot handle data output with format '%s'", $format));
$formats = [self::OUTPUT_FORMAT_DUMP, self::OUTPUT_FORMAT_JSON];

throw new InvalidArgumentException(\sprintf("Cannot handle data output with format '%s': use '%s' (STDOUT only) or '%s'.%s", $format, self::OUTPUT_FORMAT_DUMP, self::OUTPUT_FORMAT_JSON, DidYouMean::suggest((string) $format, $formats)));
}

protected function handleOutputData(mixed $data, InputInterface $input, OutputInterface $output): void
Expand Down
45 changes: 45 additions & 0 deletions src/Configuration/DidYouMean.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (c) Clever-Age
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace CleverAge\ProcessBundle\Configuration;

/**
* Suggestion of the closest known code in an error message: " Did you mean "x"?", or an empty string.
*
* @internal
*/
final class DidYouMean
{
/**
* @param iterable<int|string> $candidates
*/
public static function suggest(string $value, iterable $candidates): string
{
$best = null;
$bestDistance = null;
foreach ($candidates as $candidate) {
$candidate = (string) $candidate;
$distance = levenshtein(strtolower($value), strtolower($candidate));
// A typo, not another code: at most a third of the length (at least 1, at most 3 changes)
if ($distance > max(1, min(3, intdiv(\strlen($value), 3)))) {
continue;
}
if (null === $bestDistance || $distance < $bestDistance) {
$best = $candidate;
$bestDistance = $distance;
}
}

return null === $best ? '' : \sprintf(' Did you mean "%s"?', $best);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace CleverAge\ProcessBundle\DependencyInjection\Compiler;

use CleverAge\ProcessBundle\Configuration\DidYouMean;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand Down Expand Up @@ -101,7 +102,7 @@ private function resolveTaskCodes(ContainerBuilder $container, mixed $configurat
if (!\is_string($code) || !isset($codes[$code])) {
$known = array_keys($codes);
sort($known);
throw new InvalidArgumentException(\sprintf('Unknown task code "%s" for the task "%s" of the process "%s". Known codes: "%s".', \is_string($code) ? $code : get_debug_type($code), $taskCode, $processCode, implode('", "', $known)));
throw new InvalidArgumentException(\sprintf('Unknown task code "%s" for the task "%s" of the process "%s".%s A task of the application is given a code with the #[AsTask(code: \'...\')] attribute or the "code" attribute of its "cleverage.task" tag. Known codes: "%s".', \is_string($code) ? $code : get_debug_type($code), $taskCode, $processCode, \is_string($code) ? DidYouMean::suggest($code, $known) : '', implode('", "', $known)));
}
$configurations[$processCode]['tasks'][$taskCode]['service'] = '@'.$codes[$code];
}
Expand Down
11 changes: 10 additions & 1 deletion src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,19 @@ protected function appendProcessConfigDefinition(NodeBuilder $definition): void
->performNoDeepMerging()
->cannotBeOverwritten()
->info('Unique custom task code')
->beforeNormalization()
// e.g. "outputs: [next]" indented as a task: the list was reported as an unknown option "0"
->ifTrue(static fn (mixed $task): bool => \is_array($task) && [] !== $task && array_is_list($task))
->thenInvalid('A task is defined by a mapping ("task", "options", "outputs"...), not by a list: check the indentation of the "outputs" or "error_outputs" of the previous task. Given: %s')
->end()
->validate()
->ifTrue(static fn (array $task): bool => (null === $task['service']) === (null === $task['task']))
->ifTrue(static fn (array $task): bool => null !== $task['service'] && null !== $task['task'])
->thenInvalid('A task must define either its code ("task: <code>") or, deprecated, its "service", not both: %s')
->end()
->validate()
->ifTrue(static fn (array $task): bool => null === $task['service'] && null === $task['task'])
->thenInvalid('A task must define its code ("task: <code>", given on the reference page of each task), it defines neither "task" nor, deprecated, "service": %s')
->end()
->children();

$this->appendTaskConfigDefinition($taskListDefinition);
Expand Down
9 changes: 7 additions & 2 deletions src/Exception/MissingProcessException.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@

namespace CleverAge\ProcessBundle\Exception;

use CleverAge\ProcessBundle\Configuration\DidYouMean;

/**
* Exception thrown when trying to fetch a missing process.
*/
class MissingProcessException extends \UnexpectedValueException implements ProcessExceptionInterface
{
public static function create(?string $code = ''): self
/**
* @param iterable<string> $knownCodes to suggest the closest one
*/
public static function create(?string $code = '', iterable $knownCodes = []): self
{
$errorStr = "No process with code : {$code}";
$errorStr = "No process with code : {$code}".DidYouMean::suggest((string) $code, $knownCodes);

return new self($errorStr);
}
Expand Down
9 changes: 7 additions & 2 deletions src/Exception/MissingTransformerException.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@

namespace CleverAge\ProcessBundle\Exception;

use CleverAge\ProcessBundle\Configuration\DidYouMean;

/**
* Exception thrown when trying to fetch a missing transformer.
*/
class MissingTransformerException extends \UnexpectedValueException implements ProcessExceptionInterface
{
public static function create(?string $code = ''): self
/**
* @param iterable<int|string> $knownCodes to suggest the closest one
*/
public static function create(?string $code = '', iterable $knownCodes = []): self
{
$errorStr = "No transformer with code : {$code}";
$errorStr = "No transformer with code : {$code}".DidYouMean::suggest((string) $code, $knownCodes);

return new self($errorStr);
}
Expand Down
12 changes: 11 additions & 1 deletion src/Registry/ProcessConfigurationRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function __construct(
public function getProcessConfiguration(string $processCode): ProcessConfiguration
{
if (!$this->hasProcessConfiguration($processCode)) {
throw MissingProcessException::create($processCode);
throw MissingProcessException::create($processCode, $this->getProcessCodes());
}
$processCode = $this->resolveDeprecatedProcessCode($processCode);
$this->resolveConfiguration($processCode);
Expand Down Expand Up @@ -97,6 +97,16 @@ public function reset(): void
$this->processConfigurations = [];
}

/**
* The codes of the processes, without resolving their configuration.
*
* @return list<string>
*/
public function getProcessCodes(): array
{
return array_map(strval(...), array_keys($this->rawConfiguration));
}

public function hasProcessConfiguration(string $processCode): bool
{
return \array_key_exists($processCode, $this->rawConfiguration)
Expand Down
2 changes: 1 addition & 1 deletion src/Registry/TransformerRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public function getTransformer(string $code): TransformerInterface
return $this->transformers[$code];
}
if (!$this->locator?->has($code)) {
throw MissingTransformerException::create($code);
throw MissingTransformerException::create($code, array_keys($this->locator?->getProvidedServices() ?? []));
}

$transformer = $this->locator->get($code);
Expand Down
15 changes: 14 additions & 1 deletion src/Transformer/CallbackTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function configureOptions(OptionsResolver $resolver): void
'callback',
static function (Options $options, $value): callable {
if (!\is_callable($value)) {
throw new InvalidOptionsException('Callback option must be callable');
throw new InvalidOptionsException(\sprintf('Callback option must be callable, %s given', self::describe($value)));
}

return $value;
Expand Down Expand Up @@ -95,4 +95,17 @@ static function (Options $options, $value) {
}
);
}

private static function describe(mixed $value): string
{
if (\is_string($value)) {
return \sprintf('"%s"', $value);
}
if (\is_array($value) && array_is_list($value) && 2 === \count($value)
&& (\is_string($value[0]) || \is_object($value[0])) && \is_string($value[1])) {
return \sprintf('"%s::%s"', \is_object($value[0]) ? $value[0]::class : $value[0], $value[1]);
}

return get_debug_type($value);
}
}
25 changes: 25 additions & 0 deletions tests/Command/ExecuteProcessCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
#[UsesClass(ConsoleProcessEvent::class)]
#[UsesClass(JsonStreamFile::class)]
#[UsesClass(\CleverAge\ProcessBundle\Configuration\DeprecatedCodeAliases::class)]
#[UsesClass(\CleverAge\ProcessBundle\Configuration\DidYouMean::class)]
class ExecuteProcessCommandTest extends TestCase
{
private string $outputFile;
Expand Down Expand Up @@ -221,4 +222,28 @@ private function createTester(\PHPUnit\Framework\MockObject\Rule\InvocationOrder

return new CommandTester(new ExecuteProcessCommand($processManager, new EventDispatcher(), $registry));
}

public function testUnknownProcessSuggestsTheClosestOne(): void
{
$tester = $this->createTester($this->never());

$this->expectExceptionMessage('Unknown process test.proces. Did you mean "test.process"? The processes are listed by the cleverage:process:list command.');
$tester->execute(['processCodes' => ['test.proces']]);
}

public function testInvalidContextGivesTheExpectedFormat(): void
{
$tester = $this->createTester($this->never());

$this->expectExceptionMessage('Invalid context foo: expected key:value, e.g. -c date:2024-01-01 (the value is parsed as YAML)');
$tester->execute(['processCodes' => ['test.process'], '--context' => ['foo']]);
}

public function testUnknownOutputFormatGivesTheFormats(): void
{
$tester = $this->createTester($this->never());

$this->expectExceptionMessage("Cannot handle data output with format 'jsn-stream': use 'dump' (STDOUT only) or 'json-stream'. Did you mean \"json-stream\"?");
$tester->execute(['processCodes' => ['test.process'], '--output-format' => 'jsn-stream']);
}
}
47 changes: 47 additions & 0 deletions tests/Configuration/DidYouMeanTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

declare(strict_types=1);

/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (c) Clever-Age
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace CleverAge\ProcessBundle\Tests\Configuration;

use CleverAge\ProcessBundle\Configuration\DidYouMean;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

#[CoversClass(DidYouMean::class)]
class DidYouMeanTest extends TestCase
{
/**
* @return iterable<string, array{string, list<string>, string}>
*/
public static function provideSuggestions(): iterable
{
$codes = ['demo.main', 'demo.mail', 'uppercase', 'json-stream', 'dump'];
yield 'typo' => ['demo.mian', $codes, ' Did you mean "demo.main"?'];
yield 'closest first' => ['demo.mai', $codes, ' Did you mean "demo.main"?'];
yield 'missing letter' => ['uppercas', $codes, ' Did you mean "uppercase"?'];
yield 'case' => ['UPPERCASE', $codes, ' Did you mean "uppercase"?'];
yield 'too far' => ['csv', $codes, ''];
yield 'short value' => ['jsn', $codes, ''];
yield 'no candidate' => ['demo.main', [], ''];
}

/**
* @param list<string> $candidates
*/
#[DataProvider('provideSuggestions')]
public function testSuggest(string $value, array $candidates, string $expected): void
{
self::assertSame($expected, DidYouMean::suggest($value, $candidates));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
#[UsesClass(CleverAgeProcessExtension::class)]
#[UsesClass(Configuration::class)]
#[UsesClass(DeprecatedCodeAliases::class)]
#[UsesClass(\CleverAge\ProcessBundle\Configuration\DidYouMean::class)]
class TaskLocatorCompilerPassTest extends TestCase
{
use IgnoreDeprecationsTrait;
Expand Down Expand Up @@ -104,11 +105,11 @@ public function testTaskCodesAreResolvedIntoServices(): void

public function testUnknownTaskCodeThrows(): void
{
$container = $this->createContainerWithTask(['task' => 'unknown']);
$container = $this->createContainerWithTask(['task' => 'app_tsak']);
$container->setDefinition('app.task', (new Definition(DummyTask::class))->addTag('cleverage.task', ['code' => 'app_task']));

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Unknown task code "unknown" for the task "my_task" of the process "test.process". Known codes: "app_task".');
$this->expectExceptionMessage('Unknown task code "app_tsak" for the task "my_task" of the process "test.process". Did you mean "app_task"? A task of the application is given a code with the #[AsTask(code: \'...\')] attribute or the "code" attribute of its "cleverage.task" tag. Known codes: "app_task".');

(new TaskLocatorCompilerPass())->process($container);
}
Expand Down
27 changes: 22 additions & 5 deletions tests/DependencyInjection/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,23 @@ public function testErrorsIsDeprecated(): void
}

/**
* @return iterable<string, array{array<string, mixed>}>
* @return iterable<string, array{array<string, mixed>, string}>
*/
public static function provideInvalidTaskDefinitions(): iterable
{
yield 'neither service nor task' => [['options' => []]];
yield 'both service and task' => [['service' => '@app.task', 'task' => 'transformer']];
// The message said "not both"
yield 'neither service nor task' => [['options' => []], 'A task must define its code ("task: <code>", given on the reference page of each task), it defines neither "task" nor, deprecated, "service"'];
yield 'both service and task' => [['service' => '@app.task', 'task' => 'transformer'], 'A task must define either its code ("task: <code>") or, deprecated, its "service", not both'];
}

/**
* @param array<string, mixed> $task
*/
#[\PHPUnit\Framework\Attributes\DataProvider('provideInvalidTaskDefinitions')]
public function testTaskMustDefineEitherAServiceOrACode(array $task): void
public function testTaskMustDefineEitherAServiceOrACode(array $task, string $message): void
{
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessage('A task must define either its code ("task: <code>") or, deprecated, its "service", not both');
$this->expectExceptionMessage($message);

// Deprecated "service" option, see testServiceIsDeprecated()
self::ignoreDeprecations(fn (): array => $this->process(['configurations' => ['test.process' => ['tasks' => ['invalid' => $task]]]]));
Expand Down Expand Up @@ -259,6 +260,22 @@ public function testExclusive(): void
$this->process(['configurations' => ['test.process' => ['exclusive' => 'yes', 'tasks' => []]]]);
}

/**
* "outputs: [next]" indented as a task: it was reported as an unknown option "0".
*/
public function testATaskGivenAsAListIsReported(): void
{
// Thrown by the normalization (beforeNormalization()), before the validation
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('A task is defined by a mapping ("task", "options", "outputs"...), not by a list: check the indentation of the "outputs" or "error_outputs" of the previous task.');

$this->process(['configurations' => ['test.process' => ['tasks' => [
'first' => ['task' => 'transformer'],
'outputs' => ['next'],
'next' => ['task' => 'transformer'],
]]]]);
}

public function testPublicMustBeABoolean(): void
{
$this->expectException(InvalidConfigurationException::class);
Expand Down
Loading
Loading