diff --git a/CHANGELOG.md b/CHANGELOG.md index cdb6fbbe..815f2c3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Latest ------ ## Changes +* [#317](https://github.com/cleverage/process-bundle/issues/317) The bundle throws exceptions implementing `ProcessExceptionInterface` instead of raw SPL exceptions (124 `throw`): new `Exception\UnexpectedValueException`, `RuntimeException`, `InvalidArgumentException` and `LogicException`, extending the SPL exceptions thrown before (same messages, the existing `catch` keep working). All the errors of the bundle can be caught with `ProcessExceptionInterface`, except the exceptions of the Symfony components. Update documentation, add tests. * [#311](https://github.com/cleverage/process-bundle/issues/311) Deprecate the `cleverage_process.event_listener.data_queue` service and `DataQueueEventListener` (it keeps a copy of the `ProcessState` of every `cleverage_process.data_queue` event in memory, without limit): injecting or fetching the service triggers a deprecation, they will be removed in v6.0. Write your own listener of the event dispatched by the `event_dispatcher` task. Update documentation, add tests. * [#312](https://github.com/cleverage/process-bundle/issues/312) Add read-only interfaces for the process manager and the registries, implemented by the existing classes and autowired by their interface: `ProcessManagerInterface` (`execute()`), `ProcessConfigurationRegistryInterface` (`getProcessConfiguration()`, `getProcessConfigurations()`, `hasProcessConfiguration()`), `TransformerRegistryInterface` (`getTransformer()`, `getTransformers()`, `hasTransformer()`) and `TaskRegistryInterface` (`getTask()`). Type your services on them: the classes will be `final` in v6.0 (the services of the bundle will then be typed on the interfaces). Update documentation, add tests. * [#310](https://github.com/cleverage/process-bundle/issues/310) Process configuration tree: a task `error_strategy` other than `skip` or `stop` is deprecated (notice when the container is compiled; it was accepted and the process failed with "Unknown error strategy" when the task failed), it will be rejected in v6.0. The process `public` key is a boolean node: a non-boolean value is rejected when the container is compiled, instead of a `TypeError` when the configuration is built. Describe the nodes of the process, task and generic transformer configurations (`config:dump-reference clever_age_process`). Update documentation, add tests. diff --git a/docs/04-advanced_workflow.md b/docs/04-advanced_workflow.md index 2e6720c8..0c107e8e 100644 --- a/docs/04-advanced_workflow.md +++ b/docs/04-advanced_workflow.md @@ -27,6 +27,12 @@ Note that a task error handled by the `stop` strategy does not surface as the or throws a `CleverAge\ProcessBundle\Exception\ProcessFailedException` (a `\RuntimeException`), whose message contains the process code, the task code and the original message. The original exception is available with `getPrevious()`. +The exceptions thrown by the bundle implement `CleverAge\ProcessBundle\Exception\ProcessExceptionInterface` (since 5.4 for +the `UnexpectedValueException`, `RuntimeException`, `InvalidArgumentException` and `LogicException` of the same +namespace, which extend the SPL exceptions thrown before), so that they can all be caught at once. Not concerned: the +exceptions of the Symfony components (e.g. `InvalidOptionsException` for an invalid task option) and the ones of your +own tasks and transformers. + ### Executing a process from PHP The process manager service (`cleverage_process.manager.process`, private) can be autowired by its interface, diff --git a/src/Command/ExecuteProcessCommand.php b/src/Command/ExecuteProcessCommand.php index e2739a5d..95418fe8 100644 --- a/src/Command/ExecuteProcessCommand.php +++ b/src/Command/ExecuteProcessCommand.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Command; use CleverAge\ProcessBundle\Event\ConsoleProcessEvent; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; use CleverAge\ProcessBundle\Filesystem\JsonStreamFile; use CleverAge\ProcessBundle\Manager\ProcessManager; use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry; @@ -125,7 +126,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', $contextValue)); } $context[$parts[1]] = $parser->parse($parts[2]); } @@ -150,7 +151,7 @@ protected function handleOutputData(mixed $data, InputInterface $input, OutputIn } elseif (self::OUTPUT_FORMAT_JSON === $input->getOption('output-format')) { $output->writeln(json_encode($data, \JSON_THROW_ON_ERROR)); } else { - throw new \InvalidArgumentException(\sprintf("Cannot handle data output with format '%s'", $input->getOption('output-format'))); + throw new InvalidArgumentException(\sprintf("Cannot handle data output with format '%s'", $input->getOption('output-format'))); } } } elseif (self::OUTPUT_FORMAT_JSON === $input->getOption('output-format')) { @@ -165,7 +166,7 @@ protected function handleOutputData(mixed $data, InputInterface $input, OutputIn $output->writeln(\sprintf("Output stored in '%s'", $input->getOption('output'))); } } else { - throw new \InvalidArgumentException(\sprintf("Cannot handle data output with format '%s'", $input->getOption('output-format'))); + throw new InvalidArgumentException(\sprintf("Cannot handle data output with format '%s'", $input->getOption('output-format'))); } } } diff --git a/src/Command/ProcessHelpCommand.php b/src/Command/ProcessHelpCommand.php index c9ba520b..af865943 100644 --- a/src/Command/ProcessHelpCommand.php +++ b/src/Command/ProcessHelpCommand.php @@ -15,6 +15,8 @@ use CleverAge\ProcessBundle\Configuration\ProcessConfiguration; use CleverAge\ProcessBundle\Configuration\TaskConfiguration; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\BlockingTaskInterface; use CleverAge\ProcessBundle\Model\FlushableTaskInterface; use CleverAge\ProcessBundle\Model\IterableTaskInterface; @@ -185,7 +187,7 @@ protected function findBestNextTask( } if ([] === $taskCandidates) { - throw new \UnexpectedValueException('Cannot find a task to output'); + throw new UnexpectedValueException('Cannot find a task to output'); } // Try to find the task the most on the right @@ -198,7 +200,7 @@ protected function findBestNextTask( // Should never be non-numeric... if (!is_numeric($key)) { - throw new \UnexpectedValueException('Invalid key type'); + throw new UnexpectedValueException('Invalid key type'); } $weight += $key; } @@ -408,7 +410,7 @@ static function ($taskCode, $i) use ($gapBranches, $origin, $final, $branches): array_shift($nextTasks); $origin = array_search($taskCode, $branches, true); if (false === $origin) { - throw new \UnexpectedValueException("Task '{$taskCode}' is not in any branch"); + throw new UnexpectedValueException("Task '{$taskCode}' is not in any branch"); } $expandBranches = []; foreach ($nextTasks as $nextTask) { @@ -502,7 +504,7 @@ protected function writeBranches( } elseif (\is_callable($char)) { $str = $char($branchTask, $i); } else { - throw new \InvalidArgumentException('Char must be string|callable'); + throw new InvalidArgumentException('Char must be string|callable'); } } elseif (null !== $branchTask) { $str = self::CHAR_DOWN; diff --git a/src/DependencyInjection/Compiler/RegistryCompilerPass.php b/src/DependencyInjection/Compiler/RegistryCompilerPass.php index bf684e40..954f5ad3 100644 --- a/src/DependencyInjection/Compiler/RegistryCompilerPass.php +++ b/src/DependencyInjection/Compiler/RegistryCompilerPass.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\DependencyInjection\Compiler; +use CleverAge\ProcessBundle\Exception\LogicException; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -39,7 +40,7 @@ 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'); + throw new LogicException('The registry, tag and method of the RegistryCompilerPass must be defined'); } if (!$container->has($this->registry)) { diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php new file mode 100644 index 00000000..390110b5 --- /dev/null +++ b/src/Exception/InvalidArgumentException.php @@ -0,0 +1,21 @@ +filePath); if (!@mkdir($dirname, 0o755, true) && !is_dir($dirname)) { - throw new \RuntimeException(\sprintf('Directory "%s" was not created', $dirname)); + throw new RuntimeException(\sprintf('Directory "%s" was not created', $dirname)); } } $resource = fopen($filePath, $mode); if (false === $resource) { - throw new \UnexpectedValueException("Unable to open file: '{$filePath}' in {$mode} mode"); + throw new UnexpectedValueException("Unable to open file: '{$filePath}' in {$mode} mode"); } // All modes allowing file reading, binary safe modes are handled by stripping out the b during test $readAllowedModes = ['r', 'r+', 'w+', 'a+', 'x+', 'c+']; if (null === $headers && !\in_array(str_replace('b', '', $mode), $readAllowedModes, true)) { // Cannot read headers if the file was just created - throw new \UnexpectedValueException("Invalid headers for {$this->getResourceName()}, you need to pass the headers manually"); + throw new UnexpectedValueException("Invalid headers for {$this->getResourceName()}, you need to pass the headers manually"); } parent::__construct($resource, $delimiter, $enclosure, $escape, $headers); diff --git a/src/Filesystem/CsvResource.php b/src/Filesystem/CsvResource.php index 5220693f..b945ee49 100644 --- a/src/Filesystem/CsvResource.php +++ b/src/Filesystem/CsvResource.php @@ -13,6 +13,10 @@ namespace CleverAge\ProcessBundle\Filesystem; +use CleverAge\ProcessBundle\Exception\LogicException; +use CleverAge\ProcessBundle\Exception\RuntimeException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; + /** * Read and write CSV resources through a simple API. */ @@ -52,7 +56,7 @@ public function __construct( ) { if (!\is_resource($resource)) { $type = \gettype($resource); - throw new \UnexpectedValueException("Resource argument must be a resource, '{$type}' given"); + throw new UnexpectedValueException("Resource argument must be a resource, '{$type}' given"); } $this->handler = $resource; @@ -140,7 +144,7 @@ public function writeHeaders(): void public function getLineNumber(): int { if ($this->seekCalled) { - throw new \LogicException('Cannot get current line number after calling "seek": the line number is lost'); + throw new LogicException('Cannot get current line number after calling "seek": the line number is lost'); } return $this->lineNumber; @@ -183,20 +187,20 @@ public function readLine(?int $length = null): ?array return null; } $message = "Unable to parse data {$filePosition} for {$this->getResourceName()}"; - throw new \UnexpectedValueException($message); + throw new UnexpectedValueException($message); } $count = \count($values); if ($count !== $this->headerCount) { $message = "Number of columns not matching {$filePosition} for {$this->getResourceName()}: "; $message .= "{$count} columns for {$this->headerCount} headers"; - throw new \UnexpectedValueException($message); + throw new UnexpectedValueException($message); } try { $combined = array_combine($this->headers, $values); } catch (\ValueError) { - throw new \RuntimeException('Cannot combine headers with values'); + throw new RuntimeException('Cannot combine headers with values'); } return $combined; @@ -224,21 +228,21 @@ public function writeLine(array $fields): int if ($count !== $this->headerCount) { $message = "Trying to write an invalid number of columns for {$this->getResourceName()}: "; $message .= "{$count} columns for {$this->headerCount} headers"; - throw new \UnexpectedValueException($message); + throw new UnexpectedValueException($message); } $parsedFields = []; foreach ($this->headers as $column) { if (!\array_key_exists($column, $fields)) { $message = "Missing column {$column} in given fields for {$this->getResourceName()}"; - throw new \UnexpectedValueException($message); + throw new UnexpectedValueException($message); } $parsedFields[$column] = $fields[$column]; } $length = $this->writeRaw($parsedFields); if (false === $length) { - throw new \RuntimeException("Unable to write data to {$this->getResourceName()}"); + throw new RuntimeException("Unable to write data to {$this->getResourceName()}"); } return $length; @@ -251,7 +255,7 @@ public function rewind(): void { $this->assertOpened(); if (!rewind($this->handler)) { - throw new \RuntimeException("Unable to rewind '{$this->getResourceName()}'"); + throw new RuntimeException("Unable to rewind '{$this->getResourceName()}'"); } $this->lineNumber = 1; if (!$this->manualHeaders) { @@ -265,7 +269,7 @@ public function tell(): int $position = ftell($this->handler); if (false === $position) { - throw new \RuntimeException("Unable to get the position in {$this->getResourceName()}"); + throw new RuntimeException("Unable to get the position in {$this->getResourceName()}"); } return $position; @@ -308,7 +312,7 @@ public function getFilePath(): string protected function assertOpened(): void { if ($this->closed) { - throw new \RuntimeException("{$this->getResourceName()} was closed earlier"); + throw new RuntimeException("{$this->getResourceName()} was closed earlier"); } } @@ -324,7 +328,7 @@ protected function parseHeaders(?array $headers = null): array $autoHeaders = $this->readRaw(); // A blank line is read as [null] if (false === $autoHeaders || [null] === $autoHeaders) { - throw new \UnexpectedValueException("Unable to read headers for {$this->getResourceName()}"); + throw new UnexpectedValueException("Unable to read headers for {$this->getResourceName()}"); } $autoHeaders = array_map(strval(...), $autoHeaders); // Remove BOM if any @@ -337,7 +341,7 @@ protected function parseHeaders(?array $headers = null): array $this->manualHeaders = true; if ([] === $headers) { - throw new \UnexpectedValueException("Empty headers for {$this->getResourceName()}, you need to pass the headers manually"); + throw new UnexpectedValueException("Empty headers for {$this->getResourceName()}, you need to pass the headers manually"); } return $headers; diff --git a/src/Filesystem/JsonStreamFile.php b/src/Filesystem/JsonStreamFile.php index 7a5fd171..9f7a81ca 100644 --- a/src/Filesystem/JsonStreamFile.php +++ b/src/Filesystem/JsonStreamFile.php @@ -13,6 +13,9 @@ namespace CleverAge\ProcessBundle\Filesystem; +use CleverAge\ProcessBundle\Exception\RuntimeException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; + /** * Wrapper around JSON files to read them in a stream. * @@ -41,7 +44,7 @@ public function __construct( if (!\in_array($filename, ['php://stdin', 'php://stdout', 'php://stderr'], true) && !str_starts_with($mode, 'r')) { $dirname = \dirname($filename); if (!@mkdir($dirname, 0o755, true) && !is_dir($dirname)) { - throw new \RuntimeException(\sprintf('Directory "%s" was not created', $dirname)); + throw new RuntimeException(\sprintf('Directory "%s" was not created', $dirname)); } } @@ -113,7 +116,7 @@ public function readLine(?int $length = null): ?array $data = json_decode($rawLine, true, 512, $this->jsonFlags); if (null !== $data && !\is_array($data)) { - throw new \UnexpectedValueException(\sprintf('Line %d of file "%s" must be a JSON object or array, got %s', $currentLineNumber, $this->file->getPathname(), get_debug_type($data))); + throw new UnexpectedValueException(\sprintf('Line %d of file "%s" must be a JSON object or array, got %s', $currentLineNumber, $this->file->getPathname(), get_debug_type($data))); } return $data; diff --git a/src/Filesystem/XmlFile.php b/src/Filesystem/XmlFile.php index abb6f2b8..fc109a0c 100644 --- a/src/Filesystem/XmlFile.php +++ b/src/Filesystem/XmlFile.php @@ -13,6 +13,9 @@ namespace CleverAge\ProcessBundle\Filesystem; +use CleverAge\ProcessBundle\Exception\RuntimeException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; + /** * Read and write XML files. * @@ -33,12 +36,12 @@ public function read(): \DOMDocument // fstat() on the open handle, as getSize() may return a stale size from the stat cache $fileSize = $this->file->fstat()['size']; if (0 === $fileSize) { - throw new \UnexpectedValueException(\sprintf('XML file "%s" is empty', $this->file->getPathname())); + throw new UnexpectedValueException(\sprintf('XML file "%s" is empty', $this->file->getPathname())); } $fileContent = $this->file->fread($fileSize); if (false === $fileContent) { - throw new \RuntimeException(\sprintf('Could not read content from XML file "%s"', $this->file->getPathname())); + throw new RuntimeException(\sprintf('Could not read content from XML file "%s"', $this->file->getPathname())); } $dom = new \DOMDocument(); @@ -60,7 +63,7 @@ public function read(): \DOMDocument $errors, ); - throw new \UnexpectedValueException(\sprintf('Invalid XML in file "%s": %s', $this->file->getPathname(), [] !== $messages ? implode('; ', $messages) : 'unknown error')); + throw new UnexpectedValueException(\sprintf('Invalid XML in file "%s": %s', $this->file->getPathname(), [] !== $messages ? implode('; ', $messages) : 'unknown error')); } return $dom; @@ -70,12 +73,12 @@ public function write(\DOMDocument $dom): void { $content = $dom->saveXML(); if (false === $content) { - throw new \RuntimeException('Could not generate the XML content'); + throw new RuntimeException('Could not generate the XML content'); } $result = $this->file->fwrite($content); if (false === $result) { - throw new \RuntimeException('Could not write content to file'); + throw new RuntimeException('Could not write content to file'); } } } diff --git a/src/Manager/ProcessManager.php b/src/Manager/ProcessManager.php index 7e3bba10..bf5e7d96 100644 --- a/src/Manager/ProcessManager.php +++ b/src/Manager/ProcessManager.php @@ -20,6 +20,8 @@ use CleverAge\ProcessBundle\Exception\InvalidProcessConfigurationException; use CleverAge\ProcessBundle\Exception\ProcessFailedException; use CleverAge\ProcessBundle\Exception\ProcessStoppedException; +use CleverAge\ProcessBundle\Exception\RuntimeException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Logger\ProcessLogger; use CleverAge\ProcessBundle\Logger\TaskLogger; use CleverAge\ProcessBundle\Model\BlockingTaskInterface; @@ -247,7 +249,7 @@ protected function resolve(TaskConfiguration $taskConfiguration): bool } if (!$allParentsResolved) { - throw new \UnexpectedValueException('Cannot resolve all parents'); + throw new UnexpectedValueException('Cannot resolve all parents'); } $state->setStatus(ProcessState::STATUS_PROCESSING); @@ -401,7 +403,7 @@ protected function processExecution(TaskConfiguration $taskConfiguration, int $e { $task = $taskConfiguration->getTask(); if (!$task instanceof TaskInterface) { - throw new \RuntimeException("Missing task for configuration {$taskConfiguration->getCode()}"); + throw new RuntimeException("Missing task for configuration {$taskConfiguration->getCode()}"); } $state = $taskConfiguration->getState(); @@ -426,7 +428,7 @@ protected function processExecution(TaskConfiguration $taskConfiguration, int $e $state->reset(true); if (!$task instanceof BlockingTaskInterface) { // This exception should never be thrown - throw new \UnexpectedValueException("Task {$taskConfiguration->getCode()} is not blocking"); + throw new UnexpectedValueException("Task {$taskConfiguration->getCode()} is not blocking"); } $this->processLogger->debug("Proceeding task {$taskConfiguration->getCode()}"); $task->proceed($state); @@ -435,12 +437,12 @@ protected function processExecution(TaskConfiguration $taskConfiguration, int $e $state->reset(true); if (!$task instanceof FlushableTaskInterface) { // This exception should never be thrown - throw new \UnexpectedValueException("Task {$taskConfiguration->getCode()} is not flushable"); + throw new UnexpectedValueException("Task {$taskConfiguration->getCode()} is not flushable"); } $this->processLogger->debug("Flushing task {$taskConfiguration->getCode()}"); $task->flush($state); } else { - throw new \UnexpectedValueException("Unknown execution flag: {$executionFlag}"); + throw new UnexpectedValueException("Unknown execution flag: {$executionFlag}"); } $exception = $state->getException(); @@ -464,7 +466,7 @@ protected function processExecution(TaskConfiguration $taskConfiguration, int $e } elseif (TaskConfiguration::STRATEGY_STOP === $taskConfiguration->getErrorStrategy()) { $state->stop($exception); } else { - throw new \UnexpectedValueException("Unknown error strategy '{$taskConfiguration->getErrorStrategy()}'"); + throw new UnexpectedValueException("Unknown error strategy '{$taskConfiguration->getErrorStrategy()}'"); } } } diff --git a/src/Model/AbstractConfigurableTask.php b/src/Model/AbstractConfigurableTask.php index c4eb99ee..630bd3ec 100644 --- a/src/Model/AbstractConfigurableTask.php +++ b/src/Model/AbstractConfigurableTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Model; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Contracts\Service\ResetInterface; @@ -57,7 +58,7 @@ protected function getOption(ProcessState $state, string $code): mixed { $options = $this->getOptions($state); if (!\array_key_exists($code, $options)) { - throw new \InvalidArgumentException("Missing option {$code}"); + throw new InvalidArgumentException("Missing option {$code}"); } return $options[$code]; diff --git a/src/Model/ProcessState.php b/src/Model/ProcessState.php index af1f2605..26554175 100644 --- a/src/Model/ProcessState.php +++ b/src/Model/ProcessState.php @@ -16,6 +16,8 @@ use CleverAge\ProcessBundle\Configuration\ProcessConfiguration; use CleverAge\ProcessBundle\Configuration\TaskConfiguration; use CleverAge\ProcessBundle\Context\ContextualOptionResolver; +use CleverAge\ProcessBundle\Exception\RuntimeException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; /** * Used to pass information between tasks. @@ -288,7 +290,7 @@ public function getStatus(): string public function setStatus(string $status): void { if (!\in_array($status, self::STATUS, true)) { - throw new \UnexpectedValueException("Unknown status {$status}"); + throw new UnexpectedValueException("Unknown status {$status}"); } $this->status = $status; @@ -313,7 +315,7 @@ public function getContext(): array public function setContext(array $context): void { if ($this->context) { - throw new \RuntimeException('Once defined, context is immutable'); + throw new RuntimeException('Once defined, context is immutable'); } $this->context = $context; diff --git a/src/Model/SubprocessInstance.php b/src/Model/SubprocessInstance.php index 983f6383..37d4db98 100644 --- a/src/Model/SubprocessInstance.php +++ b/src/Model/SubprocessInstance.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Model; +use CleverAge\ProcessBundle\Exception\RuntimeException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -69,7 +70,7 @@ public function buildProcess(): static { $phpBinary = (new PhpExecutableFinder())->find(); if (false === $phpBinary) { - throw new \RuntimeException('Unable to find the PHP executable'); + throw new RuntimeException('Unable to find the PHP executable'); } $arguments = [ @@ -84,7 +85,7 @@ public function buildProcess(): static $fs = new Filesystem(); $fs->mkdir($this->logDir); if (!$fs->exists($this->consolePath)) { - throw new \RuntimeException("Unable to resolve path to symfony console '{$this->consolePath}'"); + throw new RuntimeException("Unable to resolve path to symfony console '{$this->consolePath}'"); } if ($this->options[self::OPTION_JSON_BUFFERING]) { diff --git a/src/Registry/ProcessConfigurationRegistry.php b/src/Registry/ProcessConfigurationRegistry.php index 915fa392..cca08a61 100644 --- a/src/Registry/ProcessConfigurationRegistry.php +++ b/src/Registry/ProcessConfigurationRegistry.php @@ -16,6 +16,7 @@ use CleverAge\ProcessBundle\Configuration\ProcessConfiguration; use CleverAge\ProcessBundle\Configuration\TaskConfiguration; use CleverAge\ProcessBundle\Exception\InvalidProcessConfigurationException; +use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Exception\MissingProcessException; use Psr\Log\LogLevel; @@ -84,13 +85,13 @@ protected function resolveConfiguration(string $processCode): void ) : 0) > 0) { $m = "Don't define both 'errors' and 'error_outputs' for task {$taskCode}, these options "; $m .= "are the same, 'errors' is deprecated, just use the new one 'error_outputs'"; - throw new \LogicException($m); + throw new LogicException($m); } $rawTaskConfiguration['error_outputs'] = $rawTaskConfiguration['errors']; } if (!\is_string($rawTaskConfiguration['service'] ?? null)) { // The "task" codes are resolved into services when the container is compiled (TaskLocatorCompilerPass) - throw new \LogicException("The task {$taskCode} of the process {$processCode} has no service: a \"task\" code can only be used in the configurations known when the container is compiled"); + throw new LogicException("The task {$taskCode} of the process {$processCode} has no service: a \"task\" code can only be used in the configurations known when the container is compiled"); } $taskConfigurations[$taskCode] = new TaskConfiguration( $taskCode, diff --git a/src/Registry/TaskRegistry.php b/src/Registry/TaskRegistry.php index dc04656d..aa302bd6 100644 --- a/src/Registry/TaskRegistry.php +++ b/src/Registry/TaskRegistry.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Registry; use CleverAge\ProcessBundle\Configuration\TaskConfiguration; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\TaskInterface; use Psr\Container\ContainerInterface; @@ -51,10 +52,10 @@ public function getTask(TaskConfiguration $taskConfiguration): TaskInterface // 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()}'"); + 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"); + throw new UnexpectedValueException("Service defined in Task '{$taskConfiguration->getCode()}' is not a TaskInterface"); } return $task; diff --git a/src/Registry/TransformerRegistry.php b/src/Registry/TransformerRegistry.php index 3614bab1..4bbda85b 100644 --- a/src/Registry/TransformerRegistry.php +++ b/src/Registry/TransformerRegistry.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Registry; use CleverAge\ProcessBundle\Exception\MissingTransformerException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\TransformerInterface; use Symfony\Contracts\Service\ServiceProviderInterface; @@ -58,7 +59,7 @@ public function addTransformer(TransformerInterface $transformer): void $transformer->getCode(), ); if ($this->hasTransformer($transformer->getCode())) { - throw new \UnexpectedValueException("Transformer {$transformer->getCode()} is already defined"); + throw new UnexpectedValueException("Transformer {$transformer->getCode()} is already defined"); } $this->transformers[$transformer->getCode()] = $transformer; } @@ -88,10 +89,10 @@ public function getTransformer(string $code): TransformerInterface $transformer = $this->locator->get($code); if (!$transformer instanceof TransformerInterface) { - throw new \UnexpectedValueException(\sprintf('The service of the transformer "%s" must implement "%s".', $code, TransformerInterface::class)); + throw new UnexpectedValueException(\sprintf('The service of the transformer "%s" must implement "%s".', $code, TransformerInterface::class)); } if ($code !== $transformer->getCode()) { - throw new \UnexpectedValueException(\sprintf('The transformer "%s" is registered with the code "%s" but its getCode() method returns "%s": both must be the same.', $transformer::class, $code, $transformer->getCode())); + throw new UnexpectedValueException(\sprintf('The transformer "%s" is registered with the code "%s" but its getCode() method returns "%s": both must be the same.', $transformer::class, $code, $transformer->getCode())); } return $this->transformers[$code] = $transformer; diff --git a/src/Task/AbstractIterableOutputTask.php b/src/Task/AbstractIterableOutputTask.php index 871b2489..06af127b 100644 --- a/src/Task/AbstractIterableOutputTask.php +++ b/src/Task/AbstractIterableOutputTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task; +use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\IterableTaskInterface; use CleverAge\ProcessBundle\Model\ProcessState; @@ -31,7 +32,7 @@ public function execute(ProcessState $state): void $this->handleIteratorFromInput($state); $iterator = $this->iterator; if (!$iterator instanceof \Iterator) { - throw new \LogicException('No iterator initialized'); + throw new LogicException('No iterator initialized'); } if ($iterator->valid()) { diff --git a/src/Task/ArrayMergeTask.php b/src/Task/ArrayMergeTask.php index 452e5e0d..449403f3 100644 --- a/src/Task/ArrayMergeTask.php +++ b/src/Task/ArrayMergeTask.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Task; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\BlockingTaskInterface; use CleverAge\ProcessBundle\Model\ProcessState; @@ -36,12 +38,12 @@ public function execute(ProcessState $state): void { $input = $state->getInput(); if (!\is_array($input)) { - throw new \UnexpectedValueException('Input must be an array'); + throw new UnexpectedValueException('Input must be an array'); } $mergeFunction = $this->getOption($state, 'merge_function'); if (!\in_array($mergeFunction, self::MERGE_FUNC, true)) { - throw new \InvalidArgumentException("Unknown merge function {$mergeFunction}"); + throw new InvalidArgumentException("Unknown merge function {$mergeFunction}"); } $this->mergedOutput = $mergeFunction($this->mergedOutput, $input); } diff --git a/src/Task/ColumnAggregatorTask.php b/src/Task/ColumnAggregatorTask.php index 031e3211..c0ee62ae 100644 --- a/src/Task/ColumnAggregatorTask.php +++ b/src/Task/ColumnAggregatorTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\BlockingTaskInterface; use CleverAge\ProcessBundle\Model\ProcessState; @@ -77,7 +78,7 @@ public function execute(ProcessState $state): void if ($this->getOption($state, 'ignore_missing')) { $this->logger->warning($message); } else { - throw new \UnexpectedValueException($message); + throw new UnexpectedValueException($message); } } } diff --git a/src/Task/File/Csv/CsvReaderTask.php b/src/Task/File/Csv/CsvReaderTask.php index 69a54211..0736dcce 100644 --- a/src/Task/File/Csv/CsvReaderTask.php +++ b/src/Task/File/Csv/CsvReaderTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File\Csv; +use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Filesystem\CsvFile; use CleverAge\ProcessBundle\Model\IterableTaskInterface; use CleverAge\ProcessBundle\Model\ProcessState; @@ -43,7 +44,7 @@ public function execute(ProcessState $state): void } $csv = $this->csv; if (!$csv instanceof CsvFile) { - throw new \LogicException('No CSV File initialized'); + throw new LogicException('No CSV File initialized'); } $lineNumber = $csv->getLineNumber(); $output = $csv->readLine(); @@ -73,7 +74,7 @@ public function execute(ProcessState $state): void public function next(ProcessState $state): bool { if (!$this->csv instanceof CsvFile) { - throw new \LogicException('No CSV File initialized'); + throw new LogicException('No CSV File initialized'); } $state->removeErrorContext('csv_file'); diff --git a/src/Task/File/Csv/CsvSplitterTask.php b/src/Task/File/Csv/CsvSplitterTask.php index cdc76dfd..7d7a440e 100644 --- a/src/Task/File/Csv/CsvSplitterTask.php +++ b/src/Task/File/Csv/CsvSplitterTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File\Csv; +use CleverAge\ProcessBundle\Exception\RuntimeException; use CleverAge\ProcessBundle\Filesystem\CsvFile; use CleverAge\ProcessBundle\Filesystem\CsvResource; use CleverAge\ProcessBundle\Model\ProcessState; @@ -95,7 +96,7 @@ protected function splitCsv(CsvResource $csv, int $maxLines): string $tmpFilePath = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'php_'.uniqid('process', false).'.csv'; $tmpFile = fopen($tmpFilePath, 'wb+'); if (false === $tmpFile) { - throw new \RuntimeException("Unable to open temporary file {$tmpFilePath}"); + throw new RuntimeException("Unable to open temporary file {$tmpFilePath}"); } $splitCsv = new CsvResource( $tmpFile, diff --git a/src/Task/File/Csv/CsvWriterTask.php b/src/Task/File/Csv/CsvWriterTask.php index 003bd313..f513e920 100644 --- a/src/Task/File/Csv/CsvWriterTask.php +++ b/src/Task/File/Csv/CsvWriterTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File\Csv; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Filesystem\CsvFile; use CleverAge\ProcessBundle\Model\BlockingTaskInterface; use CleverAge\ProcessBundle\Model\ProcessState; @@ -79,7 +80,7 @@ protected function getInput(ProcessState $state): array { $input = $state->getInput(); if (!\is_array($input)) { - throw new \UnexpectedValueException('Input value is not an array'); + throw new UnexpectedValueException('Input value is not an array'); } $splitCharacter = $this->getOption($state, 'split_character'); @@ -103,7 +104,7 @@ protected function getHeaders(ProcessState $state, array $options): ?array if (null === $headers) { $input = $state->getInput(); if (!\is_array($input)) { - throw new \UnexpectedValueException('Input value is not an array'); + throw new UnexpectedValueException('Input value is not an array'); } // Keys of a list are integers: the CSV output is the same with their string value diff --git a/src/Task/File/FileMoverTask.php b/src/Task/File/FileMoverTask.php index 5d9c4f1f..2969b30a 100644 --- a/src/Task/File/FileMoverTask.php +++ b/src/Task/File/FileMoverTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\ProcessState; use Symfony\Component\Filesystem\Filesystem; @@ -31,7 +32,7 @@ public function execute(ProcessState $state): void $fs = new Filesystem(); $file = $state->getInput(); if (!$fs->exists($file)) { - throw new \UnexpectedValueException("File does not exists: '{$file}'"); + throw new UnexpectedValueException("File does not exists: '{$file}'"); } $dest = $options['destination']; if (is_dir($dest)) { diff --git a/src/Task/File/FileReaderTask.php b/src/Task/File/FileReaderTask.php index 2261acbe..3ca9c7e6 100644 --- a/src/Task/File/FileReaderTask.php +++ b/src/Task/File/FileReaderTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\ProcessState; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -28,11 +29,11 @@ public function execute(ProcessState $state): void $filename = $options['filename']; if (!file_exists($filename)) { - throw new \UnexpectedValueException("File does not exists: '{$filename}'"); + throw new UnexpectedValueException("File does not exists: '{$filename}'"); } if (!is_readable($filename)) { - throw new \UnexpectedValueException("File is not readable: '{$filename}'"); + throw new UnexpectedValueException("File is not readable: '{$filename}'"); } $state->setOutput(file_get_contents($filename)); diff --git a/src/Task/File/FolderBrowserTask.php b/src/Task/File/FolderBrowserTask.php index 728a61c4..a7b13f33 100644 --- a/src/Task/File/FolderBrowserTask.php +++ b/src/Task/File/FolderBrowserTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File; +use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\IterableTaskInterface; use CleverAge\ProcessBundle\Model\ProcessState; @@ -138,7 +139,7 @@ private function getFilesIterator(): \Iterator $this->files = new \ArrayIterator($this->files); } if (!$this->files instanceof \Iterator) { - throw new \LogicException('No folder browsed'); + throw new LogicException('No folder browsed'); } return $this->files; diff --git a/src/Task/File/InputFileReaderTask.php b/src/Task/File/InputFileReaderTask.php index 61a32646..a29194c8 100644 --- a/src/Task/File/InputFileReaderTask.php +++ b/src/Task/File/InputFileReaderTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\ProcessState; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -39,7 +40,7 @@ protected function getOptions(ProcessState $state): array $options = parent::getOptions($state); $filename = $state->getInput(); if (!\is_string($filename) || '' === $filename) { - throw new \UnexpectedValueException('No file path given as input'); + throw new UnexpectedValueException('No file path given as input'); } $options['filename'] = $filename; diff --git a/src/Task/File/InputFolderBrowserTask.php b/src/Task/File/InputFolderBrowserTask.php index a1d5ebd9..a50d169b 100644 --- a/src/Task/File/InputFolderBrowserTask.php +++ b/src/Task/File/InputFolderBrowserTask.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Task\File; +use CleverAge\ProcessBundle\Exception\LogicException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\FlushableTaskInterface; use CleverAge\ProcessBundle\Model\ProcessState; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; @@ -73,13 +75,13 @@ protected function getOptions(ProcessState $state): array if ($state->getInput()) { $folderPath = $options['base_folder_path'].$state->getInput(); if ($this->folderPath && $folderPath !== $this->folderPath) { - throw new \LogicException("Folder path '{$folderPath}' already initialized with a different value {$this->folderPath}"); + throw new LogicException("Folder path '{$folderPath}' already initialized with a different value {$this->folderPath}"); } $this->folderPath = $folderPath; } if (null === $this->folderPath) { - throw new \UnexpectedValueException('No folder path given as input'); + throw new UnexpectedValueException('No folder path given as input'); } if (!is_dir($this->folderPath)) { throw new InvalidConfigurationException("Folder path does not exists or is not a folder: '{$this->folderPath}'"); diff --git a/src/Task/File/JsonStream/JsonStreamWriterTask.php b/src/Task/File/JsonStream/JsonStreamWriterTask.php index 66ca932d..d3b436cb 100644 --- a/src/Task/File/JsonStream/JsonStreamWriterTask.php +++ b/src/Task/File/JsonStream/JsonStreamWriterTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File\JsonStream; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Filesystem\JsonStreamFile; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\BlockingTaskInterface; @@ -42,7 +43,7 @@ public function execute(ProcessState $state): void $input = $state->getInput(); if (!\is_array($input)) { - throw new \UnexpectedValueException('Input value is not an array'); + throw new UnexpectedValueException('Input value is not an array'); } $this->file->writeLine($input); } diff --git a/src/Task/File/LineReaderTask.php b/src/Task/File/LineReaderTask.php index 3e7b2a29..69f1d4c3 100644 --- a/src/Task/File/LineReaderTask.php +++ b/src/Task/File/LineReaderTask.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Task\File; +use CleverAge\ProcessBundle\Exception\LogicException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\IterableTaskInterface; use CleverAge\ProcessBundle\Model\ProcessState; @@ -37,11 +39,11 @@ public function execute(ProcessState $state): void if (!$this->file instanceof \SplFileObject) { if (!file_exists($filename)) { - throw new \UnexpectedValueException("File does not exist: '{$filename}'"); + throw new UnexpectedValueException("File does not exist: '{$filename}'"); } if (!is_readable($filename)) { - throw new \UnexpectedValueException("File is not readable: '{$filename}'"); + throw new UnexpectedValueException("File is not readable: '{$filename}'"); } $this->file = new \SplFileObject($filename); @@ -56,7 +58,7 @@ public function execute(ProcessState $state): void public function next(ProcessState $state): bool { if (!$this->file instanceof \SplFileObject) { - throw new \LogicException('No File initialized'); + throw new LogicException('No File initialized'); } $endOfFile = $this->file->eof(); diff --git a/src/Task/File/Xml/XmlStreamReaderTask.php b/src/Task/File/Xml/XmlStreamReaderTask.php index 9ba741a3..4c19adb4 100644 --- a/src/Task/File/Xml/XmlStreamReaderTask.php +++ b/src/Task/File/Xml/XmlStreamReaderTask.php @@ -13,6 +13,9 @@ namespace CleverAge\ProcessBundle\Task\File\Xml; +use CleverAge\ProcessBundle\Exception\LogicException; +use CleverAge\ProcessBundle\Exception\RuntimeException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\FinalizableTaskInterface; use CleverAge\ProcessBundle\Model\IterableTaskInterface; @@ -69,7 +72,7 @@ protected function getFilePath(ProcessState $state): string { $filePath = $this->getOption($state, 'file_path') ?? $state->getInput(); if (!\is_string($filePath) || '' === $filePath) { - throw new \UnexpectedValueException('No file path given in the "file_path" option or as input'); + throw new UnexpectedValueException('No file path given in the "file_path" option or as input'); } return $filePath; @@ -78,12 +81,12 @@ protected function getFilePath(ProcessState $state): string protected function open(string $filePath): void { if (!is_file($filePath) || !is_readable($filePath)) { - throw new \UnexpectedValueException(\sprintf('XML file "%s" does not exist or is not readable', $filePath)); + throw new UnexpectedValueException(\sprintf('XML file "%s" does not exist or is not readable', $filePath)); } $reader = new \XMLReader(); if (!@$reader->open($filePath)) { - throw new \RuntimeException(\sprintf('Could not open XML file "%s"', $filePath)); + throw new RuntimeException(\sprintf('Could not open XML file "%s"', $filePath)); } $this->reader = $reader; $this->filePath = $filePath; @@ -131,7 +134,7 @@ protected function expand(): \DOMElement $this->throwOnErrors($errors); if (!$node instanceof \DOMElement) { - throw new \UnexpectedValueException(\sprintf('Could not expand element "%s" of XML file "%s"', $reader->name, $this->filePath)); + throw new UnexpectedValueException(\sprintf('Could not expand element "%s" of XML file "%s"', $reader->name, $this->filePath)); } // Each element gets its own document, so that it can be evaluated with xpath like the output of XmlReaderTask @@ -159,13 +162,13 @@ protected function throwOnErrors(array $errors): void $filePath = $this->filePath; $this->close(); - throw new \UnexpectedValueException(\sprintf('Invalid XML in file "%s": %s', $filePath, implode('; ', $messages))); + throw new UnexpectedValueException(\sprintf('Invalid XML in file "%s": %s', $filePath, implode('; ', $messages))); } protected function getReader(): \XMLReader { if (!$this->reader instanceof \XMLReader) { - throw new \LogicException('No XML file opened'); + throw new LogicException('No XML file opened'); } return $this->reader; diff --git a/src/Task/File/Xml/XmlWriterTask.php b/src/Task/File/Xml/XmlWriterTask.php index 314021d8..f9ecb724 100644 --- a/src/Task/File/Xml/XmlWriterTask.php +++ b/src/Task/File/Xml/XmlWriterTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\File\Xml; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Filesystem\XmlFile; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\ProcessState; @@ -35,7 +36,7 @@ public function execute(ProcessState $state): void { $input = $state->getInput(); if (!$input instanceof \DOMDocument) { - throw new \UnexpectedValueException('Input must be a \DOMDocument'); + throw new UnexpectedValueException('Input must be a \DOMDocument'); } $file = new XmlFile($this->getOption($state, 'file_path'), $this->getOption($state, 'mode')); diff --git a/src/Task/File/Yaml/YamlReaderTask.php b/src/Task/File/Yaml/YamlReaderTask.php index f6b9e92b..2d20fa7b 100644 --- a/src/Task/File/Yaml/YamlReaderTask.php +++ b/src/Task/File/Yaml/YamlReaderTask.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Task\File\Yaml; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\ProcessState; use CleverAge\ProcessBundle\Task\AbstractIterableOutputTask; use Symfony\Component\OptionsResolver\Options; @@ -34,7 +36,7 @@ protected function configureOptions(OptionsResolver $resolver): void 'file_path', static function (Options $options, $value) { if (!file_exists($value)) { - throw new \UnexpectedValueException("File not found: {$value}"); + throw new UnexpectedValueException("File not found: {$value}"); } return $value; @@ -47,7 +49,7 @@ protected function initializeIterator(ProcessState $state): \Iterator $filePath = $this->getOption($state, 'file_path'); $content = Yaml::parseFile($filePath); if (!\is_array($content)) { - throw new \InvalidArgumentException("File content is not an array: {$filePath}"); + throw new InvalidArgumentException("File content is not an array: {$filePath}"); } return new \ArrayIterator($content); diff --git a/src/Task/InputAggregatorTask.php b/src/Task/InputAggregatorTask.php index 4bb151d1..c417e779 100644 --- a/src/Task/InputAggregatorTask.php +++ b/src/Task/InputAggregatorTask.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Task; +use CleverAge\ProcessBundle\Exception\RuntimeException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\ProcessState; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -49,7 +51,7 @@ public function execute(ProcessState $state): void { $previousState = $state->getPreviousState(); if (!$previousState instanceof ProcessState) { - throw new \UnexpectedValueException('This task cannot be used without a previous task'); + throw new UnexpectedValueException('This task cannot be used without a previous task'); } $inputCode = $this->getInputCode($state); @@ -60,7 +62,7 @@ public function execute(ProcessState $state): void $this->inputs = []; $this->inputAncestors = []; } else { - throw new \UnexpectedValueException("The output from input '{$inputCode}' has already been defined, please use an aggregator if you have an iterable output"); + throw new UnexpectedValueException("The output from input '{$inputCode}' has already been defined, please use an aggregator if you have an iterable output"); } } @@ -101,13 +103,13 @@ protected function getInputCode(ProcessState $state): string { $previousState = $state->getPreviousState(); if (!$previousState instanceof ProcessState) { - throw new \RuntimeException('No previous state for current task'); + throw new RuntimeException('No previous state for current task'); } $previousTaskCode = $previousState->getTaskConfiguration() ->getCode(); $inputCodes = $this->getOption($state, 'input_codes'); if (!\array_key_exists($previousTaskCode, $inputCodes)) { - throw new \UnexpectedValueException("Task '{$previousTaskCode}' is not mapped in the input_codes option"); + throw new UnexpectedValueException("Task '{$previousTaskCode}' is not mapped in the input_codes option"); } return $inputCodes[$previousTaskCode]; diff --git a/src/Task/InputIteratorTask.php b/src/Task/InputIteratorTask.php index c9618bf5..b255bbc9 100644 --- a/src/Task/InputIteratorTask.php +++ b/src/Task/InputIteratorTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\ProcessState; /** @@ -44,6 +45,6 @@ protected function initializeIterator(ProcessState $state): \Iterator return new \ArrayIterator($input); } - throw new \UnexpectedValueException('Cannot create iterator from input'); + throw new UnexpectedValueException('Cannot create iterator from input'); } } diff --git a/src/Task/ObjectUpdaterTask.php b/src/Task/ObjectUpdaterTask.php index b62b1ab4..89632065 100644 --- a/src/Task/ObjectUpdaterTask.php +++ b/src/Task/ObjectUpdaterTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\ProcessState; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -35,10 +36,10 @@ public function execute(ProcessState $state): void { $input = $state->getInput(); if (!\array_key_exists('object', $input)) { - throw new \UnexpectedValueException("Missing 'object' key in input array"); + throw new UnexpectedValueException("Missing 'object' key in input array"); } if (!\array_key_exists('value', $input)) { - throw new \UnexpectedValueException("Missing 'value' key in input array"); + throw new UnexpectedValueException("Missing 'value' key in input array"); } $this->accessor->setValue($input['object'], $this->getOption($state, 'property_path'), $input['value']); $state->setOutput($input['object']); diff --git a/src/Task/Process/ProcessLauncherTask.php b/src/Task/Process/ProcessLauncherTask.php index c066239d..227c4b0b 100644 --- a/src/Task/Process/ProcessLauncherTask.php +++ b/src/Task/Process/ProcessLauncherTask.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Task\Process; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; +use CleverAge\ProcessBundle\Exception\RuntimeException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\FlushableTaskInterface; use CleverAge\ProcessBundle\Model\IterableTaskInterface; @@ -174,7 +176,7 @@ protected function handleProcesses(ProcessState $state): void $this->logger->critical($process->getProcess()->getErrorOutput(), $logContext); $this->killProcesses(); - throw new \RuntimeException("Sub-process has failed: {$process->getProcess()->getExitCodeText()}"); + throw new RuntimeException("Sub-process has failed: {$process->getProcess()->getExitCodeText()}"); } $result = $process->getResult(); @@ -227,7 +229,7 @@ function (Options $options, $value) { static function (Options $options, array $value): array { if ([] !== $value) { // Todo deprecation trigger - throw new \InvalidArgumentException('Deprecated option, please contact support for help'); + throw new InvalidArgumentException('Deprecated option, please contact support for help'); } return $value; diff --git a/src/Task/Serialization/NormalizerTask.php b/src/Task/Serialization/NormalizerTask.php index 6cd8c52a..23f8ee14 100644 --- a/src/Task/Serialization/NormalizerTask.php +++ b/src/Task/Serialization/NormalizerTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\Serialization; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\ProcessState; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -35,7 +36,7 @@ public function execute(ProcessState $state): void $options = $this->getOptions($state); if (!$this->normalizer->supportsNormalization($state->getInput(), $options['format'])) { - throw new \UnexpectedValueException('Given value is not normalizable for format '.$options['format']); + throw new UnexpectedValueException('Given value is not normalizable for format '.$options['format']); } $normalizedData = $this->normalizer->normalize( diff --git a/src/Task/SplitJoinLineTask.php b/src/Task/SplitJoinLineTask.php index 55bffd4c..a1019163 100644 --- a/src/Task/SplitJoinLineTask.php +++ b/src/Task/SplitJoinLineTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\ProcessState; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -58,7 +59,7 @@ protected function initializeIterator(ProcessState $state): \Iterator $outputLines = []; foreach ($options['split_columns'] as $column) { if (!\array_key_exists($column, $originalLine)) { - throw new \UnexpectedValueException("Missing column {$column}"); + throw new UnexpectedValueException("Missing column {$column}"); } $columnValues = explode($options['split_character'], (string) $originalLine[$column]); foreach ($columnValues as $columnValue) { diff --git a/src/Task/UnavailableTask.php b/src/Task/UnavailableTask.php index a2f58c3a..df9b88ec 100644 --- a/src/Task/UnavailableTask.php +++ b/src/Task/UnavailableTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task; +use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Model\ProcessState; use CleverAge\ProcessBundle\Model\TaskInterface; @@ -33,6 +34,6 @@ public function __construct( public function execute(ProcessState $state): void { - throw new \LogicException($this->message); + throw new LogicException($this->message); } } diff --git a/src/Task/Validation/ValidatorTask.php b/src/Task/Validation/ValidatorTask.php index 68770945..1985a891 100644 --- a/src/Task/Validation/ValidatorTask.php +++ b/src/Task/Validation/ValidatorTask.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Task\Validation; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Model\AbstractConfigurableTask; use CleverAge\ProcessBundle\Model\ProcessState; use CleverAge\ProcessBundle\Validator\ConstraintLoader; @@ -63,7 +64,7 @@ public function execute(ProcessState $state): void return; } - throw new \UnexpectedValueException("{$violations->count()} constraint violations detected on validation"); + throw new UnexpectedValueException("{$violations->count()} constraint violations detected on validation"); } $state->setOutput($state->getInput()); diff --git a/src/Transformer/Array/ArrayFilterTransformer.php b/src/Transformer/Array/ArrayFilterTransformer.php index e6424224..10fd391d 100644 --- a/src/Transformer/Array/ArrayFilterTransformer.php +++ b/src/Transformer/Array/ArrayFilterTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\Array; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConditionTrait; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -42,7 +43,7 @@ public function __construct(PropertyAccessorInterface $accessor) public function transform(mixed $value, array $options = []): array { if (!is_iterable($value)) { - throw new \UnexpectedValueException('Given value is not iterable'); + throw new UnexpectedValueException('Given value is not iterable'); } $result = []; diff --git a/src/Transformer/Array/ArrayMapTransformer.php b/src/Transformer/Array/ArrayMapTransformer.php index 0ab0ff0e..6b5f5d26 100644 --- a/src/Transformer/Array/ArrayMapTransformer.php +++ b/src/Transformer/Array/ArrayMapTransformer.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Transformer\Array; use CleverAge\ProcessBundle\Exception\TransformerException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Registry\TransformerRegistry; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use CleverAge\ProcessBundle\Transformer\TransformerTrait; @@ -43,7 +44,7 @@ public function __construct(TransformerRegistry $transformerRegistry) public function transform(mixed $value, array $options = []): array { if (!\is_array($value) && !$value instanceof \Traversable) { - throw new \UnexpectedValueException('Input value must be an array or traversable'); + throw new UnexpectedValueException('Input value must be an array or traversable'); } $results = []; diff --git a/src/Transformer/Array/ArrayUnsetTransformer.php b/src/Transformer/Array/ArrayUnsetTransformer.php index 0c5da954..9c4542b1 100644 --- a/src/Transformer/Array/ArrayUnsetTransformer.php +++ b/src/Transformer/Array/ArrayUnsetTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\Array; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -29,7 +30,7 @@ class ArrayUnsetTransformer implements ConfigurableTransformerInterface public function transform(mixed $value, array $options = []): mixed { if (!\is_array($value)) { - throw new \UnexpectedValueException('Given value is not an array'); + throw new UnexpectedValueException('Given value is not an array'); } unset($value[$options['key']]); diff --git a/src/Transformer/ConvertValueTransformer.php b/src/Transformer/ConvertValueTransformer.php index 0548c7af..4d5e6df9 100644 --- a/src/Transformer/ConvertValueTransformer.php +++ b/src/Transformer/ConvertValueTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -36,10 +37,10 @@ public function transform(mixed $value, array $options = []): mixed if (!\is_string($value) && !\is_int($value)) { // If not a valid array index if (!$options['auto_cast']) { $type = \gettype($value); - throw new \UnexpectedValueException("Value of type {$type} is not a valid array index, set auto_cast to true to cast it to a string"); + throw new UnexpectedValueException("Value of type {$type} is not a valid array index, set auto_cast to true to cast it to a string"); } if (\is_array($value)) { // Array to string conversion is a simple notice so we need to catch it here - throw new \UnexpectedValueException("Unexpected input of type 'array' in convert_value transformer"); + throw new UnexpectedValueException("Unexpected input of type 'array' in convert_value transformer"); } $value = (string) $value; // Let's cast it to string } @@ -49,7 +50,7 @@ public function transform(mixed $value, array $options = []): mixed return $value; } if (!$options['ignore_missing']) { - throw new \UnexpectedValueException("Missing value in map '{$value}'"); + throw new UnexpectedValueException("Missing value in map '{$value}'"); } return null; diff --git a/src/Transformer/Date/DateFormatTransformer.php b/src/Transformer/Date/DateFormatTransformer.php index 18cc0488..ea1fc5bc 100644 --- a/src/Transformer/Date/DateFormatTransformer.php +++ b/src/Transformer/Date/DateFormatTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\Date; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -40,7 +41,7 @@ public function transform(mixed $value, array $options = []): mixed if ($value instanceof \DateTimeInterface) { $date = $value; } else { - throw new \UnexpectedValueException('Given value cannot be parsed into a date'); + throw new UnexpectedValueException('Given value cannot be parsed into a date'); } return $date->format($options['format']); diff --git a/src/Transformer/Date/DateParserTransformer.php b/src/Transformer/Date/DateParserTransformer.php index ec197dcc..4cc9a7e7 100644 --- a/src/Transformer/Date/DateParserTransformer.php +++ b/src/Transformer/Date/DateParserTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\Date; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -44,7 +45,7 @@ public function transform(mixed $value, array $options = []): mixed $date = \DateTime::createFromFormat($options['format'], $value); if (!$date) { - throw new \UnexpectedValueException('Given value cannot be parsed into a date'); + throw new UnexpectedValueException('Given value cannot be parsed into a date'); } return $date; diff --git a/src/Transformer/ExpressionLanguageMapTransformer.php b/src/Transformer/ExpressionLanguageMapTransformer.php index 4289429b..c08fe775 100644 --- a/src/Transformer/ExpressionLanguageMapTransformer.php +++ b/src/Transformer/ExpressionLanguageMapTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\ParsedExpression; use Symfony\Component\OptionsResolver\Options; @@ -44,7 +45,7 @@ public function configureOptions(OptionsResolver $resolver): void 'map', function (Options $options, $values): array { if (!\is_array($values)) { - throw new \UnexpectedValueException('The map must be an array'); + throw new UnexpectedValueException('The map must be an array'); } $resolver = new OptionsResolver(); $resolver->setRequired(['condition', 'output']); @@ -85,7 +86,7 @@ public function transform(mixed $value, array $options = []): mixed } if (!$options['ignore_missing']) { $printableValue = \is_scalar($value) || $value instanceof \Stringable ? (string) $value : get_debug_type($value); - throw new \UnexpectedValueException("No expression accepting value '{$printableValue}' in map"); + throw new UnexpectedValueException("No expression accepting value '{$printableValue}' in map"); } return null; diff --git a/src/Transformer/GenericTransformer.php b/src/Transformer/GenericTransformer.php index 283a1b3c..0f86ce4b 100644 --- a/src/Transformer/GenericTransformer.php +++ b/src/Transformer/GenericTransformer.php @@ -14,6 +14,8 @@ namespace CleverAge\ProcessBundle\Transformer; use CleverAge\ProcessBundle\Context\ContextualOptionResolver; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; +use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Registry\TransformerRegistry; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -103,7 +105,7 @@ public function configureOptions(OptionsResolver $resolver): void $this->configureTransformersOptions($resolver); $resolver->setNormalizer('transformers', function (Options $options, $transformerOptions): array { if ([] !== $transformerOptions) { - throw new \InvalidArgumentException('Transformers option should not be used at this point'); + throw new InvalidArgumentException('Transformers option should not be used at this point'); } $transformerOptions = $this->normalizeTransformerOptions($options, $this->preconfiguredTransformerOptions ?? []); @@ -123,7 +125,7 @@ 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'); + throw new LogicException('The generic transformer is not initialized'); } return $this->transformerCode; diff --git a/src/Transformer/MappingTransformer.php b/src/Transformer/MappingTransformer.php index 050bd9e4..82a0f6ed 100644 --- a/src/Transformer/MappingTransformer.php +++ b/src/Transformer/MappingTransformer.php @@ -14,6 +14,7 @@ namespace CleverAge\ProcessBundle\Transformer; use CleverAge\ProcessBundle\Exception\TransformerException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Registry\TransformerRegistry; use Psr\Log\LoggerInterface; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; @@ -130,7 +131,7 @@ public function transform(mixed $value, array $options = []): mixed // Only a simple property name can be added to a \stdClass, nested paths are not created $result->{$targetProperty} = $transformedValue; } else { - throw new \UnexpectedValueException("Property '{$targetProperty}' is not writable"); + throw new UnexpectedValueException("Property '{$targetProperty}' is not writable"); } } diff --git a/src/Transformer/Object/InstantiateTransformer.php b/src/Transformer/Object/InstantiateTransformer.php index 8fd61771..2d7eb785 100644 --- a/src/Transformer/Object/InstantiateTransformer.php +++ b/src/Transformer/Object/InstantiateTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\Object; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -29,7 +30,7 @@ class InstantiateTransformer implements ConfigurableTransformerInterface public function transform(mixed $value, array $options = []): mixed { if (!\is_array($value)) { - throw new \UnexpectedValueException('Input value must be an array for transformer instantiate'); + throw new UnexpectedValueException('Input value must be an array for transformer instantiate'); } return (new \ReflectionClass($options['class']))->newInstanceArgs($value); diff --git a/src/Transformer/RulesTransformer.php b/src/Transformer/RulesTransformer.php index 4efd5041..6c59aa23 100644 --- a/src/Transformer/RulesTransformer.php +++ b/src/Transformer/RulesTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; use CleverAge\ProcessBundle\Registry\TransformerRegistry; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\ParsedExpression; @@ -81,13 +82,13 @@ public function configureOptions(OptionsResolver $resolver): void foreach ($rules as $rule) { if ($rule['default']) { if ($hasFoundDefault) { - throw new \InvalidArgumentException('Rules set cannot have more than one default rule'); + throw new InvalidArgumentException('Rules set cannot have more than one default rule'); } $hasFoundDefault = true; } if ($hasFoundDefault && null !== $rule['condition']) { - throw new \InvalidArgumentException('A conditional rule cannot be placed after a default rule'); + throw new InvalidArgumentException('A conditional rule cannot be placed after a default rule'); } } @@ -123,7 +124,7 @@ public function configureRuleOptions(OptionsResolver $resolver, ?array $expressi $resolver->setNormalizer('condition', $expressionNormalizer); $resolver->setNormalizer('default', static function (Options $options, $value) { if ($value && $options['condition']) { - throw new \InvalidArgumentException('A rule cannot have a condition and be the default in the same time'); + throw new InvalidArgumentException('A rule cannot have a condition and be the default in the same time'); } return $value; diff --git a/src/Transformer/String/ImplodeTransformer.php b/src/Transformer/String/ImplodeTransformer.php index 5a7a994c..0d221eaf 100644 --- a/src/Transformer/String/ImplodeTransformer.php +++ b/src/Transformer/String/ImplodeTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\String; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -35,7 +36,7 @@ public function configureOptions(OptionsResolver $resolver): void public function transform(mixed $value, array $options = []): string { if (!\is_array($value)) { - throw new \UnexpectedValueException('Given value is not an array'); + throw new UnexpectedValueException('Given value is not an array'); } return implode($options['separator'], $value); diff --git a/src/Transformer/String/SlugifyTransformer.php b/src/Transformer/String/SlugifyTransformer.php index dd5eaab2..2e2c6926 100644 --- a/src/Transformer/String/SlugifyTransformer.php +++ b/src/Transformer/String/SlugifyTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer\String; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Options; @@ -34,7 +35,7 @@ public function transform(mixed $value, array $options = []): string $transliterator = $options['transliterator']; $string = $transliterator->transliterate($value); if (false === $string) { - throw new \UnexpectedValueException("Unable to transliterate the value: {$transliterator->getErrorMessage()}"); + throw new UnexpectedValueException("Unable to transliterate the value: {$transliterator->getErrorMessage()}"); } return trim( diff --git a/src/Transformer/TransformerTrait.php b/src/Transformer/TransformerTrait.php index 7883ce39..e4d391d8 100644 --- a/src/Transformer/TransformerTrait.php +++ b/src/Transformer/TransformerTrait.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Transformer; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; +use CleverAge\ProcessBundle\Exception\LogicException; use CleverAge\ProcessBundle\Exception\TransformerException; use CleverAge\ProcessBundle\Registry\TransformerRegistry; use Closure; @@ -58,7 +60,7 @@ public function normalizeTransformers(Options $options, array $transformers): ar $transformer->configureOptions($transformerOptionsResolver); $transformerOptions = $transformerOptionsResolver->resolve($transformerOptions); } elseif (!empty($transformerOptions)) { - throw new \InvalidArgumentException("Transformer {$origTransformerCode} should not have options"); + throw new InvalidArgumentException("Transformer {$origTransformerCode} should not have options"); } $closure = static fn ($value) => $transformer->transform($value, $transformerOptions); @@ -140,7 +142,7 @@ private function checkTransformerOptions(mixed $transformerOptions, string $tran $type = get_debug_type($transformerOptions); - throw new \InvalidArgumentException("Options for transformer {$transformerCode} are invalid : found {$type}, expected array or null"); + throw new InvalidArgumentException("Options for transformer {$transformerCode} are invalid : found {$type}, expected array or null"); } /** @@ -163,13 +165,13 @@ private function parseListedTransformer(mixed $transformerDefinition, int $posit $type = get_debug_type($transformerDefinition); - throw new \InvalidArgumentException("Transformer at position {$position} is invalid : found {$type}, expected a transformer code or a single \"code: options\" map"); + throw new InvalidArgumentException("Transformer at position {$position} is invalid : found {$type}, expected a transformer code or a single \"code: options\" map"); } private function getTransformerRegistry(): TransformerRegistry { if (!$this->transformerRegistry instanceof TransformerRegistry) { - throw new \LogicException('No transformer registry defined'); + throw new LogicException('No transformer registry defined'); } return $this->transformerRegistry; diff --git a/src/Transformer/UnavailableTransformer.php b/src/Transformer/UnavailableTransformer.php index f28bcb49..4f59b0ef 100644 --- a/src/Transformer/UnavailableTransformer.php +++ b/src/Transformer/UnavailableTransformer.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Transformer; +use CleverAge\ProcessBundle\Exception\LogicException; + /** * Replaces a transformer whose dependencies are not available (e.g. the Symfony serializer is not enabled), so that * the container still compiles and the transformer code is still known: it fails only when it is used, with an @@ -32,7 +34,7 @@ public function __construct( public function transform(mixed $value, array $options = []): mixed { - throw new \LogicException($this->message); + throw new LogicException($this->message); } public function getCode(): string diff --git a/src/Transformer/UnsetTransformer.php b/src/Transformer/UnsetTransformer.php index 2090d646..92cb59b7 100644 --- a/src/Transformer/UnsetTransformer.php +++ b/src/Transformer/UnsetTransformer.php @@ -13,6 +13,7 @@ namespace CleverAge\ProcessBundle\Transformer; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -38,11 +39,11 @@ public function __construct(PropertyAccessorInterface $accessor) public function transform(mixed $value, array $options = []): array { if (!\is_array($value)) { - throw new \UnexpectedValueException('Given value must be an array'); + throw new UnexpectedValueException('Given value must be an array'); } if (!\array_key_exists($options['property'], $value)) { - throw new \UnexpectedValueException("Property {$options['property']} does not exists"); + throw new UnexpectedValueException("Property {$options['property']} does not exists"); } if ($this->checkCondition($value, $options['condition'])) { diff --git a/src/Transformer/Xml/XpathEvaluatorTransformer.php b/src/Transformer/Xml/XpathEvaluatorTransformer.php index f282e20d..3413e601 100644 --- a/src/Transformer/Xml/XpathEvaluatorTransformer.php +++ b/src/Transformer/Xml/XpathEvaluatorTransformer.php @@ -13,6 +13,8 @@ namespace CleverAge\ProcessBundle\Transformer\Xml; +use CleverAge\ProcessBundle\Exception\InvalidArgumentException; +use CleverAge\ProcessBundle\Exception\UnexpectedValueException; use CleverAge\ProcessBundle\Transformer\ConfigurableTransformerInterface; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -56,7 +58,7 @@ public function configureOptions(OptionsResolver $resolver): void } // This should never be reached - throw new \InvalidArgumentException('Unhandled query'); + throw new InvalidArgumentException('Unhandled query'); }); // Use same options & defaults for root option level and subquery options @@ -87,7 +89,7 @@ public function configureQueryOptions(OptionsResolver $resolver, ?Options $paren public function transform(mixed $value, array $options = []): mixed { if (!$value instanceof \DOMNode) { - throw new \UnexpectedValueException('Input should be a '.\DOMNode::class); + throw new UnexpectedValueException('Input should be a '.\DOMNode::class); } $xpath = $this->buildXpath($value); @@ -112,7 +114,7 @@ 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'); + throw new UnexpectedValueException('The node does not belong to a document'); } return new \DOMXPath($doc); @@ -135,7 +137,7 @@ public function query(\DOMXPath $xpath, string $query, \DOMNode $node, array $op 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')); + throw new UnexpectedValueException(\sprintf("Invalid xpath query '%s': %s", $query, [] !== $messages ? implode('; ', $messages) : 'unknown error')); } $results = iterator_to_array($nodeList); @@ -151,18 +153,18 @@ public function query(\DOMXPath $xpath, string $query, \DOMNode $node, array $op return $item->textContent; } - throw new \UnexpectedValueException("Xpath result cannot be unwrapped for query '{$query}'"); + throw new UnexpectedValueException("Xpath result cannot be unwrapped for query '{$query}'"); }, $results); } // Unwrap the node list if ($options['single_result']) { if (\count($results) > 1) { - throw new \UnexpectedValueException("There is too much results for query '{$query}'"); + throw new UnexpectedValueException("There is too much results for query '{$query}'"); } if (!$options['ignore_missing'] && [] === $results) { - throw new \UnexpectedValueException("There is not enough results for query '{$query}'"); + throw new UnexpectedValueException("There is not enough results for query '{$query}'"); } $results = 1 === \count($results) ? $results[0] : null; diff --git a/tests/Exception/SplExceptionsTest.php b/tests/Exception/SplExceptionsTest.php new file mode 100644 index 00000000..74500847 --- /dev/null +++ b/tests/Exception/SplExceptionsTest.php @@ -0,0 +1,72 @@ +, class-string<\Throwable>}> + */ + public static function provideExceptions(): iterable + { + yield 'UnexpectedValueException' => [UnexpectedValueException::class, \UnexpectedValueException::class]; + yield 'RuntimeException' => [RuntimeException::class, \RuntimeException::class]; + yield 'InvalidArgumentException' => [InvalidArgumentException::class, \InvalidArgumentException::class]; + yield 'LogicException' => [LogicException::class, \LogicException::class]; + } + + /** + * @param class-string<\Throwable> $class + * @param class-string<\Throwable> $splClass + */ + #[DataProvider('provideExceptions')] + public function testExtendsTheSplExceptionAndImplementsTheInterface(string $class, string $splClass): void + { + $exception = new $class('message', 12); + + $this->assertInstanceOf($splClass, $exception); + $this->assertInstanceOf(ProcessExceptionInterface::class, $exception); + $this->assertSame(['message', 12], [$exception->getMessage(), $exception->getCode()]); + } + + public function testBundleExceptionsCanBeCaughtByTheInterface(): void + { + try { + (new ImplodeTransformer())->transform('not an array', ['separator' => ',']); + $this->fail('No exception thrown'); + } catch (ProcessExceptionInterface $exception) { + $this->assertInstanceOf(\UnexpectedValueException::class, $exception); + } + } +}