From 73bf579da32e1c9c6b820a5adf85fc69f76549fc Mon Sep 17 00:00:00 2001 From: Nuno Maduro Date: Wed, 2 Jul 2025 00:26:15 +0100 Subject: [PATCH] chore: code refactor --- src/Plugins/Shard.php | 60 +++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 22 deletions(-) diff --git a/src/Plugins/Shard.php b/src/Plugins/Shard.php index c73601e0..9ac2c436 100644 --- a/src/Plugins/Shard.php +++ b/src/Plugins/Shard.php @@ -7,6 +7,7 @@ namespace Pest\Plugins; use Pest\Contracts\Plugins\HandlesArguments; use Pest\Exceptions\InvalidOption; use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Process\Process; /** @@ -35,28 +36,7 @@ final class Shard implements HandlesArguments // @phpstan-ignore-next-line $input = new ArgvInput($arguments); - if ($input->hasParameterOption('--'.self::SHARD_OPTION)) { - $shard = $input->getParameterOption('--'.self::SHARD_OPTION); - } else { - $shard = null; - } - - if (! is_string($shard) || ! preg_match('/^\d+\/\d+$/', $shard)) { - throw new InvalidOption('The [--shard] option must be in the format "index/total".'); - } - - [$index, $total] = explode('/', $shard); - - if (! is_numeric($index) || ! is_numeric($total)) { - throw new InvalidOption('The [--shard] option must be in the format "index/total".'); - } - - if ($index <= 0 || $total <= 0 || $index > $total) { - throw new InvalidOption('The [--shard] option index must be a non-negative integer less than the total number of shards.'); - } - - $index = (int) $index; - $total = (int) $total; + ['index' => $index, 'total' => $total] = self::getShard($input); $arguments = $this->popArgument("--shard=$index/$total", $this->popArgument('--shard', $this->popArgument( "$index/$total", @@ -105,4 +85,40 @@ final class Shard implements HandlesArguments { return addslashes(implode('|', $testsToRun)); } + + /** + * Returns the shard information. + * + * @return array{index: int, total: int} + */ + public static function getShard(InputInterface $input): array + { + if ($input->hasParameterOption('--'.self::SHARD_OPTION)) { + $shard = $input->getParameterOption('--'.self::SHARD_OPTION); + } else { + $shard = null; + } + + if (! is_string($shard) || ! preg_match('/^\d+\/\d+$/', $shard)) { + throw new InvalidOption('The [--shard] option must be in the format "index/total".'); + } + + [$index, $total] = explode('/', $shard); + + if (! is_numeric($index) || ! is_numeric($total)) { + throw new InvalidOption('The [--shard] option must be in the format "index/total".'); + } + + if ($index <= 0 || $total <= 0 || $index > $total) { + throw new InvalidOption('The [--shard] option index must be a non-negative integer less than the total number of shards.'); + } + + $index = (int) $index; + $total = (int) $total; + + return [ + 'index' => $index, + 'total' => $total, + ]; + } }