From 89d07567ab9cda3595fa02b28040140e8bb26287 Mon Sep 17 00:00:00 2001 From: Nicolas Joubert Date: Fri, 9 Oct 2026 10:52:50 +0200 Subject: [PATCH] chore(quality) #143 Improve PHPStan level from 6 to 7 and fix the level 8 errors not requiring a signature change: explicit exceptions instead of TypeError / Error on edge cases (CsvResource, XpathEvaluatorTransformer, SlugifyTransformer, GenericTransformer, TransformerTrait, RegistryCompilerPass, SubprocessInstance), safe defaults in ProcessState, ConditionTrait, IterableBatchTask and JsonStreamReaderTask Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 2 + docs/reference/tasks/csv_reader_task.md | 3 +- .../transformers/slugify_transformer.md | 2 + .../xpath_evaluator_transformer.md | 3 +- phpstan.neon | 2 +- src/Command/ListProcessCommand.php | 2 +- src/Command/ProcessHelpCommand.php | 23 +++++--- .../Compiler/RegistryCompilerPass.php | 4 ++ src/Filesystem/CsvResource.php | 17 +++++- src/Filesystem/FileStreamInterface.php | 2 + src/Filesystem/JsonStreamFile.php | 2 + src/Model/ProcessState.php | 5 +- src/Model/SubprocessInstance.php | 7 ++- src/Task/AbstractIterableOutputTask.php | 10 +++- src/Task/File/Csv/CsvReaderTask.php | 12 ++-- src/Task/File/Csv/CsvWriterTask.php | 3 +- src/Task/File/FolderBrowserTask.php | 25 ++++++-- .../File/JsonStream/JsonStreamReaderTask.php | 3 + src/Task/IterableBatchTask.php | 4 +- src/Task/Process/ProcessLauncherTask.php | 4 +- .../Reporting/AdvancedStatCounterTask.php | 2 +- src/Transformer/CachedTransformer.php | 2 + src/Transformer/ConditionTrait.php | 4 +- src/Transformer/GenericTransformer.php | 10 +++- src/Transformer/String/SlugifyTransformer.php | 3 + src/Transformer/TransformerTrait.php | 13 ++++- .../Xml/XpathEvaluatorTransformer.php | 20 ++++++- .../Compiler/RegistryCompilerPassTest.php | 52 +++++++++++++++++ tests/Filesystem/CsvResourceTest.php | 57 +++++++++++++++++++ tests/Model/ProcessStateTest.php | 18 ++++++ .../JsonStream/JsonStreamReaderTaskTest.php | 5 ++ tests/Task/IterableBatchTaskTest.php | 10 ++++ tests/Task/Reporting/LoggerTaskTest.php | 6 +- tests/Task/Validation/ValidatorTaskTest.php | 6 +- tests/Transformer/GenericTransformerTest.php | 10 ++++ .../String/SlugifyTransformerTest.php | 10 ++++ tests/Transformer/TransformerTraitHolder.php | 57 +++++++++++++++++++ tests/Transformer/TransformerTraitTest.php | 46 ++++----------- .../Xml/XpathEvaluatorTransformerTest.php | 37 ++++++++++++ 39 files changed, 419 insertions(+), 84 deletions(-) create mode 100644 tests/DependencyInjection/Compiler/RegistryCompilerPassTest.php create mode 100644 tests/Filesystem/CsvResourceTest.php create mode 100644 tests/Transformer/TransformerTraitHolder.php diff --git a/CHANGELOG.md b/CHANGELOG.md index bdf7f535..206837d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,11 @@ Latest ## Changes * [#197](https://github.com/cleverage/process-bundle/issues/197) Add missing tests: every Task and Transformer is now covered by unit tests. Remove the obsolete `tests.old` directory. * [#143](https://github.com/cleverage/process-bundle/issues/143) Improve PHPStan configuration: remove all `ignoreErrors` and `@phpstan-ignore` comments (report unmatched ignored errors again), add missing iterable value types and generic types in PHPDoc, remove unreachable code in AbstractIterableOutputTask and InputAggregatorTask. +* [#143](https://github.com/cleverage/process-bundle/issues/143) Improve PHPStan level from 6 to 7, and fix the level 8 errors that do not require a signature change (the remaining ones, due to nullable return types such as `AbstractConfigurableTask::getOptions(): ?array`, will be fixed in v6.0). Default to a `ContextualOptionResolver` in ProcessState and to a property accessor in ConditionTrait when none is set. ## Fixes * [#143](https://github.com/cleverage/process-bundle/issues/143) Fix InputIteratorTask: an `\IteratorAggregate` input whose `getIterator()` does not return an `\Iterator` (e.g. another `\IteratorAggregate`) is iterated instead of failing with a `TypeError`. Update documentation, add tests. +* [#143](https://github.com/cleverage/process-bundle/issues/143) Fix level 8 edge cases failing with a `TypeError` or an `Error`: `CsvResource` rejects a blank header line and checks `ftell()`, XpathEvaluatorTransformer throws an explicit `\UnexpectedValueException` on an invalid query (with the libxml messages), a namespace node to unwrap or a node without document, SlugifyTransformer on a value that cannot be transliterated, `ProcessState::getContext()` returns `[]` until the context is defined, GenericTransformer and TransformerTrait throw a `\LogicException` when not initialized, IterableBatchTask and JsonStreamReaderTask can be flushed / iterated before their first execution, RegistryCompilerPass checks its configuration, SubprocessInstance checks the PHP executable. Update documentation, add tests. v5.1 ----- diff --git a/docs/reference/tasks/csv_reader_task.md b/docs/reference/tasks/csv_reader_task.md index b1872987..664321f2 100644 --- a/docs/reference/tasks/csv_reader_task.md +++ b/docs/reference/tasks/csv_reader_task.md @@ -70,7 +70,8 @@ Notes ----- * Each line must contain exactly as many columns as there are headers, otherwise an `\UnexpectedValueException` is thrown. -* A UTF-8 BOM is removed from the first header when headers are read from the file. +* A UTF-8 BOM is removed from the first header when headers are read from the file. If the first line is blank, an + `\UnexpectedValueException` is thrown. * `csv_file` and `csv_line` are added to the error context of the process. * The file is closed once fully read: if the task is executed again (e.g. for a new input), the file is read again from its beginning. diff --git a/docs/reference/transformers/slugify_transformer.md b/docs/reference/transformers/slugify_transformer.md index 063fc7b1..fd85192a 100644 --- a/docs/reference/transformers/slugify_transformer.md +++ b/docs/reference/transformers/slugify_transformer.md @@ -58,3 +58,5 @@ Notes An invalid `transliterator` identifier (rejected by `\Transliterator::create()`), or an option that is not a string, raises an `InvalidOptionsException` when the options are resolved, i.e. when the transformer is configured, not on the first transformed value. + +A value that cannot be transliterated (e.g. invalid UTF-8) throws an `\UnexpectedValueException`. diff --git a/docs/reference/transformers/xpath_evaluator_transformer.md b/docs/reference/transformers/xpath_evaluator_transformer.md index d87b7a0a..3ed4609c 100644 --- a/docs/reference/transformers/xpath_evaluator_transformer.md +++ b/docs/reference/transformers/xpath_evaluator_transformer.md @@ -17,7 +17,8 @@ Transformer reference Accepted inputs --------------- -`\DOMNode` (including `\DOMDocument`). Any other value throws an `\UnexpectedValueException`. +`\DOMNode` (including `\DOMDocument`). Any other value, a node that does not belong to a document or an invalid xpath +query throws an `\UnexpectedValueException`. Possible outputs ---------------- diff --git a/phpstan.neon b/phpstan.neon index 337ea110..3ac0c7ab 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,5 +1,5 @@ parameters: - level: 6 + level: 7 paths: - src - tests diff --git a/src/Command/ListProcessCommand.php b/src/Command/ListProcessCommand.php index 4837bda4..41818247 100644 --- a/src/Command/ListProcessCommand.php +++ b/src/Command/ListProcessCommand.php @@ -125,6 +125,6 @@ protected function padMessage(string $message, int $length = 80): string protected function filterOutTags(string $string): string { - return preg_replace('/<[^<>]*>/', '', $string); + return preg_replace('/<[^<>]*>/', '', $string) ?? $string; } } diff --git a/src/Command/ProcessHelpCommand.php b/src/Command/ProcessHelpCommand.php index 5864ffad..2a6b0cd7 100644 --- a/src/Command/ProcessHelpCommand.php +++ b/src/Command/ProcessHelpCommand.php @@ -107,12 +107,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $totalBranches = \count($taskList); for ($i = 0; $i < $totalBranches; ++$i) { // Find the best task to display - $nextTaskCode = $this->findBestNextTask($branches, $remainingTasks, $process); + // A numeric task code may be returned as an integer array key + $nextTaskCode = (string) $this->findBestNextTask($branches, $remainingTasks, $process); $this->resolveBranchOutput($branches, $nextTaskCode, $process, $output); // Remove the task from the remaining list - $remainingTasks = array_filter($remainingTasks, static fn ($task): bool => $task !== $nextTaskCode); + $remainingTasks = array_values(array_filter($remainingTasks, static fn ($task): bool => $task !== $nextTaskCode)); } $branches = array_filter($branches); @@ -127,8 +128,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int /** * Try to find a best candidate for next display. * - * @param array $branches - * @param list $taskList + * @param array $branches + * @param list $taskList */ protected function findBestNextTask( array $branches, @@ -227,7 +228,7 @@ protected function getTaskChildrenCount(TaskConfiguration $task): int /** * Merge needed branches, display a task node, split following needed branches. * - * @param array $branches + * @param array $branches */ protected function resolveBranchOutput( array &$branches, @@ -293,7 +294,12 @@ protected function resolveBranchOutput( $origin = array_shift($branchesToMerge); $final = $gapFrom; - $branches[$origin] = $taskCode; + if (null === $origin) { + // No previous branch found (an error has been displayed): open a new branch + $branches[] = $taskCode; + } else { + $branches[$origin] = $taskCode; + } } // Merge branches @@ -377,6 +383,9 @@ static function ($taskCode, $i) use ($gapBranches, $origin, $final, $branches): $this->writeBranches($output, $branches); array_shift($nextTasks); $origin = array_search($taskCode, $branches, true); + if (false === $origin) { + throw new \UnexpectedValueException("Task '{$taskCode}' is not in any branch"); + } $expandBranches = []; foreach ($nextTasks as $nextTask) { $index = array_search(null, $branches, true); @@ -448,7 +457,7 @@ static function ($branchTask, $i) use ($origin, $branches, $gapBranches, $final) } /** - * @param array $branches + * @param array $branches * @param string|iterable $comment */ protected function writeBranches( diff --git a/src/DependencyInjection/Compiler/RegistryCompilerPass.php b/src/DependencyInjection/Compiler/RegistryCompilerPass.php index 9de12c25..7896c4b5 100644 --- a/src/DependencyInjection/Compiler/RegistryCompilerPass.php +++ b/src/DependencyInjection/Compiler/RegistryCompilerPass.php @@ -34,6 +34,10 @@ public function __construct( */ public function process(ContainerBuilder $container): void { + if (\in_array(null, [$this->registry, $this->tag, $this->method], true)) { + throw new \LogicException('The registry, tag and method of the RegistryCompilerPass must be defined'); + } + if (!$container->has($this->registry)) { return; } diff --git a/src/Filesystem/CsvResource.php b/src/Filesystem/CsvResource.php index 4fc24d2d..5220693f 100644 --- a/src/Filesystem/CsvResource.php +++ b/src/Filesystem/CsvResource.php @@ -156,6 +156,8 @@ public function isEndOfFile(): bool /** * Warning, this function will return exactly the same value as the fgetcsv() function. * + * @param int<0, max>|null $length + * * @return list|false */ public function readRaw(?int $length = null): array|false @@ -167,6 +169,8 @@ public function readRaw(?int $length = null): array|false } /** + * @param int<0, max>|null $length + * * @return array|null */ public function readLine(?int $length = null): ?array @@ -259,7 +263,12 @@ public function tell(): int { $this->assertOpened(); - return ftell($this->handler); + $position = ftell($this->handler); + if (false === $position) { + throw new \RuntimeException("Unable to get the position in {$this->getResourceName()}"); + } + + return $position; } public function seek(int $offset): int @@ -313,12 +322,14 @@ protected function parseHeaders(?array $headers = null): array // If headers are not passed in the constructor but file is readable, try to read headers from file if (null === $headers) { $autoHeaders = $this->readRaw(); - if (false === $autoHeaders || [] === $autoHeaders) { + // A blank line is read as [null] + if (false === $autoHeaders || [null] === $autoHeaders) { throw new \UnexpectedValueException("Unable to read headers for {$this->getResourceName()}"); } + $autoHeaders = array_map(strval(...), $autoHeaders); // Remove BOM if any $bom = pack('H*', 'EFBBBF'); - $autoHeaders[0] = preg_replace("/^{$bom}/", '', (string) $autoHeaders[0]); + $autoHeaders[0] = (string) preg_replace("/^{$bom}/", '', $autoHeaders[0]); return $autoHeaders; } diff --git a/src/Filesystem/FileStreamInterface.php b/src/Filesystem/FileStreamInterface.php index e319df39..78f750fc 100644 --- a/src/Filesystem/FileStreamInterface.php +++ b/src/Filesystem/FileStreamInterface.php @@ -28,6 +28,8 @@ public function getLineNumber(): int; public function isEndOfFile(): bool; /** + * @param int<0, max>|null $length + * * @return array|null */ public function readLine(?int $length = null): ?array; diff --git a/src/Filesystem/JsonStreamFile.php b/src/Filesystem/JsonStreamFile.php index 1253943d..18d0b66a 100644 --- a/src/Filesystem/JsonStreamFile.php +++ b/src/Filesystem/JsonStreamFile.php @@ -90,6 +90,8 @@ public function isEndOfFile(): bool /** * Return an array containing current data and moving the file pointer. * + * @param int<0, max>|null $length + * * @return array|null * * @throws \UnexpectedValueException if the line decodes to a scalar value diff --git a/src/Model/ProcessState.php b/src/Model/ProcessState.php index 13ef03d1..d34c2b29 100644 --- a/src/Model/ProcessState.php +++ b/src/Model/ProcessState.php @@ -280,7 +280,7 @@ public function isResolved(): bool */ public function getContext(): array { - return $this->context; + return $this->context ?? []; } /** @@ -303,9 +303,10 @@ public function getContextualizedOptions(): ?array if (!$this->contextualizedOptions) { $options = $this->getTaskConfiguration() ->getOptions(); + $this->contextualOptionResolver ??= new ContextualOptionResolver(); $this->contextualizedOptions = $this->contextualOptionResolver->contextualizeOptions( $options, - $this->context + $this->getContext() ); } diff --git a/src/Model/SubprocessInstance.php b/src/Model/SubprocessInstance.php index f52b94f0..18b074af 100644 --- a/src/Model/SubprocessInstance.php +++ b/src/Model/SubprocessInstance.php @@ -64,11 +64,14 @@ public function __construct( */ public function buildProcess(): static { - $pathFinder = new PhpExecutableFinder(); + $phpBinary = (new PhpExecutableFinder())->find(); + if (false === $phpBinary) { + throw new \RuntimeException('Unable to find the PHP executable'); + } $arguments = [ 'nohup', - $pathFinder->find(), + $phpBinary, $this->consolePath, '--env='.$this->environment, 'cleverage:process:execute', diff --git a/src/Task/AbstractIterableOutputTask.php b/src/Task/AbstractIterableOutputTask.php index b756d049..871b2489 100644 --- a/src/Task/AbstractIterableOutputTask.php +++ b/src/Task/AbstractIterableOutputTask.php @@ -29,10 +29,14 @@ abstract class AbstractIterableOutputTask extends AbstractConfigurableTask imple public function execute(ProcessState $state): void { $this->handleIteratorFromInput($state); + $iterator = $this->iterator; + if (!$iterator instanceof \Iterator) { + throw new \LogicException('No iterator initialized'); + } - if ($this->iterator->valid()) { - $state->addErrorContextValue('iterator_key', $this->iterator->key()); - $state->setOutput($this->iterator->current()); + if ($iterator->valid()) { + $state->addErrorContextValue('iterator_key', $iterator->key()); + $state->setOutput($iterator->current()); } else { $state->setSkipped(true); $this->iterator = null; diff --git a/src/Task/File/Csv/CsvReaderTask.php b/src/Task/File/Csv/CsvReaderTask.php index 635041f4..f976ddca 100644 --- a/src/Task/File/Csv/CsvReaderTask.php +++ b/src/Task/File/Csv/CsvReaderTask.php @@ -40,13 +40,17 @@ public function execute(ProcessState $state): void if (!$this->csv instanceof CsvFile) { $this->initFile($state); } - $lineNumber = $this->csv->getLineNumber(); - $output = $this->csv->readLine(); + $csv = $this->csv; + if (!$csv instanceof CsvFile) { + throw new \LogicException('No CSV File initialized'); + } + $lineNumber = $csv->getLineNumber(); + $output = $csv->readLine(); if (null === $output) { if ($this->getOption($state, 'log_empty_lines')) { $logContext = [ - 'csv_file' => $this->csv->getFilePath(), + 'csv_file' => $csv->getFilePath(), 'csv_line' => $lineNumber, ]; $this->logger->warning("Empty line detected at line: {$lineNumber}", $logContext); @@ -55,7 +59,7 @@ public function execute(ProcessState $state): void $state->setSkipped(true); } - $state->addErrorContextValue('csv_file', $this->csv->getFilePath()); + $state->addErrorContextValue('csv_file', $csv->getFilePath()); $state->addErrorContextValue('csv_line', $lineNumber); $state->setOutput($output); } diff --git a/src/Task/File/Csv/CsvWriterTask.php b/src/Task/File/Csv/CsvWriterTask.php index c0e1a922..691bde92 100644 --- a/src/Task/File/Csv/CsvWriterTask.php +++ b/src/Task/File/Csv/CsvWriterTask.php @@ -96,7 +96,8 @@ protected function getHeaders(ProcessState $state, array $options): ?array { $headers = $options['headers']; if (null === $headers) { - return array_keys($state->getInput()); + // Keys of a list are integers: the CSV output is the same with their string value + return array_map(strval(...), array_keys($state->getInput())); } return $headers; diff --git a/src/Task/File/FolderBrowserTask.php b/src/Task/File/FolderBrowserTask.php index 540e2c61..728a61c4 100644 --- a/src/Task/File/FolderBrowserTask.php +++ b/src/Task/File/FolderBrowserTask.php @@ -51,8 +51,9 @@ public function execute(ProcessState $state): void $this->files = $finder->in($options['folder_path'])->sortByName()->getIterator(); $this->files->rewind(); } + $files = $this->getFilesIterator(); - if (!$this->files->valid()) { + if (!$files->valid()) { $this->logger->log($options['empty_log_level'], "No item found in path {$options['folder_path']}"); $state->setSkipped(true); $state->setErrorOutput($options['folder_path']); @@ -61,7 +62,7 @@ public function execute(ProcessState $state): void return; } /** @var SplFileInfo $fileInfo */ - $fileInfo = $this->files->current(); + $fileInfo = $files->current(); $filePath = $fileInfo->getPathname(); $state->addErrorContextValue('current_file_path', $filePath); $state->setOutput($filePath); @@ -77,10 +78,11 @@ public function next(ProcessState $state): bool if (!$this->files) { return false; } - $this->files->next(); + $files = $this->getFilesIterator(); + $files->next(); $state->removeErrorContext('current_file_path'); - if (!$this->files->valid()) { + if (!$files->valid()) { // Reset the iterator to allow the following iteration $this->files = null; @@ -126,4 +128,19 @@ static function (Options $options, $value) { ] ); } + + /** + * @return \Iterator + */ + private function getFilesIterator(): \Iterator + { + if (\is_array($this->files)) { + $this->files = new \ArrayIterator($this->files); + } + if (!$this->files instanceof \Iterator) { + throw new \LogicException('No folder browsed'); + } + + return $this->files; + } } diff --git a/src/Task/File/JsonStream/JsonStreamReaderTask.php b/src/Task/File/JsonStream/JsonStreamReaderTask.php index e1924b0f..946a48a3 100644 --- a/src/Task/File/JsonStream/JsonStreamReaderTask.php +++ b/src/Task/File/JsonStream/JsonStreamReaderTask.php @@ -45,6 +45,9 @@ public function execute(ProcessState $state): void public function next(ProcessState $state): bool { + if (!$this->file instanceof JsonStreamFile) { + return false; + } $eof = $this->file->isEndOfFile(); if ($eof) { $this->file = null; diff --git a/src/Task/IterableBatchTask.php b/src/Task/IterableBatchTask.php index 692e5666..ec247ccc 100644 --- a/src/Task/IterableBatchTask.php +++ b/src/Task/IterableBatchTask.php @@ -48,6 +48,7 @@ public function initialize(ProcessState $state): void public function flush(ProcessState $state): void { $this->flushMode = true; + $this->outputQueue ??= new \SplQueue(); if ($this->outputQueue->isEmpty()) { $state->setSkipped(true); } else { @@ -58,6 +59,7 @@ public function flush(ProcessState $state): void public function execute(ProcessState $state): void { $batchCount = $this->getOption($state, 'batch_count'); + $this->outputQueue ??= new \SplQueue(); // Register new input if (!$this->flushMode) { @@ -65,7 +67,7 @@ public function execute(ProcessState $state): void } // Detect flushing - if (null !== $batchCount && ($this->outputQueue instanceof \SplQueue ? \count($this->outputQueue) : 0) >= $batchCount) { + if (null !== $batchCount && \count($this->outputQueue) >= $batchCount) { $this->flushMode = true; } diff --git a/src/Task/Process/ProcessLauncherTask.php b/src/Task/Process/ProcessLauncherTask.php index 692016fa..82cdb58d 100644 --- a/src/Task/Process/ProcessLauncherTask.php +++ b/src/Task/Process/ProcessLauncherTask.php @@ -222,8 +222,8 @@ function (Options $options, $value) { $resolver->setAllowedTypes('process_options', ['array']); $resolver->setNormalizer( 'process_options', - static function (Options $options, $value): array { - if (!empty($value)) { + static function (Options $options, array $value): array { + if ([] !== $value) { // Todo deprecation trigger throw new \InvalidArgumentException('Deprecated option, please contact support for help'); } diff --git a/src/Task/Reporting/AdvancedStatCounterTask.php b/src/Task/Reporting/AdvancedStatCounterTask.php index ddaff0e3..a4a87ce0 100644 --- a/src/Task/Reporting/AdvancedStatCounterTask.php +++ b/src/Task/Reporting/AdvancedStatCounterTask.php @@ -52,7 +52,7 @@ public function execute(ProcessState $state): void } ++$this->counter; if (0 === $this->counter % $this->getOption($state, 'show_every')) { - $diff = $now->diff($this->lastUpdate); + $diff = $now->diff($this->lastUpdate ?? $now); $fullText = "Last iteration {$diff->format('%H:%I:%S')} ago"; $items = $this->getOption($state, 'num_items') * $this->counter; $seconds = $now->getTimestamp() - $this->startedAt->getTimestamp(); diff --git a/src/Transformer/CachedTransformer.php b/src/Transformer/CachedTransformer.php index 9cb226e7..eb6ea962 100644 --- a/src/Transformer/CachedTransformer.php +++ b/src/Transformer/CachedTransformer.php @@ -109,6 +109,8 @@ public function getCode(): string /** * @param array $options + * + * @return string|false */ protected function generateCacheKey(string $cacheKeyRoot, mixed $value, array $options): bool|string { diff --git a/src/Transformer/ConditionTrait.php b/src/Transformer/ConditionTrait.php index 9e282e8e..a6666a5b 100644 --- a/src/Transformer/ConditionTrait.php +++ b/src/Transformer/ConditionTrait.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Transformer; use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; /** @@ -161,7 +162,8 @@ protected function getValue(mixed $input, string $key): mixed { if ('' === $key) { $currentValue = $input; - } elseif ((\is_array($input) || \is_object($input)) && $this->accessor->isReadable($input, $key)) { + } elseif ((\is_array($input) || \is_object($input)) + && ($this->accessor ??= PropertyAccess::createPropertyAccessor())->isReadable($input, $key)) { $currentValue = $this->accessor->getValue($input, $key); } else { $currentValue = null; diff --git a/src/Transformer/GenericTransformer.php b/src/Transformer/GenericTransformer.php index 11e4d29a..9a2a6bb9 100644 --- a/src/Transformer/GenericTransformer.php +++ b/src/Transformer/GenericTransformer.php @@ -86,7 +86,7 @@ public function configureInitialOptions(OptionsResolver $resolver): void */ public function configureOptions(OptionsResolver $resolver): void { - foreach ($this->contextualOptions as $option => $optionConfig) { + foreach ($this->contextualOptions ?? [] as $option => $optionConfig) { $resolver->setDefined($option); if (null !== $optionConfig['default'] || $optionConfig['default_is_null']) { $resolver->setDefault($option, $optionConfig['default']); @@ -104,7 +104,7 @@ public function configureOptions(OptionsResolver $resolver): void throw new \InvalidArgumentException('Transformers option should not be used at this point'); } - $transformerOptions = $this->normalizeTransformerOptions($options, $this->preconfiguredTransformerOptions); + $transformerOptions = $this->normalizeTransformerOptions($options, $this->preconfiguredTransformerOptions ?? []); return $this->normalizeTransformers($options, $transformerOptions); }); @@ -120,6 +120,10 @@ public function transform(mixed $value, array $options = []): mixed public function getCode(): string { + if (null === $this->transformerCode) { + throw new \LogicException('The generic transformer is not initialized'); + } + return $this->transformerCode; } @@ -134,7 +138,7 @@ public function getCode(): string public function normalizeTransformerOptions(Options $options, array $transformerOptions): array { $contextualizedOptionValues = []; - foreach ($this->contextualOptions as $contextualOption => $contextualOptionConfig) { + foreach ($this->contextualOptions ?? [] as $contextualOption => $contextualOptionConfig) { // An optional contextual option without default value is replaced by null when not provided $contextualizedOptionValues[$contextualOption] = $options->offsetExists($contextualOption) ? $options[$contextualOption] diff --git a/src/Transformer/String/SlugifyTransformer.php b/src/Transformer/String/SlugifyTransformer.php index f3c02275..81180ed3 100644 --- a/src/Transformer/String/SlugifyTransformer.php +++ b/src/Transformer/String/SlugifyTransformer.php @@ -31,6 +31,9 @@ public function transform(mixed $value, array $options = []): string /** @var \Transliterator $transliterator */ $transliterator = $options['transliterator']; $string = $transliterator->transliterate($value); + if (false === $string) { + throw new \UnexpectedValueException("Unable to transliterate the value: {$transliterator->getErrorMessage()}"); + } return trim( (string) preg_replace( diff --git a/src/Transformer/TransformerTrait.php b/src/Transformer/TransformerTrait.php index 34b0a2d8..f463cba4 100644 --- a/src/Transformer/TransformerTrait.php +++ b/src/Transformer/TransformerTrait.php @@ -38,7 +38,7 @@ public function normalizeTransformers(Options $options, array $transformers): ar foreach ($transformers as $origTransformerCode => $transformerOptions) { $transformerOptionsResolver = new OptionsResolver(); $transformerCode = $this->getCleanedTransfomerCode($origTransformerCode); - $transformer = $this->transformerRegistry->getTransformer($transformerCode); + $transformer = $this->getTransformerRegistry()->getTransformer($transformerCode); $transformerOptions = $this->checkTransformerOptions($transformerOptions, $origTransformerCode); if ($transformer instanceof ConfigurableTransformerInterface) { $transformer->configureOptions($transformerOptionsResolver); @@ -94,7 +94,7 @@ protected function getCleanedTransfomerCode(string $transformerCode): string { $match = preg_match('/^([^#]+)#.+$/', $transformerCode, $parts); - if (1 === $match && $this->transformerRegistry->hasTransformer($parts[1])) { + if (1 === $match && $this->getTransformerRegistry()->hasTransformer($parts[1])) { return $parts[1]; } @@ -128,4 +128,13 @@ private function checkTransformerOptions(mixed $transformerOptions, string $tran throw new \InvalidArgumentException("Options for transformer {$transformerCode} are invalid : found {$type}, expected array or null"); } + + private function getTransformerRegistry(): TransformerRegistry + { + if (!$this->transformerRegistry instanceof TransformerRegistry) { + throw new \LogicException('No transformer registry defined'); + } + + return $this->transformerRegistry; + } } diff --git a/src/Transformer/Xml/XpathEvaluatorTransformer.php b/src/Transformer/Xml/XpathEvaluatorTransformer.php index 87be9f8d..5acbf351 100644 --- a/src/Transformer/Xml/XpathEvaluatorTransformer.php +++ b/src/Transformer/Xml/XpathEvaluatorTransformer.php @@ -109,6 +109,9 @@ public function getCode(): string public function buildXpath(\DOMNode $node): \DOMXPath { $doc = $node instanceof \DOMDocument ? $node : $node->ownerDocument; + if (!$doc instanceof \DOMDocument) { + throw new \UnexpectedValueException('The node does not belong to a document'); + } return new \DOMXPath($doc); } @@ -118,12 +121,25 @@ public function buildXpath(\DOMNode $node): \DOMXPath */ public function query(\DOMXPath $xpath, string $query, \DOMNode $node, array $options): mixed { - $nodeList = $xpath->query($query, $node); + $previousUseErrors = libxml_use_internal_errors(true); + libxml_clear_errors(); + try { + $nodeList = $xpath->query($query, $node); + $errors = libxml_get_errors(); + } finally { + libxml_clear_errors(); + libxml_use_internal_errors($previousUseErrors); + } + if (false === $nodeList) { + $messages = array_map(static fn (\LibXMLError $error): string => trim($error->message), $errors); + + throw new \UnexpectedValueException(\sprintf("Invalid xpath query '%s': %s", $query, [] !== $messages ? implode('; ', $messages) : 'unknown error')); + } $results = iterator_to_array($nodeList); // Convert results to text if ($options['unwrap_value']) { - $results = array_map(static function (\DOMNode $item) use ($query): string { + $results = array_map(static function (\DOMNode|\DOMNameSpaceNode $item) use ($query): string { if ($item instanceof \DOMAttr) { return $item->value; } diff --git a/tests/DependencyInjection/Compiler/RegistryCompilerPassTest.php b/tests/DependencyInjection/Compiler/RegistryCompilerPassTest.php new file mode 100644 index 00000000..9538c49d --- /dev/null +++ b/tests/DependencyInjection/Compiler/RegistryCompilerPassTest.php @@ -0,0 +1,52 @@ +register('registry', \ArrayObject::class); + $container->register('service', \stdClass::class)->addTag('tag'); + + (new RegistryCompilerPass('registry', 'tag', 'append'))->process($container); + + self::assertEquals([['append', [new Reference('service')]]], $container->getDefinition('registry')->getMethodCalls()); + } + + public function testMissingRegistryIsIgnored(): void + { + $container = new ContainerBuilder(); + $container->register('service', \stdClass::class)->addTag('tag'); + + (new RegistryCompilerPass('registry', 'tag', 'append'))->process($container); + + self::assertFalse($container->has('registry')); + } + + public function testUndefinedConfigurationThrows(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('The registry, tag and method of the RegistryCompilerPass must be defined'); + + (new RegistryCompilerPass())->process(new ContainerBuilder()); + } +} diff --git a/tests/Filesystem/CsvResourceTest.php b/tests/Filesystem/CsvResourceTest.php new file mode 100644 index 00000000..11cd46e3 --- /dev/null +++ b/tests/Filesystem/CsvResourceTest.php @@ -0,0 +1,57 @@ +createResource("\xEF\xBB\xBFa;b\n1;2\n"), ';'); + + self::assertSame(['a', 'b'], $csv->getHeaders()); + self::assertSame(['a' => '1', 'b' => '2'], $csv->readLine()); + } + + public function testBlankFirstLineIsRejected(): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Unable to read headers'); + + new CsvResource($this->createResource("\na;b\n"), ';'); + } + + public function testTellReturnsThePositionInTheResource(): void + { + $csv = new CsvResource($this->createResource("a;b\n1;2\n"), ';'); + + self::assertSame(4, $csv->tell()); + } + + /** + * @return resource + */ + private function createResource(string $content) + { + $resource = fopen('php://memory', 'w+'); + self::assertIsResource($resource); + fwrite($resource, $content); + rewind($resource); + + return $resource; + } +} diff --git a/tests/Model/ProcessStateTest.php b/tests/Model/ProcessStateTest.php index 1453e2f5..0fc69490 100644 --- a/tests/Model/ProcessStateTest.php +++ b/tests/Model/ProcessStateTest.php @@ -14,6 +14,8 @@ namespace CleverAge\ProcessBundle\Tests\Model; use CleverAge\ProcessBundle\Configuration\ProcessConfiguration; +use CleverAge\ProcessBundle\Configuration\TaskConfiguration; +use CleverAge\ProcessBundle\Context\ContextualOptionResolver; use CleverAge\ProcessBundle\Model\ProcessHistory; use CleverAge\ProcessBundle\Model\ProcessState; use PHPUnit\Framework\Attributes\DataProvider; @@ -22,6 +24,8 @@ #[\PHPUnit\Framework\Attributes\CoversClass(ProcessState::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessConfiguration::class)] #[\PHPUnit\Framework\Attributes\UsesClass(ProcessHistory::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(TaskConfiguration::class)] +#[\PHPUnit\Framework\Attributes\UsesClass(ContextualOptionResolver::class)] class ProcessStateTest extends TestCase { /** @@ -59,6 +63,20 @@ public function testRemoveErrorContext(): void self::assertSame(['kept' => 'foo'], $state->getErrorContext()); } + public function testContextIsEmptyUntilDefined(): void + { + self::assertSame([], $this->createState()->getContext()); + } + + public function testContextualizedOptionsUseADefaultResolver(): void + { + $state = $this->createState(); + $state->setContext(['bar' => 'baz']); + $state->setTaskConfiguration(new TaskConfiguration('task', 'service', ['foo' => '{{ bar }}'])); + + self::assertSame(['foo' => 'baz'], $state->getContextualizedOptions()); + } + private function createState(): ProcessState { $processConfiguration = new ProcessConfiguration('test', []); diff --git a/tests/Task/File/JsonStream/JsonStreamReaderTaskTest.php b/tests/Task/File/JsonStream/JsonStreamReaderTaskTest.php index c1660510..8259e237 100644 --- a/tests/Task/File/JsonStream/JsonStreamReaderTaskTest.php +++ b/tests/Task/File/JsonStream/JsonStreamReaderTaskTest.php @@ -211,6 +211,11 @@ public function testThrowsOnInvalidOptions(array $options): void $task->initialize($state); } + public function testNextWithoutFileReturnsFalse(): void + { + self::assertFalse((new JsonStreamReaderTask())->next($this->createState([]))); + } + /** * Mimics the ProcessManager loop over an iterable task and returns the non-skipped outputs. * diff --git a/tests/Task/IterableBatchTaskTest.php b/tests/Task/IterableBatchTaskTest.php index 8010d97b..36e9e23f 100644 --- a/tests/Task/IterableBatchTaskTest.php +++ b/tests/Task/IterableBatchTaskTest.php @@ -52,6 +52,16 @@ public function testNullBatchCountOnlyOutputsOnFlush(): void self::assertSame(['a', 'b', 'c'], $this->flush($task, $state)); } + public function testFlushWithoutInitializationIsSkipped(): void + { + $task = new IterableBatchTask(new NullLogger()); + $state = $this->createState(IterableBatchTask::class, []); + + $task->flush($state); + + self::assertTrue($state->isSkipped()); + } + /** * @param array $options * diff --git a/tests/Task/Reporting/LoggerTaskTest.php b/tests/Task/Reporting/LoggerTaskTest.php index d13bd61a..07a927d3 100644 --- a/tests/Task/Reporting/LoggerTaskTest.php +++ b/tests/Task/Reporting/LoggerTaskTest.php @@ -161,8 +161,8 @@ private function execute(array $options, mixed $input, array $context = []): Pro private function createTask(): LoggerTask { - $logger = new class(function (array $record): void { - $this->records[] = $record; + $logger = new class(function (mixed $level, string $message, array $context): void { + $this->records[] = ['level' => $level, 'message' => $message, 'context' => $context]; }) extends AbstractLogger { public function __construct(private readonly \Closure $onLog) { @@ -170,7 +170,7 @@ public function __construct(private readonly \Closure $onLog) public function log($level, string|\Stringable $message, array $context = []): void { - ($this->onLog)(['level' => $level, 'message' => (string) $message, 'context' => $context]); + ($this->onLog)($level, (string) $message, $context); } }; diff --git a/tests/Task/Validation/ValidatorTaskTest.php b/tests/Task/Validation/ValidatorTaskTest.php index 9c9e8829..35a83085 100644 --- a/tests/Task/Validation/ValidatorTaskTest.php +++ b/tests/Task/Validation/ValidatorTaskTest.php @@ -261,8 +261,8 @@ private function execute(array $options, mixed $input): ProcessState private function createTask(): ValidatorTask { - $logger = new class(function (array $record): void { - $this->records[] = $record; + $logger = new class(function (mixed $level, string $message, array $context): void { + $this->records[] = ['level' => $level, 'message' => $message, 'context' => $context]; }) extends AbstractLogger { public function __construct(private readonly \Closure $onLog) { @@ -270,7 +270,7 @@ public function __construct(private readonly \Closure $onLog) public function log($level, string|\Stringable $message, array $context = []): void { - ($this->onLog)(['level' => $level, 'message' => (string) $message, 'context' => $context]); + ($this->onLog)($level, (string) $message, $context); } }; diff --git a/tests/Transformer/GenericTransformerTest.php b/tests/Transformer/GenericTransformerTest.php index 001a9183..fed7100c 100644 --- a/tests/Transformer/GenericTransformerTest.php +++ b/tests/Transformer/GenericTransformerTest.php @@ -71,6 +71,16 @@ public function testOptionalOptionWithoutDefaultIsNullWhenOmitted(): void $this->assertSame('ello', $transformer->transform('hello', $options)); } + public function testGetCodeRequiresInitialization(): void + { + $transformer = new GenericTransformer(new ContextualOptionResolver(), new TransformerRegistry()); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('The generic transformer is not initialized'); + + $transformer->getCode(); + } + /** * Generic transformer applying substr($value, {{ offset }}, {{ length }}). * diff --git a/tests/Transformer/String/SlugifyTransformerTest.php b/tests/Transformer/String/SlugifyTransformerTest.php index aaae8159..d21b13af 100644 --- a/tests/Transformer/String/SlugifyTransformerTest.php +++ b/tests/Transformer/String/SlugifyTransformerTest.php @@ -78,6 +78,16 @@ public function testGetCodeReturnsCorrectCode(): void $this->assertSame('slugify', (new SlugifyTransformer())->getCode()); } + public function testValueThatCannotBeTransliteratedThrows(): void + { + $transformer = new SlugifyTransformer(); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('Unable to transliterate the value'); + + $transformer->transform("a\xff", $this->resolveOptions($transformer)); + } + /** * @param array $options * diff --git a/tests/Transformer/TransformerTraitHolder.php b/tests/Transformer/TransformerTraitHolder.php new file mode 100644 index 00000000..a6badc95 --- /dev/null +++ b/tests/Transformer/TransformerTraitHolder.php @@ -0,0 +1,57 @@ +transformerRegistry = $transformerRegistry; + } + + public function cleanCode(string $code): string + { + return $this->getCleanedTransfomerCode($code); + } + + /** + * @param array $transformers + * + * @return array + */ + public function resolve(array $transformers): array + { + $resolver = new OptionsResolver(); + $this->configureTransformersOptions($resolver); + + return $resolver->resolve(['transformers' => $transformers])['transformers']; + } + + /** + * @param array $transformers + */ + public function apply(array $transformers, mixed $value): mixed + { + return $this->applyTransformers($transformers, $value); + } +} diff --git a/tests/Transformer/TransformerTraitTest.php b/tests/Transformer/TransformerTraitTest.php index bfe6f572..335429a2 100644 --- a/tests/Transformer/TransformerTraitTest.php +++ b/tests/Transformer/TransformerTraitTest.php @@ -19,7 +19,6 @@ use CleverAge\ProcessBundle\Transformer\TransformerTrait; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Symfony\Component\OptionsResolver\OptionsResolver; #[\PHPUnit\Framework\Attributes\CoversTrait(TransformerTrait::class)] #[\PHPUnit\Framework\Attributes\UsesClass(TransformerRegistry::class)] @@ -67,44 +66,19 @@ public function testEmptySuffixIsAnUnknownTransformer(): void $this->createHolder()->resolve(['callback#' => ['callback' => 'trim']]); } - private function createHolder(): object + public function testMissingRegistryThrows(): void { - $registry = new TransformerRegistry(); - $registry->addTransformer(new CallbackTransformer()); - - return new class($registry) { - use TransformerTrait; - - public function __construct(TransformerRegistry $transformerRegistry) - { - $this->transformerRegistry = $transformerRegistry; - } - - public function cleanCode(string $code): string - { - return $this->getCleanedTransfomerCode($code); - } + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('No transformer registry defined'); - /** - * @param array $transformers - * - * @return array - */ - public function resolve(array $transformers): array - { - $resolver = new OptionsResolver(); - $this->configureTransformersOptions($resolver); + (new TransformerTraitHolder())->cleanCode('callback#1'); + } - return $resolver->resolve(['transformers' => $transformers])['transformers']; - } + private function createHolder(): TransformerTraitHolder + { + $registry = new TransformerRegistry(); + $registry->addTransformer(new CallbackTransformer()); - /** - * @param array $transformers - */ - public function apply(array $transformers, mixed $value): mixed - { - return $this->applyTransformers($transformers, $value); - } - }; + return new TransformerTraitHolder($registry); } } diff --git a/tests/Transformer/Xml/XpathEvaluatorTransformerTest.php b/tests/Transformer/Xml/XpathEvaluatorTransformerTest.php index cb1eb488..9204c870 100644 --- a/tests/Transformer/Xml/XpathEvaluatorTransformerTest.php +++ b/tests/Transformer/Xml/XpathEvaluatorTransformerTest.php @@ -107,4 +107,41 @@ public function testGetCodeReturnsCorrectCode(): void $this->assertEquals('xpath_evaluator', $code); } + + public function testInvalidQueryThrows(): void + { + $domDocument = new \DOMDocument(); + $domDocument->loadXML('ok'); + $transformer = new XpathEvaluatorTransformer(); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Invalid xpath query '//[': Invalid expression"); + + $transformer->query($transformer->buildXpath($domDocument), '//[', $domDocument, ['unwrap_value' => false, 'single_result' => false]); + } + + public function testNamespaceNodeCannotBeUnwrapped(): void + { + $domDocument = new \DOMDocument(); + $domDocument->loadXML(''); + $transformer = new XpathEvaluatorTransformer(); + + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage("Xpath result cannot be unwrapped for query '/a/namespace::x'"); + + $transformer->query( + $transformer->buildXpath($domDocument), + '/a/namespace::x', + $domDocument, + ['unwrap_value' => true, 'single_result' => true, 'ignore_missing' => false], + ); + } + + public function testNodeWithoutDocumentThrows(): void + { + $this->expectException(\UnexpectedValueException::class); + $this->expectExceptionMessage('The node does not belong to a document'); + + (new XpathEvaluatorTransformer())->buildXpath(new \DOMElement('a')); + } }