diff --git a/src/Command/CacheClearCommand.php b/src/Command/CacheClearCommand.php index 15b723a1ff0..f2f04757451 100644 --- a/src/Command/CacheClearCommand.php +++ b/src/Command/CacheClearCommand.php @@ -19,8 +19,6 @@ use Cake\Cache\Cache; use Cake\Cache\Engine\ApcuEngine; use Cake\Cache\Exception\InvalidArgumentException; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -69,26 +67,24 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar /** * Implement this method with your command's logic. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $name = (string)$args->getArgument('engine'); + $name = (string)$this->args->getArgument('engine'); try { - $io->out("Clearing {$name}"); + $this->io->out("Clearing {$name}"); $engine = Cache::pool($name); Cache::clear($name); if ($engine instanceof ApcuEngine) { - $io->warning("ApcuEngine detected: Cleared {$name} CLI cache successfully " . + $this->io->warning("ApcuEngine detected: Cleared {$name} CLI cache successfully " . "but {$name} web cache must be cleared separately."); } else { - $io->out("Cleared {$name} cache"); + $this->io->out("Cleared {$name} cache"); } } catch (InvalidArgumentException $e) { - $io->error($e->getMessage()); + $this->io->error($e->getMessage()); $this->abort(); } diff --git a/src/Command/CacheClearGroupCommand.php b/src/Command/CacheClearGroupCommand.php index 7d2c60f5657..58ce4d1a659 100644 --- a/src/Command/CacheClearGroupCommand.php +++ b/src/Command/CacheClearGroupCommand.php @@ -18,8 +18,6 @@ use Cake\Cache\Cache; use Cake\Cache\Exception\InvalidArgumentException; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -71,24 +69,22 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar /** * Clears the cache group * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $group = (string)$args->getArgument('group'); + $group = (string)$this->args->getArgument('group'); try { $groupConfigs = Cache::groupConfigs($group); } catch (InvalidArgumentException) { - $io->error(sprintf('Cache group "%s" not found', $group)); + $this->io->error(sprintf('Cache group "%s" not found', $group)); return static::CODE_ERROR; } - $config = $args->getArgument('config'); + $config = $this->args->getArgument('config'); if ($config !== null && Cache::getConfig($config) === null) { - $io->error(sprintf('Cache config "%s" not found', $config)); + $this->io->error(sprintf('Cache config "%s" not found', $config)); return static::CODE_ERROR; } @@ -99,14 +95,14 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int } if (!Cache::clearGroup($group, $groupConfig)) { - $io->error(sprintf( + $this->io->error(sprintf( 'Error encountered clearing group "%s". Was unable to clear entries for "%s".', $group, $groupConfig, )); $this->abort(); } else { - $io->success(sprintf('Cache "%s" was cleared.', $groupConfig)); + $this->io->success(sprintf('Cache "%s" was cleared.', $groupConfig)); } } diff --git a/src/Command/CacheClearallCommand.php b/src/Command/CacheClearallCommand.php index fceaa379204..81363d2b86f 100644 --- a/src/Command/CacheClearallCommand.php +++ b/src/Command/CacheClearallCommand.php @@ -17,8 +17,6 @@ namespace Cake\Command; use Cake\Cache\Cache; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -62,14 +60,12 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar /** * Implement this method with your command's logic. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { foreach (Cache::configured() as $engine) { - $this->executeCommand(CacheClearCommand::class, [$engine], $io); + $this->executeCommand(CacheClearCommand::class, [$engine]); } return static::CODE_SUCCESS; diff --git a/src/Command/CacheListCommand.php b/src/Command/CacheListCommand.php index b0ef972cb2d..26ae970cd3e 100644 --- a/src/Command/CacheListCommand.php +++ b/src/Command/CacheListCommand.php @@ -17,8 +17,6 @@ namespace Cake\Command; use Cake\Cache\Cache; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -60,14 +58,12 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar /** * Get the list of cache prefixes * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { foreach (Cache::configured() as $engine) { - $io->out("- {$engine}"); + $this->io->out("- {$engine}"); } return static::CODE_SUCCESS; diff --git a/src/Command/Command.php b/src/Command/Command.php index 46aedc36c2a..d0f2d8ea5c7 100644 --- a/src/Command/Command.php +++ b/src/Command/Command.php @@ -16,9 +16,7 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; use Cake\Console\BaseCommand; -use Cake\Console\ConsoleIoInterface; use Cake\Log\LogTrait; use Cake\ORM\Locator\LocatorAwareTrait; @@ -37,11 +35,9 @@ class Command extends BaseCommand /** * Implement this method with your command's logic. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null|void The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { } } diff --git a/src/Command/CompletionCommand.php b/src/Command/CompletionCommand.php index fe4512a2aed..a6857f60d26 100644 --- a/src/Command/CompletionCommand.php +++ b/src/Command/CompletionCommand.php @@ -16,11 +16,9 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; use Cake\Console\BaseCommand; use Cake\Console\CommandCollection; use Cake\Console\CommandCollectionAwareInterface; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use ReflectionClass; @@ -99,16 +97,14 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar /** * Main function Prints out the list of commands. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - return match ($args->getArgument('mode')) { - 'commands' => $this->getCommands($args, $io), - 'subcommands' => $this->getSubcommands($args, $io), - 'options' => $this->getOptions($args, $io), + return match ($this->args->getArgument('mode')) { + 'commands' => $this->getCommands(), + 'subcommands' => $this->getSubcommands(), + 'options' => $this->getOptions(), default => static::CODE_ERROR, }; } @@ -116,11 +112,9 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int /** * Get the list of defined commands. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int */ - protected function getCommands(Arguments $args, ConsoleIoInterface $io): int + protected function getCommands(): int { $options = []; foreach ($this->commands as $key => $value) { @@ -128,7 +122,7 @@ protected function getCommands(Arguments $args, ConsoleIoInterface $io): int $options[] = $parts[0]; } $options = array_unique($options); - $io->out(implode(' ', $options)); + $this->io->out(implode(' ', $options)); return static::CODE_SUCCESS; } @@ -136,13 +130,11 @@ protected function getCommands(Arguments $args, ConsoleIoInterface $io): int /** * Get the list of defined sub-commands. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int */ - protected function getSubcommands(Arguments $args, ConsoleIoInterface $io): int + protected function getSubcommands(): int { - $name = $args->getArgument('command'); + $name = $this->args->getArgument('command'); if ($name === null || $name === '') { return static::CODE_SUCCESS; } @@ -161,7 +153,7 @@ protected function getSubcommands(Arguments $args, ConsoleIoInterface $io): int } } $options = array_unique($options); - $io->out(implode(' ', $options)); + $this->io->out(implode(' ', $options)); return static::CODE_SUCCESS; } @@ -169,14 +161,12 @@ protected function getSubcommands(Arguments $args, ConsoleIoInterface $io): int /** * Get the options for a command or subcommand * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null */ - protected function getOptions(Arguments $args, ConsoleIoInterface $io): ?int + protected function getOptions(): ?int { - $name = $args->getArgument('command'); - $subcommand = $args->getArgument('subcommand'); + $name = $this->args->getArgument('command'); + $subcommand = $this->args->getArgument('subcommand'); $options = []; foreach ($this->commands as $key => $value) { @@ -191,28 +181,21 @@ protected function getOptions(Arguments $args, ConsoleIoInterface $io): ?int continue; } - // Handle class strings - if (is_string($value)) { - $reflection = new ReflectionClass($value); - $value = $reflection->newInstance(); - assert($value instanceof BaseCommand); - } - - if (method_exists($value, 'getOptionParser')) { - /** @var \Cake\Console\ConsoleOptionParser $parser */ - $parser = $value->getOptionParser(); + $reflection = new ReflectionClass($value); + $value = $reflection->newInstance(); + assert($value instanceof BaseCommand); - foreach ($parser->options() as $name => $option) { - $options[] = "--{$name}"; - $short = $option->short(); - if ($short) { - $options[] = "-{$short}"; - } + $parser = $value->getOptionParser(); + foreach ($parser->options() as $name => $option) { + $options[] = "--{$name}"; + $short = $option->short(); + if ($short) { + $options[] = "-{$short}"; } } } $options = array_unique($options); - $io->out(implode(' ', $options)); + $this->io->out(implode(' ', $options)); return static::CODE_SUCCESS; } diff --git a/src/Command/CounterCacheCommand.php b/src/Command/CounterCacheCommand.php index 4cd533ba1b7..4c9500ea001 100644 --- a/src/Command/CounterCacheCommand.php +++ b/src/Command/CounterCacheCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -47,35 +45,33 @@ public static function getDescription(): string * Updates the counter cache for the specified model and association based * on the model's counter cache behavior's configuration. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): int + public function execute(): int { - $table = $this->fetchTable($args->getArgument('model')); + $table = $this->fetchTable($this->args->getArgument('model')); if (!$table->hasBehavior('CounterCache')) { - $io->error('The specified model does not have the CounterCache behavior attached.'); + $this->io->error('The specified model does not have the CounterCache behavior attached.'); return static::CODE_ERROR; } $methodArgs = []; - if ($args->hasOption('assoc')) { - $methodArgs['assocName'] = $args->getOption('assoc'); + if ($this->args->hasOption('assoc')) { + $methodArgs['assocName'] = $this->args->getOption('assoc'); } - if ($args->hasOption('limit')) { - $methodArgs['limit'] = (int)$args->getOption('limit'); + if ($this->args->hasOption('limit')) { + $methodArgs['limit'] = (int)$this->args->getOption('limit'); } - if ($args->hasOption('page')) { - $methodArgs['page'] = (int)$args->getOption('page'); + if ($this->args->hasOption('page')) { + $methodArgs['page'] = (int)$this->args->getOption('page'); } /** @var \Cake\ORM\Table $table */ $table->getBehavior('CounterCache')->updateCounterCache(...$methodArgs); - $io->success('Counter cache updated successfully.'); + $this->io->success('Counter cache updated successfully.'); return static::CODE_SUCCESS; } diff --git a/src/Command/I18nCommand.php b/src/Command/I18nCommand.php index 924e5c50f4a..2ad38a938a3 100644 --- a/src/Command/I18nCommand.php +++ b/src/Command/I18nCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -36,37 +34,35 @@ public static function getDescription(): string /** * Execute interactive mode * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $io->out('I18n Command'); - $io->hr(); - $io->out('[E]xtract POT file from sources'); - $io->out('[I]nitialize a language from POT file'); - $io->out('[H]elp'); - $io->out('[Q]uit'); + $this->io->out('I18n Command'); + $this->io->hr(); + $this->io->out('[E]xtract POT file from sources'); + $this->io->out('[I]nitialize a language from POT file'); + $this->io->out('[H]elp'); + $this->io->out('[Q]uit'); do { - $choice = strtolower($io->askChoice('What would you like to do?', ['E', 'I', 'H', 'Q'])); + $choice = strtolower($this->io->askChoice('What would you like to do?', ['E', 'I', 'H', 'Q'])); $code = null; switch ($choice) { case 'e': - $code = $this->executeCommand(I18nExtractCommand::class, [], $io); + $code = $this->executeCommand(I18nExtractCommand::class, []); break; case 'i': - $code = $this->executeCommand(I18nInitCommand::class, [], $io); + $code = $this->executeCommand(I18nInitCommand::class, []); break; case 'h': - $io->out($this->getOptionParser()->help()); + $this->io->out($this->getOptionParser()->help()); break; case 'q': // Do nothing break; default: - $io->err( + $this->io->err( 'You have made an invalid selection. ' . 'Please choose a command to execute by entering E, I, H, or Q.', ); diff --git a/src/Command/I18nExtractCommand.php b/src/Command/I18nExtractCommand.php index a997549a141..e12a1612bce 100644 --- a/src/Command/I18nExtractCommand.php +++ b/src/Command/I18nExtractCommand.php @@ -17,7 +17,6 @@ namespace Cake\Command; use Cake\Command\Helper\ProgressHelper; -use Cake\Console\Arguments; use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Core\App; @@ -177,35 +176,33 @@ protected function getPaths(ConsoleIoInterface $io): void /** * Execute the command * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { $plugin = ''; - if ($args->getOption('exclude')) { - $this->exclude = explode(',', (string)$args->getOption('exclude')); + if ($this->args->getOption('exclude')) { + $this->exclude = explode(',', (string)$this->args->getOption('exclude')); } - if ($args->getOption('files')) { - $this->files = explode(',', (string)$args->getOption('files')); + if ($this->args->getOption('files')) { + $this->files = explode(',', (string)$this->args->getOption('files')); } - if ($args->getOption('paths')) { - $this->paths = explode(',', (string)$args->getOption('paths')); + if ($this->args->getOption('paths')) { + $this->paths = explode(',', (string)$this->args->getOption('paths')); } - if ($args->getOption('plugin')) { - $plugin = Inflector::camelize((string)$args->getOption('plugin')); + if ($this->args->getOption('plugin')) { + $plugin = Inflector::camelize((string)$this->args->getOption('plugin')); if ($this->paths === []) { $this->paths = [Plugin::classPath($plugin), Plugin::templatePath($plugin)]; } - } elseif (!$args->getOption('paths')) { - $this->getPaths($io); + } elseif (!$this->args->getOption('paths')) { + $this->getPaths($this->io); } - if ($args->hasOption('extract-core')) { - $this->extractCore = strtolower((string)$args->getOption('extract-core')) !== 'no'; + if ($this->args->hasOption('extract-core')) { + $this->extractCore = strtolower((string)$this->args->getOption('extract-core')) !== 'no'; } else { - $response = $io->askChoice( + $response = $this->io->askChoice( 'Would you like to extract the messages from the CakePHP core?', ['y', 'n'], 'n', @@ -213,7 +210,7 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int $this->extractCore = strtolower($response) === 'y'; } - if ($args->hasOption('exclude-plugins') && $this->isExtractingApp()) { + if ($this->args->hasOption('exclude-plugins') && $this->isExtractingApp()) { $this->exclude = array_merge($this->exclude, array_values(App::path('plugins'))); } @@ -221,9 +218,9 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int $this->paths[] = CAKE; } - if ($args->hasOption('output')) { - $this->output = (string)$args->getOption('output'); - } elseif ($args->hasOption('plugin')) { + if ($this->args->hasOption('output')) { + $this->output = (string)$this->args->getOption('output'); + } elseif ($this->args->hasOption('plugin')) { $this->output = Plugin::path($plugin) . 'resources' . DIRECTORY_SEPARATOR . 'locales' . DIRECTORY_SEPARATOR; @@ -236,12 +233,12 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int . 'locales' . DIRECTORY_SEPARATOR; } while (true) { - $response = $io->ask( + $response = $this->io->ask( $message, $localePaths[0], ); if (strtoupper($response) === 'Q') { - $io->error('Extract Aborted'); + $this->io->error('Extract Aborted'); return static::CODE_ERROR; } @@ -250,20 +247,20 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int break; } - $io->err(''); - $io->error( + $this->io->err(''); + $this->io->error( 'The directory path you supplied was ' . 'not found. Please try again.', ); - $io->err(''); + $this->io->err(''); } } - if ($args->hasOption('merge')) { - $this->merge = strtolower((string)$args->getOption('merge')) !== 'no'; + if ($this->args->hasOption('merge')) { + $this->merge = strtolower((string)$this->args->getOption('merge')) !== 'no'; } else { - $io->out(); - $response = $io->askChoice( + $this->io->out(); + $response = $this->io->askChoice( 'Would you like to merge all domain strings into the default.pot file?', ['y', 'n'], 'n', @@ -271,7 +268,7 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int $this->merge = strtolower($response) === 'y'; } - $this->markerError = (bool)$args->getOption('marker-error'); + $this->markerError = (bool)$this->args->getOption('marker-error'); if (!$this->files) { $this->searchFiles(); @@ -279,12 +276,12 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int $this->output = rtrim($this->output, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if (!$this->isPathUsable($this->output)) { - $io->error(sprintf('The output directory `%s` was not found or writable.', $this->output)); + $this->io->error(sprintf('The output directory `%s` was not found or writable.', $this->output)); return static::CODE_ERROR; } - $this->extract($args, $io); + $this->extract(); return static::CODE_SUCCESS; } @@ -322,37 +319,35 @@ protected function addTranslation(string $domain, string $msgid, array $details /** * Extract text * - * @param \Cake\Console\Arguments $args The Arguments instance - * @param \Cake\Console\ConsoleIoInterface $io The io instance * @return void */ - protected function extract(Arguments $args, ConsoleIoInterface $io): void + protected function extract(): void { - $io->out(); - $io->out(); - $io->out('Extracting...'); - $io->hr(); - $io->out('Paths:'); + $this->io->out(); + $this->io->out(); + $this->io->out('Extracting...'); + $this->io->hr(); + $this->io->out('Paths:'); foreach ($this->paths as $path) { - $io->out(' ' . $path); + $this->io->out(' ' . $path); } - $io->out('Output Directory: ' . $this->output); - $io->hr(); - $this->extractTokens($args, $io); - $this->buildFiles($args); - $this->writeFiles($args, $io); + $this->io->out('Output Directory: ' . $this->output); + $this->io->hr(); + $this->extractTokens(); + $this->buildFiles(); + $this->writeFiles(); $this->paths = []; $this->files = []; $this->storage = []; $this->translations = []; $this->tokens = []; - $io->out(); + $this->io->out(); if ($this->countMarkerError) { - $io->error("{$this->countMarkerError} marker error(s) detected."); - $io->err(' => Use the --marker-error option to display errors.'); + $this->io->error("{$this->countMarkerError} marker error(s) detected."); + $this->io->err(' => Use the --marker-error option to display errors.'); } - $io->out('Done.'); + $this->io->out('Done.'); } /** @@ -413,16 +408,14 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar /** * Extract tokens out of all files to be processed * - * @param \Cake\Console\Arguments $args The io instance - * @param \Cake\Console\ConsoleIoInterface $io The io instance * @return void */ - protected function extractTokens(Arguments $args, ConsoleIoInterface $io): void + protected function extractTokens(): void { - $progress = $io->helper('progress'); + $progress = $this->io->helper('progress'); assert($progress instanceof ProgressHelper); $progress->init(['total' => count($this->files)]); - $isVerbose = $args->getOption('verbose'); + $isVerbose = $this->args->getOption('verbose'); $functions = [ '__' => ['singular'], @@ -439,7 +432,7 @@ protected function extractTokens(Arguments $args, ConsoleIoInterface $io): void foreach ($this->files as $file) { $this->file = $file; if ($isVerbose) { - $io->verbose(sprintf('Processing %s...', $file)); + $this->io->verbose(sprintf('Processing %s...', $file)); } $code = (string)file_get_contents($file); @@ -456,7 +449,7 @@ protected function extractTokens(Arguments $args, ConsoleIoInterface $io): void unset($allTokens); foreach ($functions as $functionName => $map) { - $this->parse($io, $functionName, $map); + $this->parse($this->io, $functionName, $map); } } @@ -533,10 +526,9 @@ protected function parse(ConsoleIoInterface $io, string $functionName, array $ma /** * Build the translate template file contents out of obtained strings * - * @param \Cake\Console\Arguments $args Console arguments * @return void */ - protected function buildFiles(Arguments $args): void + protected function buildFiles(): void { $paths = $this->paths; $paths[] = realpath(APP) . DIRECTORY_SEPARATOR; @@ -552,7 +544,7 @@ protected function buildFiles(Arguments $args): void $files = $details['references']; $header = ''; - if (!$args->getOption('no-location')) { + if (!$this->args->getOption('no-location')) { $occurrences = []; foreach ($files as $file => $lines) { $lines = array_unique($lines); @@ -613,15 +605,13 @@ protected function store(string $domain, string $header, string $sentence): void /** * Write the files that need to be stored * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return void */ - protected function writeFiles(Arguments $args, ConsoleIoInterface $io): void + protected function writeFiles(): void { - $io->out(); + $this->io->out(); $overwriteAll = false; - if ($args->getOption('overwrite')) { + if ($this->args->getOption('overwrite')) { $overwriteAll = true; } foreach ($this->storage as $domain => $sentences) { @@ -635,14 +625,14 @@ protected function writeFiles(Arguments $args, ConsoleIoInterface $io): void $outputPath = $this->output . $filename; if ($this->checkUnchanged($outputPath, $headerLength, $output)) { - $io->out($filename . ' is unchanged. Skipping.'); + $this->io->out($filename . ' is unchanged. Skipping.'); continue; } $response = ''; while ($overwriteAll === false && file_exists($outputPath) && strtoupper($response) !== 'Y') { - $io->out(); - $response = $io->askChoice( + $this->io->out(); + $response = $this->io->askChoice( sprintf('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename), ['y', 'n', 'a'], 'y', @@ -650,7 +640,7 @@ protected function writeFiles(Arguments $args, ConsoleIoInterface $io): void if (strtoupper($response) === 'N') { $response = ''; while (!$response) { - $response = $io->ask('What would you like to name this file?', 'new_' . $filename); + $response = $this->io->ask('What would you like to name this file?', 'new_' . $filename); $filename = $response; } } elseif (strtoupper($response) === 'A') { diff --git a/src/Command/I18nInitCommand.php b/src/Command/I18nInitCommand.php index bce2d0d44ca..9e5f9b3d949 100644 --- a/src/Command/I18nInitCommand.php +++ b/src/Command/I18nInitCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Core\App; use Cake\Core\Exception\CakeException; @@ -49,29 +47,27 @@ public static function getDescription(): string /** * Execute the command * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $language = $args->getArgument('language'); + $language = $this->args->getArgument('language'); if (!$language) { - $language = $io->ask('Please specify language code, e.g. `en`, `eng`, `en_US` etc.'); + $language = $this->io->ask('Please specify language code, e.g. `en`, `eng`, `en_US` etc.'); } if (strlen($language) < 2) { - $io->error('Invalid language code. Valid is `en`, `eng`, `en_US` etc.'); + $this->io->error('Invalid language code. Valid is `en`, `eng`, `en_US` etc.'); return static::CODE_ERROR; } $paths = array_values(App::path('locales')); - if ($args->hasOption('plugin')) { - $plugin = Inflector::camelize((string)$args->getOption('plugin')); + if ($this->args->hasOption('plugin')) { + $plugin = Inflector::camelize((string)$this->args->getOption('plugin')); $paths = [Plugin::path($plugin) . 'resources' . DIRECTORY_SEPARATOR . 'locales' . DIRECTORY_SEPARATOR]; } - $response = $io->ask('What folder?', rtrim($paths[0], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR); + $response = $this->io->ask('What folder?', rtrim($paths[0], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR); $sourceFolder = rtrim($response, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $targetFolder = $sourceFolder . $language . DIRECTORY_SEPARATOR; if (!is_dir($targetFolder)) { @@ -92,11 +88,11 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int if ($content === false) { throw new CakeException(sprintf('Cannot read file content of `%s`', $sourceFolder . $filename)); } - $io->createFile($targetFolder . $newFilename, $content); + $this->io->createFile($targetFolder . $newFilename, $content); $count++; } - $io->out('Generated ' . $count . ' PO files in ' . $targetFolder); + $this->io->out('Generated ' . $count . ' PO files in ' . $targetFolder); return static::CODE_SUCCESS; } diff --git a/src/Command/PluginAssetsCopyCommand.php b/src/Command/PluginAssetsCopyCommand.php index 84229c077c5..13715b6d2f6 100644 --- a/src/Command/PluginAssetsCopyCommand.php +++ b/src/Command/PluginAssetsCopyCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -49,17 +47,12 @@ public static function getDescription(): string * Copying plugin assets to app's webroot. For vendor namespaced plugin, * parent folder for vendor name are created if required. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $this->io = $io; - $this->args = $args; - - $name = $args->getArgument('name'); - $overwrite = (bool)$args->getOption('overwrite'); + $name = $this->args->getArgument('name'); + $overwrite = (bool)$this->args->getOption('overwrite'); $this->process($this->list($name), true, $overwrite); return static::CODE_SUCCESS; diff --git a/src/Command/PluginAssetsRemoveCommand.php b/src/Command/PluginAssetsRemoveCommand.php index 96463091710..0124887fcbe 100644 --- a/src/Command/PluginAssetsRemoveCommand.php +++ b/src/Command/PluginAssetsRemoveCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -48,16 +46,11 @@ public static function getDescription(): string * * Remove plugin assets from app's webroot. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $this->io = $io; - $this->args = $args; - - $name = $args->getArgument('name'); + $name = $this->args->getArgument('name'); $plugins = $this->list($name); foreach ($plugins as $plugin => $config) { diff --git a/src/Command/PluginAssetsSymlinkCommand.php b/src/Command/PluginAssetsSymlinkCommand.php index 1c53e7a34dc..ebce8b14b87 100644 --- a/src/Command/PluginAssetsSymlinkCommand.php +++ b/src/Command/PluginAssetsSymlinkCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; /** @@ -50,18 +48,13 @@ public static function getDescription(): string * fallbacks to copying the assets. For vendor namespaced plugin, parent folder * for vendor name are created if required. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $this->io = $io; - $this->args = $args; - - $name = $args->getArgument('name'); - $overwrite = (bool)$args->getOption('overwrite'); - $relative = (bool)$args->getOption('relative'); + $name = $this->args->getArgument('name'); + $overwrite = (bool)$this->args->getOption('overwrite'); + $relative = (bool)$this->args->getOption('relative'); $this->process($this->list($name), false, $overwrite, $relative); return static::CODE_SUCCESS; diff --git a/src/Command/PluginAssetsTrait.php b/src/Command/PluginAssetsTrait.php index 1066af5f05b..6730d448239 100644 --- a/src/Command/PluginAssetsTrait.php +++ b/src/Command/PluginAssetsTrait.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Utility\Filesystem; @@ -31,20 +29,6 @@ */ trait PluginAssetsTrait { - /** - * Arguments - * - * @var \Cake\Console\Arguments - */ - protected Arguments $args; - - /** - * Console IO - * - * @var \Cake\Console\ConsoleIoInterface - */ - protected ConsoleIoInterface $io; - /** * Get list of plugins to process. Plugins without a webroot directory are skipped. * diff --git a/src/Command/PluginListCommand.php b/src/Command/PluginListCommand.php index 16c1f2640e6..39222bab540 100644 --- a/src/Command/PluginListCommand.php +++ b/src/Command/PluginListCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Core\Plugin; use Cake\Core\PluginConfig; @@ -47,14 +45,12 @@ public static function getDescription(): string /** * Displays all currently available plugins. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { $loadedPluginsCollection = Plugin::getCollection(); - $path = (string)$args->getOption('composer-path'); + $path = (string)$this->args->getOption('composer-path'); $config = PluginConfig::getAppConfig($path ?: null); $table = [ @@ -62,7 +58,7 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int ]; if ($config === []) { - $io->warning(__d('cake', 'No plugins have been found.')); + $this->io->warning(__d('cake', 'No plugins have been found.')); return static::CODE_ERROR; } @@ -82,7 +78,7 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int $version, ]; } - $io->helper('Table')->output($table); + $this->io->helper('Table')->output($table); return static::CODE_SUCCESS; } diff --git a/src/Command/PluginLoadCommand.php b/src/Command/PluginLoadCommand.php index 65fe03924bb..62173665edc 100644 --- a/src/Command/PluginLoadCommand.php +++ b/src/Command/PluginLoadCommand.php @@ -17,8 +17,6 @@ namespace Cake\Command; use Brick\VarExporter\VarExporter; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Core\Exception\MissingPluginException; use Cake\Core\Plugin; @@ -66,26 +64,24 @@ public static function getDescription(): string /** * Execute the command * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $plugin = (string)$args->getArgument('plugin'); + $plugin = (string)$this->args->getArgument('plugin'); $options = []; - if ($args->getOption('only-debug')) { + if ($this->args->getOption('only-debug')) { $options['onlyDebug'] = true; } - if ($args->getOption('only-cli')) { + if ($this->args->getOption('only-cli')) { $options['onlyCli'] = true; } - if ($args->getOption('optional')) { + if ($this->args->getOption('optional')) { $options['optional'] = true; } foreach (PluginInterface::VALID_HOOKS as $hook) { - if ($args->getOption('no-' . $hook)) { + if ($this->args->getOption('no-' . $hook)) { $options[$hook] = false; } } @@ -95,8 +91,8 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int $path = Plugin::getCollection()->findPath($plugin); } catch (MissingPluginException $e) { if (empty($options['optional'])) { - $io->error($e->getMessage()); - $io->error('Ensure you have the correct spelling and casing.'); + $this->io->error($e->getMessage()); + $this->io->error('Ensure you have the correct spelling and casing.'); return static::CODE_ERROR; } @@ -111,7 +107,7 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int $option = $name . ': ' . ($v ? 'true' : 'false'); $question = 'Based on the plugin composer keywords, this seems to be `' . $option . '`. '; $question .= 'Do you want to change this?'; - $in = $io->askChoice($question, ['y', 'n'], 'y'); + $in = $this->io->askChoice($question, ['y', 'n'], 'y'); if ($in !== 'y') { continue; } @@ -121,10 +117,10 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int $result = $this->modifyConfigFile($plugin, $options); if ($result === static::CODE_ERROR) { - $io->error('Failed to update `CONFIG/plugins.php`'); + $this->io->error('Failed to update `CONFIG/plugins.php`'); } - $io->success('Plugin added successfully to `CONFIG/plugins.php`'); + $this->io->success('Plugin added successfully to `CONFIG/plugins.php`'); return $result; } diff --git a/src/Command/PluginLoadedCommand.php b/src/Command/PluginLoadedCommand.php index d247b5c04b7..b7948318083 100644 --- a/src/Command/PluginLoadedCommand.php +++ b/src/Command/PluginLoadedCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Core\Plugin; @@ -45,14 +43,12 @@ public static function getDescription(): string /** * Displays all currently loaded plugins. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { $loaded = Plugin::loaded(); - $io->out($loaded); + $this->io->out($loaded); return static::CODE_SUCCESS; } diff --git a/src/Command/PluginUnloadCommand.php b/src/Command/PluginUnloadCommand.php index 24d3c8b8c4b..a9800a32962 100644 --- a/src/Command/PluginUnloadCommand.php +++ b/src/Command/PluginUnloadCommand.php @@ -17,8 +17,6 @@ namespace Cake\Command; use Brick\VarExporter\VarExporter; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Utility\Hash; @@ -53,22 +51,20 @@ public static function getDescription(): string /** * Execute the command * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $plugin = (string)$args->getArgument('plugin'); + $plugin = (string)$this->args->getArgument('plugin'); $result = $this->modifyConfigFile($plugin); if ($result === null) { - $io->success('Plugin removed from `CONFIG/plugins.php`'); + $this->io->success('Plugin removed from `CONFIG/plugins.php`'); return static::CODE_SUCCESS; } - $io->err($result); + $this->io->err($result); return static::CODE_ERROR; } diff --git a/src/Command/RoutesCheckCommand.php b/src/Command/RoutesCheckCommand.php index cd58f26f4cf..9193c85604a 100644 --- a/src/Command/RoutesCheckCommand.php +++ b/src/Command/RoutesCheckCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Http\Exception\RedirectException; use Cake\Http\ServerRequest; @@ -48,14 +46,12 @@ public static function getDescription(): string /** * Display all routes in an application * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success * @throws \JsonException */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $url = $args->getArgument('url'); + $url = $this->args->getArgument('url'); try { $parsed = Router::parseRequest(new ServerRequest(['url' => $url])); $name = $parsed['_name'] ?? $parsed['_route']->getName(); @@ -67,18 +63,18 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int ['Route name', 'URI template', 'Defaults'], [$name, $url, json_encode($parsed, JSON_THROW_ON_ERROR)], ]; - $io->helper('table')->output($output); - $io->out(); + $this->io->helper('table')->output($output); + $this->io->out(); } catch (RedirectException $e) { $output = [ ['URI template', 'Redirect'], [$url, $e->getMessage()], ]; - $io->helper('table')->output($output); - $io->out(); + $this->io->helper('table')->output($output); + $this->io->out(); } catch (MissingRouteException) { - $io->warning("'{$url}' did not match any routes."); - $io->out(); + $this->io->warning("'{$url}' did not match any routes."); + $this->io->out(); return static::CODE_ERROR; } diff --git a/src/Command/RoutesCommand.php b/src/Command/RoutesCommand.php index 550bba02b52..3b5a24743cc 100644 --- a/src/Command/RoutesCommand.php +++ b/src/Command/RoutesCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Routing\Router; @@ -37,18 +35,16 @@ public static function getDescription(): string /** * Display all routes in an application * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success * @throws \JsonException */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { $header = ['Route name', 'URI template', 'Plugin', 'Prefix', 'Controller', 'Action', 'Method(s)']; - if ($args->getOption('with-middlewares') || $args->getOption('verbose')) { + if ($this->args->getOption('with-middlewares') || $this->args->getOption('verbose')) { $header[] = 'Middlewares'; } - if ($args->getOption('verbose')) { + if ($this->args->getOption('verbose')) { $header[] = 'Defaults'; } @@ -69,10 +65,10 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int implode(', ', $methods), ]; - if ($args->getOption('with-middlewares') || $args->getOption('verbose')) { + if ($this->args->getOption('with-middlewares') || $this->args->getOption('verbose')) { $item[] = implode(', ', $route->getMiddleware()); } - if ($args->getOption('verbose')) { + if ($this->args->getOption('verbose')) { ksort($route->defaults); $item[] = json_encode($route->defaults, JSON_THROW_ON_ERROR); } @@ -85,7 +81,7 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int } } - if ($args->getOption('sort')) { + if ($this->args->getOption('sort')) { usort($output, function (array $a, array $b) { return strcasecmp($a[0], $b[0]); }); @@ -93,8 +89,8 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int array_unshift($output, $header); - $io->helper('table')->output($output); - $io->out(); + $this->io->helper('table')->output($output); + $this->io->out(); $duplicateRoutes = []; @@ -124,9 +120,9 @@ public function execute(Arguments $args, ConsoleIoInterface $io): ?int if ($duplicateRoutes) { array_unshift($duplicateRoutes, $header); - $io->warning('The following possible route collisions were detected.'); - $io->helper('table')->output($duplicateRoutes); - $io->out(); + $this->io->warning('The following possible route collisions were detected.'); + $this->io->helper('table')->output($duplicateRoutes); + $this->io->out(); } return static::CODE_SUCCESS; diff --git a/src/Command/RoutesGenerateCommand.php b/src/Command/RoutesGenerateCommand.php index 2ab7c83ec89..917e94ed0c8 100644 --- a/src/Command/RoutesGenerateCommand.php +++ b/src/Command/RoutesGenerateCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Routing\Exception\MissingRouteException; use Cake\Routing\Router; @@ -46,20 +44,18 @@ public static function getDescription(): string /** * Display all routes in an application * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { try { - $args = $this->splitArgs($args->getArguments()); + $args = $this->splitArgs($this->args->getArguments()); $url = Router::url($args); - $io->out("> {$url}"); - $io->out(); + $this->io->out("> {$url}"); + $this->io->out(); } catch (MissingRouteException) { - $io->warning('The provided parameters do not match any routes.'); - $io->out(); + $this->io->warning('The provided parameters do not match any routes.'); + $this->io->out(); return static::CODE_ERROR; } diff --git a/src/Command/SchemacacheBuildCommand.php b/src/Command/SchemacacheBuildCommand.php index d3a49eabb2d..f255cccefac 100644 --- a/src/Command/SchemacacheBuildCommand.php +++ b/src/Command/SchemacacheBuildCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Database\Connection; use Cake\Database\SchemaCache; @@ -50,29 +48,27 @@ public static function getDescription(): string /** * Display all routes in an application * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { try { - $connection = ConnectionManager::get((string)$args->getOption('connection')); + $connection = ConnectionManager::get((string)$this->args->getOption('connection')); assert($connection instanceof Connection); $cache = new SchemaCache($connection); } catch (RuntimeException $e) { - $io->error($e->getMessage()); + $this->io->error($e->getMessage()); return static::CODE_ERROR; } - $tables = $cache->build($args->getArgument('name')); + $tables = $cache->build($this->args->getArgument('name')); foreach ($tables as $table) { - $io->verbose(sprintf('Cached `%s`', $table)); + $this->io->verbose(sprintf('Cached `%s`', $table)); } - $io->out('Cache build complete'); + $this->io->out('Cache build complete'); return static::CODE_SUCCESS; } diff --git a/src/Command/SchemacacheClearCommand.php b/src/Command/SchemacacheClearCommand.php index 7b10967fb2c..753f16f439f 100644 --- a/src/Command/SchemacacheClearCommand.php +++ b/src/Command/SchemacacheClearCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Database\Connection; use Cake\Database\SchemaCache; @@ -50,29 +48,27 @@ public static function getDescription(): string /** * Display all routes in an application * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { try { - $connection = ConnectionManager::get((string)$args->getOption('connection')); + $connection = ConnectionManager::get((string)$this->args->getOption('connection')); assert($connection instanceof Connection); $cache = new SchemaCache($connection); } catch (RuntimeException $e) { - $io->error($e->getMessage()); + $this->io->error($e->getMessage()); return static::CODE_ERROR; } - $tables = $cache->clear($args->getArgument('name')); + $tables = $cache->clear($this->args->getArgument('name')); foreach ($tables as $table) { - $io->verbose(sprintf('Cleared `%s`', $table)); + $this->io->verbose(sprintf('Cleared `%s`', $table)); } - $io->out('Cache clear complete'); + $this->io->out('Cache clear complete'); return static::CODE_SUCCESS; } diff --git a/src/Command/ServerCommand.php b/src/Command/ServerCommand.php index da0e77c0f2f..ec3b36e595c 100644 --- a/src/Command/ServerCommand.php +++ b/src/Command/ServerCommand.php @@ -17,8 +17,6 @@ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Core\Configure; use function Cake\Core\env; @@ -89,26 +87,24 @@ public static function getDescription(): string * Starts up the Command and displays the welcome message. * Allows for checking and configuring prior to command or main execution * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return void * @link https://book.cakephp.org/5/en/console-and-shells.html#hook-methods */ - protected function startup(Arguments $args, ConsoleIoInterface $io): void + protected function startup(): void { - if ($args->getOption('host')) { - $this->host = (string)$args->getOption('host'); + if ($this->args->getOption('host')) { + $this->host = (string)$this->args->getOption('host'); } - if ($args->getOption('port')) { - $this->port = (int)$args->getOption('port'); + if ($this->args->getOption('port')) { + $this->port = (int)$this->args->getOption('port'); } - if ($args->getOption('document_root')) { - $this->documentRoot = (string)$args->getOption('document_root'); + if ($this->args->getOption('document_root')) { + $this->documentRoot = (string)$this->args->getOption('document_root'); } - if ($args->getOption('ini_path')) { - $this->iniPath = (string)$args->getOption('ini_path'); + if ($this->args->getOption('ini_path')) { + $this->iniPath = (string)$this->args->getOption('ini_path'); } - if ($args->getOption('frankenphp')) { + if ($this->args->getOption('frankenphp')) { $this->server = 'frankenphp'; } @@ -125,34 +121,32 @@ protected function startup(Arguments $args, ConsoleIoInterface $io): void $this->iniPath = $m[1] . '\\' . $m[2]; } - $io->out(); - $io->out(sprintf('Welcome to CakePHP %s Console', 'v' . Configure::version())); - $io->hr(); - $io->out(sprintf('App : %s', Configure::read('App.dir'))); - $io->out(sprintf('Path: %s', APP)); - $io->out(sprintf('DocumentRoot: %s', $this->documentRoot)); - $io->out(sprintf('Ini Path: %s', $this->iniPath)); - $io->hr(); + $this->io->out(); + $this->io->out(sprintf('Welcome to CakePHP %s Console', 'v' . Configure::version())); + $this->io->hr(); + $this->io->out(sprintf('App : %s', Configure::read('App.dir'))); + $this->io->out(sprintf('Path: %s', APP)); + $this->io->out(sprintf('DocumentRoot: %s', $this->documentRoot)); + $this->io->out(sprintf('Ini Path: %s', $this->iniPath)); + $this->io->hr(); } /** * Execute. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int The exit code */ - public function execute(Arguments $args, ConsoleIoInterface $io): int + public function execute(): int { - $this->startup($args, $io); + $this->startup(); - $io->out(sprintf( + $this->io->out(sprintf( '%s server is running at http://%s:%s/', $this->server, $this->host, $this->port, )); - $io->out('You can exit with `CTRL-C`'); + $this->io->out('You can exit with `CTRL-C`'); return $this->runCommand($this->{$this->server . 'Command'}()); } diff --git a/src/Command/VersionCommand.php b/src/Command/VersionCommand.php index 39dc65515aa..5110620170b 100644 --- a/src/Command/VersionCommand.php +++ b/src/Command/VersionCommand.php @@ -16,8 +16,6 @@ */ namespace Cake\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Core\Configure; /** @@ -36,13 +34,11 @@ public static function getDescription(): string /** * Print out the version of CakePHP in use. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $io->out(Configure::version()); + $this->io->out(Configure::version()); return static::CODE_SUCCESS; } diff --git a/src/Console/BaseCommand.php b/src/Console/BaseCommand.php index 51bb002efbb..1928f073c9f 100644 --- a/src/Console/BaseCommand.php +++ b/src/Console/BaseCommand.php @@ -61,16 +61,28 @@ abstract class BaseCommand implements CommandInterface, EventDispatcherInterface */ protected string $name = 'cake unknown'; - protected ?CommandFactoryInterface $factory = null; + /** + * The IO instance to interact with IO + * + * @var \Cake\Console\ConsoleIoInterface + */ + protected ConsoleIoInterface $io; + + /** + * The arguments instance which holds the parsed arguments and options + * + * @var \Cake\Console\Arguments + */ + protected Arguments $args; /** * Constructor * - * @param \Cake\Console\CommandFactoryInterface|null $factory Command factory instance. + * @param \Cake\Console\CommandFactoryInterface|null $factory The factory, which is needed to invoke more commands */ - public function __construct(?CommandFactoryInterface $factory = null) - { - $this->factory = $factory; + public function __construct( + protected ?CommandFactoryInterface $factory = null, + ) { $this->getEventManager()->on($this); } @@ -120,6 +132,15 @@ public function getRootName(): string return $root; } + /** + * @param \Cake\Console\ConsoleIoInterface $io + * @return void + */ + public function setIo(ConsoleIoInterface $io): void + { + $this->io = $io; + } + /** * Get the command name. * @@ -198,8 +219,6 @@ public function implementedEvents(): array * command or perform logic that needs to happen before the command runs. * * @param \Cake\Event\EventInterface<\Cake\Console\BaseCommand> $event An Event instance - * @param \Cake\Console\Arguments $args - * @param \Cake\Console\ConsoleIoInterface $io * @return void * @link https://book.cakephp.org/5/en/console-commands/commands.html#lifecycle-callbacks */ @@ -212,8 +231,6 @@ public function beforeExecute(EventInterface $event, Arguments $args, ConsoleIoI * perform logic that needs to happen after the command runs. * * @param \Cake\Event\EventInterface<\Cake\Console\BaseCommand> $event An Event instance - * @param \Cake\Console\Arguments $args - * @param \Cake\Console\ConsoleIoInterface $io * @param int|null $result * @return void * @link https://book.cakephp.org/5/en/console-commands/commands.html#lifecycle-callbacks @@ -225,39 +242,38 @@ public function afterExecute(EventInterface $event, Arguments $args, ConsoleIoIn /** * @inheritDoc */ - public function run(array $argv, ConsoleIoInterface $io): ?int + public function run(array $argv, ?ConsoleIoInterface $io = null): ?int { - $this->initialize(); + if ($io !== null) { + $this->io = $io; + } $parser = $this->getOptionParser(); try { - [$options, $arguments] = $parser->parse($argv, $io); - $args = new Arguments( - $arguments, - $options, - $parser->argumentNames(), - ); + $this->parseArguments($parser, $argv); } catch (ConsoleException $e) { - $io->error('Error: ' . $e->getMessage()); + $this->io->error('Error: ' . $e->getMessage()); return static::CODE_ERROR; } - $this->setOutputLevel($args, $io); + $this->setOutputLevel(); - if ($args->getOption('help')) { - $this->displayHelp($parser, $args, $io); + if ($this->args->getOption('help')) { + $this->displayHelp($parser); return static::CODE_SUCCESS; } - if ($args->getOption('quiet')) { - $io->setInteractive(false); + if ($this->args->getOption('quiet')) { + $this->io->setInteractive(false); } - $this->dispatchEvent('Command.beforeExecute', ['args' => $args, 'io' => $io]); + $this->initialize(); + + $this->dispatchEvent('Command.beforeExecute', ['args' => $this->args, 'io' => $this->io]); /** @var int|null $result */ - $result = $this->execute($args, $io); - $this->dispatchEvent('Command.afterExecute', ['args' => $args, 'io' => $io, 'result' => $result]); + $result = $this->execute(); + $this->dispatchEvent('Command.afterExecute', ['args' => $this->args, 'io' => $this->io, 'result' => $result]); return $result; } @@ -266,49 +282,61 @@ public function run(array $argv, ConsoleIoInterface $io): ?int * Output help content * * @param \Cake\Console\ConsoleOptionParser $parser The option parser. - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return void */ - protected function displayHelp(ConsoleOptionParser $parser, Arguments $args, ConsoleIoInterface $io): void + protected function displayHelp(ConsoleOptionParser $parser): void { $format = 'text'; - if ($args->getArgumentAt(0) === 'xml') { + if ($this->args->getArgumentAt(0) === 'xml') { $format = 'xml'; - $io->setOutputAs(ConsoleOutput::RAW); + $this->io->setOutputAs(ConsoleOutput::RAW); } - $io->out($parser->help($format)); + $this->io->out($parser->help($format)); } /** * Set the output level based on the Arguments. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return void */ - protected function setOutputLevel(Arguments $args, ConsoleIoInterface $io): void + protected function setOutputLevel(): void { - $io->setLoggers(ConsoleIoInterface::NORMAL); - if ($args->getOption('quiet')) { - $io->level(ConsoleIoInterface::QUIET); - $io->setLoggers(ConsoleIoInterface::QUIET); + $this->io->setLoggers(ConsoleIoInterface::NORMAL); + if ($this->args->getOption('quiet')) { + $this->io->level(ConsoleIoInterface::QUIET); + $this->io->setLoggers(ConsoleIoInterface::QUIET); } - if ($args->getOption('verbose')) { - $io->level(ConsoleIoInterface::VERBOSE); - $io->setLoggers(ConsoleIoInterface::VERBOSE); + if ($this->args->getOption('verbose')) { + $this->io->level(ConsoleIoInterface::VERBOSE); + $this->io->setLoggers(ConsoleIoInterface::VERBOSE); } } + /** + * Parses the command-line arguments using the provided option parser and assigns + * the parsed options and arguments to the command's arguments property. + * + * @param \Cake\Console\ConsoleOptionParser $parser + * @param array $argv + * @return void + */ + protected function parseArguments(ConsoleOptionParser $parser, array $argv): void + { + [$options, $arguments] = $parser->parse($argv, $this->io); + $this->args = new Arguments( + $arguments, + $options, + $parser->argumentNames(), + ); + } + /** * Implement this method with your command's logic. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null|void The exit code or null for success */ - abstract public function execute(Arguments $args, ConsoleIoInterface $io); + abstract public function execute(); /** * Halt the current process with a StopException. @@ -329,7 +357,7 @@ public function abort(int $code = self::CODE_ERROR): never * will not be resolved with the application container. Instead you will * need to pass the command as an object with all of its dependencies. * - * @param \Cake\Console\CommandInterface|string $command The command class name or command instance. + * @param \Cake\Console\CommandInterface|class-string<\Cake\Console\CommandInterface> $command The command class name or command instance. * @param array $args The arguments to invoke the command with. * @param \Cake\Console\ConsoleIoInterface|null $io The ConsoleIo instance to use for the executed command. * @return int|null The exit code or null for success of the command. @@ -347,10 +375,9 @@ public function executeCommand( $command = $this->factory?->create($command) ?? new $command(); } - $io = $io ?: new ConsoleIo(); try { - return $command->run($args, $io); + return $command->run($args, $io ?? $this->io); } catch (StopException $e) { return $e->getCode(); } diff --git a/src/Console/Command/HelpCommand.php b/src/Console/Command/HelpCommand.php index df8492ccf71..9a4f3bf17c0 100644 --- a/src/Console/Command/HelpCommand.php +++ b/src/Console/Command/HelpCommand.php @@ -17,7 +17,6 @@ namespace Cake\Console\Command; use ArrayIterator; -use Cake\Console\Arguments; use Cake\Console\BaseCommand; use Cake\Console\CommandCollection; use Cake\Console\CommandCollectionAwareInterface; @@ -52,24 +51,22 @@ public function setCommandCollection(CommandCollection $commands): void /** * Main function Prints out the list of commands. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null */ - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { $commands = $this->commands->getIterator(); if ($commands instanceof ArrayIterator) { $commands->ksort(); } - if ($args->getOption('xml')) { - $this->asXml($io, $commands); + if ($this->args->getOption('xml')) { + $this->asXml($this->io, $commands); return static::CODE_SUCCESS; } - $this->asText($io, $commands); + $this->asText($this->io, $commands); return static::CODE_SUCCESS; } diff --git a/src/Console/CommandCollection.php b/src/Console/CommandCollection.php index 21f48133894..fbad71c4e2e 100644 --- a/src/Console/CommandCollection.php +++ b/src/Console/CommandCollection.php @@ -191,7 +191,7 @@ public function count(): int * the long name (`plugin.command`) will be returned. * * @param string $plugin The plugin to scan. - * @return array> Discovered plugin commands. + * @return array> Discovered plugin commands. */ public function discoverPlugin(string $plugin): array { @@ -205,7 +205,7 @@ public function discoverPlugin(string $plugin): array * Resolve names based on existing commands * * @param array> $input The results of a CommandScanner operation. - * @return array> A flat map of command names => class names. + * @return array> A flat map of command names => class names. */ protected function resolveNames(array $input): array { @@ -244,7 +244,7 @@ protected function resolveNames(array $input): array * Commands defined in the application will overwrite commands with * the same name provided by CakePHP. * - * @return array> An array of command names and their classes. + * @return array> An array of command names and their classes. */ public function autoDiscover(): array { diff --git a/src/Console/CommandInterface.php b/src/Console/CommandInterface.php index 1e4072ee020..0d457a6d0d4 100644 --- a/src/Console/CommandInterface.php +++ b/src/Console/CommandInterface.php @@ -52,8 +52,9 @@ public function setName(string $name): static; * Run the command. * * @param array $argv Arguments from the CLI environment. - * @param \Cake\Console\ConsoleIoInterface $io The console io + * @param \Cake\Console\ConsoleIoInterface|null $io A custom console io + * instance if the default one shouldn't be used * @return int|null Exit code or null for success. */ - public function run(array $argv, ConsoleIoInterface $io): ?int; + public function run(array $argv, ?ConsoleIoInterface $io = null): ?int; } diff --git a/src/Console/CommandRunner.php b/src/Console/CommandRunner.php index d80cfd2976f..dc8975ac445 100644 --- a/src/Console/CommandRunner.php +++ b/src/Console/CommandRunner.php @@ -165,7 +165,7 @@ public function run(array $argv, ?ConsoleIoInterface $io = null): int } $command = $this->getCommand($io, $commands, $name); - $result = $this->runCommand($command, $argv, $io); + $result = $this->runCommand($command, $argv); if ($result === null) { return CommandInterface::CODE_SUCCESS; @@ -237,7 +237,9 @@ protected function getCommand(ConsoleIoInterface $io, CommandCollection $command $instance = $this->createCommand($instance); } + assert($instance instanceof BaseCommand); $instance->setName("{$this->root} {$name}"); + $instance->setIo($io); if ($instance instanceof CommandCollectionAwareInterface) { $instance->setCommandCollection($commands); @@ -318,11 +320,9 @@ protected function resolveName(CommandCollection $commands, ConsoleIoInterface $ * Execute a Command class. * * @param \Cake\Console\CommandInterface $command The command to run. - * @param array $argv The CLI arguments to invoke. - * @param \Cake\Console\ConsoleIoInterface $io The console io * @return int|null Exit code */ - protected function runCommand(CommandInterface $command, array $argv, ConsoleIoInterface $io): ?int + protected function runCommand(CommandInterface $command, array $argv): ?int { try { $eventManager = $this->getEventManager(); @@ -335,7 +335,7 @@ protected function runCommand(CommandInterface $command, array $argv, ConsoleIoI $command->setEventManager($this->getEventManager()); } - return $command->run($argv, $io); + return $command->run($argv); } catch (StopException $e) { return $e->getCode(); } diff --git a/tests/TestCase/Command/PluginAssetsCommandsTest.php b/tests/TestCase/Command/PluginAssetsCommandsTest.php index 36e6e0a3604..f0f8fa04afa 100644 --- a/tests/TestCase/Command/PluginAssetsCommandsTest.php +++ b/tests/TestCase/Command/PluginAssetsCommandsTest.php @@ -146,6 +146,7 @@ public function testSymlinkWhenTargetAlreadyExits(): void ->onlyMethods(['getOptionParser', 'createSymlink', 'copyDirectory']) ->getMock(); $command->method('getOptionParser')->willReturn($parser); + $command->setIo($io); $this->assertDirectoryExists($this->wwwRoot . 'test_theme'); diff --git a/tests/TestCase/Command/ServerCommandTest.php b/tests/TestCase/Command/ServerCommandTest.php index 4441d7c41fb..b5873280b46 100644 --- a/tests/TestCase/Command/ServerCommandTest.php +++ b/tests/TestCase/Command/ServerCommandTest.php @@ -17,7 +17,11 @@ namespace Cake\Test\TestCase\Command; use Cake\Command\ServerCommand; +use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; +use Cake\Console\TestSuite\StubConsoleOutput; use Cake\TestSuite\TestCase; +use Mockery; /** * ServerShell test. @@ -36,6 +40,8 @@ protected function setUp(): void { parent::setUp(); $this->command = new ServerCommand(); + $io = $this->getMockIo(new StubConsoleOutput()); + $this->command->setIo($io); } /** @@ -51,4 +57,11 @@ public function testGetOptionParser(): void $this->assertArrayHasKey('document_root', $options); $this->assertArrayHasKey('frankenphp', $options); } + + protected function getMockIo(StubConsoleOutput $output): ConsoleIoInterface + { + return Mockery::mock(ConsoleIo::class, [$output, $output, null, null]) + ->shouldAllowMockingMethod('in') + ->makePartial(); + } } diff --git a/tests/TestCase/Console/CommandFactoryTest.php b/tests/TestCase/Console/CommandFactoryTest.php index 30b5586c35c..4e6728bec8d 100644 --- a/tests/TestCase/Console/CommandFactoryTest.php +++ b/tests/TestCase/Console/CommandFactoryTest.php @@ -16,8 +16,12 @@ use Cake\Console\CommandFactory; use Cake\Console\CommandInterface; +use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; +use Cake\Console\TestSuite\StubConsoleOutput; use Cake\Core\Container; use Cake\TestSuite\TestCase; +use Mockery; use stdClass; use TestApp\Command\DemoCommand; use TestApp\Command\DependencyCommand; @@ -45,4 +49,11 @@ public function testCreateCommandDependencies(): void $this->assertInstanceOf(DependencyCommand::class, $command); $this->assertInstanceOf(stdClass::class, $command->inject); } + + protected function getMockIo(StubConsoleOutput $output): ConsoleIoInterface + { + return Mockery::mock(ConsoleIo::class, [$output, $output, null, null]) + ->shouldAllowMockingMethod('in') + ->makePartial(); + } } diff --git a/tests/TestCase/Console/CommandRunnerTest.php b/tests/TestCase/Console/CommandRunnerTest.php index 851de1136d7..87377373d33 100644 --- a/tests/TestCase/Console/CommandRunnerTest.php +++ b/tests/TestCase/Console/CommandRunnerTest.php @@ -347,10 +347,12 @@ public function testRunWithCustomFactory(): void $output = new StubConsoleOutput(); $io = $this->getMockIo($output); $factory = $this->createMock(CommandFactoryInterface::class); + $command = new DemoCommand($factory); + $command->setIo($io); $factory->expects($this->once()) ->method('create') ->with(DemoCommand::class) - ->willReturn(new DemoCommand()); + ->willReturn($command); $app = $this->makeAppWithCommands(['ex' => DemoCommand::class]); @@ -367,15 +369,15 @@ public function testRunWithContainerDependencies(): void $app = $this->makeAppWithCommands([ 'dependency' => DependencyCommand::class, ]); + $output = new StubConsoleOutput(); + $mockIo = $this->getMockIo($output); $container = $app->getContainer(); $container->add(stdClass::class, json_decode('{"key":"value"}')); $container->add(DependencyCommand::class) ->addArgument(stdClass::class); - $output = new StubConsoleOutput(); - $runner = new CommandRunner($app, 'cake'); - $result = $runner->run(['cake', 'dependency'], $this->getMockIo($output)); + $result = $runner->run(['cake', 'dependency'], $mockIo); $this->assertSame(CommandInterface::CODE_SUCCESS, $result); $messages = implode("\n", $output->messages()); diff --git a/tests/TestCase/Console/CommandTest.php b/tests/TestCase/Console/CommandTest.php index 734a48f9217..429b3c44caa 100644 --- a/tests/TestCase/Console/CommandTest.php +++ b/tests/TestCase/Console/CommandTest.php @@ -22,8 +22,10 @@ use Cake\Console\CommandFactoryInterface; use Cake\Console\CommandInterface; use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; use Cake\Console\Exception\StopException; +use Cake\Console\TestSuite\ConsoleIntegrationTestTrait; use Cake\Console\TestSuite\StubConsoleOutput; use Cake\Core\Container; use Cake\ORM\Locator\TableLocator; @@ -43,12 +45,15 @@ */ class CommandTest extends TestCase { + use ConsoleIntegrationTestTrait; + /** * test orm locator is setup */ public function testConstructorSetsLocator(): void { $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $result = $command->getTableLocator(); $this->assertInstanceOf(TableLocator::class, $result); } @@ -60,6 +65,7 @@ public function testConstructorAutoLoadModel(): void { // No deprecation as AutoLoadModelCommand class defines Posts property $command = new AutoLoadModelCommand(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $this->assertInstanceOf(Table::class, $command->fetchTable()); } @@ -69,6 +75,7 @@ public function testConstructorAutoLoadModel(): void public function testSetName(): void { $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $this->assertSame($command, $command->setName('routes show')); $this->assertSame('routes show', $command->getName()); $this->assertSame('routes', $command->getRootName()); @@ -83,6 +90,7 @@ public function testSetNameInvalid(): void $this->expectExceptionMessage("The name 'routes_show' is missing a space. Names should look like `cake routes`"); $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->setName('routes_show'); } @@ -94,6 +102,7 @@ public function testSetNameInvalidLeadingSpace(): void $this->expectException(AssertionError::class); $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->setName(' routes_show'); } @@ -103,6 +112,7 @@ public function testSetNameInvalidLeadingSpace(): void public function testGetOptionParser(): void { $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->setName('cake routes show'); $parser = $command->getOptionParser(); $this->assertInstanceOf(ConsoleOptionParser::class, $parser); @@ -117,14 +127,26 @@ public function testRunCallsInitialize(): void $command = new class extends Command { public bool $initializeCalled = false; + public string $someArg = ''; + + public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser + { + $parser->addArgument('someArg', ['required' => false]); + + return parent::buildOptionParser($parser); + } + public function initialize(): void { $this->initializeCalled = true; + $this->someArg = $this->args->getArgument('someArg'); } }; $command->setName('cake example'); - $command->run([], $this->getMockIo(new StubConsoleOutput())); + $command->run(['something'], $this->getMockIo(new StubConsoleOutput())); $this->assertTrue($command->initializeCalled); + // Make sure args are parsed and passed to initialize + $this->assertEquals('something', $command->someArg); } /** @@ -133,6 +155,7 @@ public function initialize(): void public function testRunOutputHelp(): void { $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->setName('cake demo'); $output = new StubConsoleOutput(); @@ -151,6 +174,7 @@ public function testRunOutputHelp(): void public function testRunOutputHelpLongOption(): void { $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->setName('cake demo'); $output = new StubConsoleOutput(); @@ -169,6 +193,7 @@ public function testRunOutputHelpLongOption(): void public function testRunVerboseOption(): void { $command = new DemoCommand(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->setName('cake demo'); $output = new StubConsoleOutput(); @@ -186,6 +211,7 @@ public function testRunVerboseOption(): void public function testRunQuietOption(): void { $command = new DemoCommand(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->setName('cake demo'); $output = new StubConsoleOutput(); @@ -231,6 +257,7 @@ public function testAbort(): void $this->expectExceptionCode(1); $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->abort(); } @@ -243,6 +270,7 @@ public function testAbortCustomCode(): void $this->expectExceptionCode(99); $command = new Command(); + $command->setIo($this->getMockIo(new StubConsoleOutput())); $command->abort(99); } @@ -253,7 +281,8 @@ public function testExecuteCommandString(): void { $output = new StubConsoleOutput(); $command = new Command(); - $result = $command->executeCommand(DemoCommand::class, [], $this->getMockIo($output)); + $command->setIo($this->getMockIo($output)); + $result = $command->executeCommand(DemoCommand::class, []); $this->assertNull($result); $this->assertEquals(['Quiet!', 'Demo Command!'], $output->messages()); } @@ -265,7 +294,8 @@ public function testExecuteCommandArguments(): void { $output = new StubConsoleOutput(); $command = new Command(); - $command->executeCommand(DemoCommand::class, ['Jane'], $this->getMockIo($output)); + $command->setIo($this->getMockIo($output)); + $command->executeCommand(DemoCommand::class, ['Jane']); $this->assertEquals(['Quiet!', 'Demo Command!', 'Jane'], $output->messages()); } @@ -276,7 +306,8 @@ public function testExecuteCommandArgumentsOptions(): void { $output = new StubConsoleOutput(); $command = new Command(); - $command->executeCommand(DemoCommand::class, ['--quiet', 'Jane'], $this->getMockIo($output)); + $command->setIo($this->getMockIo($output)); + $command->executeCommand(DemoCommand::class, ['--quiet', 'Jane']); $this->assertEquals(['Quiet!'], $output->messages()); } @@ -287,7 +318,8 @@ public function testExecuteCommandInstance(): void { $output = new StubConsoleOutput(); $command = new Command(); - $result = $command->executeCommand(new DemoCommand(), [], $this->getMockIo($output)); + $command->setIo($this->getMockIo($output)); + $result = $command->executeCommand(new DemoCommand(), []); $this->assertNull($result); $this->assertEquals(['Quiet!', 'Demo Command!'], $output->messages()); } @@ -299,7 +331,8 @@ public function testExecuteCommandAbort(): void { $output = new StubConsoleOutput(); $command = new Command(); - $result = $command->executeCommand(AbortCommand::class, [], $this->getMockIo($output)); + $command->setIo($this->getMockIo($output)); + $result = $command->executeCommand(AbortCommand::class, []); $this->assertSame(127, $result); $this->assertEquals(['Command aborted'], $output->messages()); } @@ -311,13 +344,15 @@ public function testExecuteCommandNonInteractive(): void { $output = new StubConsoleOutput(); $command = new Command(); - $command->executeCommand(NonInteractiveCommand::class, ['--quiet'], $this->getMockIo($output)); + $command->setIo($this->getMockIo($output)); + $command->executeCommand(NonInteractiveCommand::class, ['--quiet']); $this->assertEquals(['Result: Default!'], $output->messages()); } public function testExecuteCommandWithDI(): void { $output = new StubConsoleOutput(); + $mockIo = $this->getMockIo($output); $container = new Container(); $factory = new CommandFactory($container); @@ -329,7 +364,8 @@ public function testExecuteCommandWithDI(): void ->addArgument(stdClass::class); $command = $factory->create(Command::class); - $result = $command->executeCommand(DependencyCommand::class, [], $this->getMockIo($output)); + $command->setIo($mockIo); + $result = $command->executeCommand(DependencyCommand::class, []); $this->assertSame(Command::CODE_SUCCESS, $result); $this->assertEquals(['Dependency Command', 'constructor inject: {}'], $output->messages()); @@ -339,7 +375,8 @@ public function testExecuteCommandWithEventHooks(): void { $output = new StubConsoleOutput(); $command = new Command(); - $command->executeCommand(EventsCommand::class, [], $this->getMockIo($output)); + $command->setIo($this->getMockIo($output)); + $command->executeCommand(EventsCommand::class, []); $this->assertEquals([ 'beforeExecute run', 'execute run', @@ -355,4 +392,23 @@ protected function getMockIo($output) { return Mockery::mock(ConsoleIo::class, [$output, $output, null, null])->makePartial(); } + + /** + * @param class-string $command + * @return array{0: \Cake\Console\CommandInterface, 1: \Cake\Console\ConsoleIoInterface, 2: \Cake\Console\ConsoleOutput} + */ + protected function getCommandWithMockedIo(string $command): array + { + $output = new StubConsoleOutput(); + $mockIo = $this->getMockIo($output); + $container = new Container(); + $factory = new CommandFactory($container); + $container->add($command) + ->addArgument(ConsoleIoInterface::class); + + $command = $factory->create($command); + $command->setIo($mockIo); + + return [$command, $mockIo, $output]; + } } diff --git a/tests/test_app/Plugin/Company/TestPluginThree/src/Command/CompanyCommand.php b/tests/test_app/Plugin/Company/TestPluginThree/src/Command/CompanyCommand.php index 09aa8297f38..201d95083c8 100644 --- a/tests/test_app/Plugin/Company/TestPluginThree/src/Command/CompanyCommand.php +++ b/tests/test_app/Plugin/Company/TestPluginThree/src/Command/CompanyCommand.php @@ -4,12 +4,10 @@ namespace Company\TestPluginThree\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class CompanyCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { } } diff --git a/tests/test_app/Plugin/TestPlugin/src/Command/ExampleCommand.php b/tests/test_app/Plugin/TestPlugin/src/Command/ExampleCommand.php index 55d0f6b5f96..f4abb24df8c 100644 --- a/tests/test_app/Plugin/TestPlugin/src/Command/ExampleCommand.php +++ b/tests/test_app/Plugin/TestPlugin/src/Command/ExampleCommand.php @@ -4,12 +4,10 @@ namespace TestPlugin\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class ExampleCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { } } diff --git a/tests/test_app/Plugin/TestPlugin/src/Command/SampleCommand.php b/tests/test_app/Plugin/TestPlugin/src/Command/SampleCommand.php index 90e3bacf444..6efd8a368cd 100644 --- a/tests/test_app/Plugin/TestPlugin/src/Command/SampleCommand.php +++ b/tests/test_app/Plugin/TestPlugin/src/Command/SampleCommand.php @@ -4,12 +4,10 @@ namespace TestPlugin\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class SampleCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { } } diff --git a/tests/test_app/Plugin/TestPlugin/src/Command/SampleSubCommand.php b/tests/test_app/Plugin/TestPlugin/src/Command/SampleSubCommand.php index 27542aa9121..0200f5bfd1a 100644 --- a/tests/test_app/Plugin/TestPlugin/src/Command/SampleSubCommand.php +++ b/tests/test_app/Plugin/TestPlugin/src/Command/SampleSubCommand.php @@ -17,8 +17,6 @@ namespace TestPlugin\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class SampleSubCommand extends Command { @@ -32,7 +30,7 @@ public static function defaultName(): string return 'sample sub'; } - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { } } diff --git a/tests/test_app/Plugin/TestPluginTwo/src/Command/ExampleCommand.php b/tests/test_app/Plugin/TestPluginTwo/src/Command/ExampleCommand.php index b73deb4ea52..dca3238a44c 100644 --- a/tests/test_app/Plugin/TestPluginTwo/src/Command/ExampleCommand.php +++ b/tests/test_app/Plugin/TestPluginTwo/src/Command/ExampleCommand.php @@ -4,13 +4,11 @@ namespace TestPluginTwo\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class ExampleCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $io->out('This is the main method called from TestPluginTwo.ExampleCommand'); + $this->io->out('This is the main method called from TestPluginTwo.ExampleCommand'); } } diff --git a/tests/test_app/Plugin/TestPluginTwo/src/Command/UniqueCommand.php b/tests/test_app/Plugin/TestPluginTwo/src/Command/UniqueCommand.php index 1746bc73787..fd8e6195a78 100644 --- a/tests/test_app/Plugin/TestPluginTwo/src/Command/UniqueCommand.php +++ b/tests/test_app/Plugin/TestPluginTwo/src/Command/UniqueCommand.php @@ -4,13 +4,11 @@ namespace TestPluginTwo\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class UniqueCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $io->out('This is the main method called from TestPluginTwo.UniqueCommand'); + $this->io->out('This is the main method called from TestPluginTwo.UniqueCommand'); } } diff --git a/tests/test_app/Plugin/TestPluginTwo/src/Command/WelcomeCommand.php b/tests/test_app/Plugin/TestPluginTwo/src/Command/WelcomeCommand.php index 35d1052e127..fc18755fc4c 100644 --- a/tests/test_app/Plugin/TestPluginTwo/src/Command/WelcomeCommand.php +++ b/tests/test_app/Plugin/TestPluginTwo/src/Command/WelcomeCommand.php @@ -4,13 +4,11 @@ namespace TestPluginTwo\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class WelcomeCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $io->out('This is the say_hello method called from TestPluginTwo.WelcomeCommand'); + $this->io->out('This is the say_hello method called from TestPluginTwo.WelcomeCommand'); } } diff --git a/tests/test_app/Plugin/TestPluginTwo/src/Command/WelcomeSayHelloCommand.php b/tests/test_app/Plugin/TestPluginTwo/src/Command/WelcomeSayHelloCommand.php index 2cec0a48b1d..93718728cce 100644 --- a/tests/test_app/Plugin/TestPluginTwo/src/Command/WelcomeSayHelloCommand.php +++ b/tests/test_app/Plugin/TestPluginTwo/src/Command/WelcomeSayHelloCommand.php @@ -4,8 +4,6 @@ namespace TestPluginTwo\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class WelcomeSayHelloCommand extends Command { @@ -14,7 +12,7 @@ public static function defaultName(): string return 'welcome say_hello'; } - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { } } diff --git a/tests/test_app/TestApp/Application.php b/tests/test_app/TestApp/Application.php index 9390679876c..c7ea1c97624 100644 --- a/tests/test_app/TestApp/Application.php +++ b/tests/test_app/TestApp/Application.php @@ -52,8 +52,8 @@ public function bootstrap(): void public function console(CommandCollection $commands): CommandCollection { return $commands - ->add('abort_command', new AbortCommand()) - ->add('format_specifier_command', new FormatSpecifierCommand()) + ->add('abort_command', AbortCommand::class) + ->add('format_specifier_command', FormatSpecifierCommand::class) ->addMany($commands->autoDiscover()); } diff --git a/tests/test_app/TestApp/Command/AbortCommand.php b/tests/test_app/TestApp/Command/AbortCommand.php index b3f05ffce22..0b1808123ef 100644 --- a/tests/test_app/TestApp/Command/AbortCommand.php +++ b/tests/test_app/TestApp/Command/AbortCommand.php @@ -4,14 +4,12 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class AbortCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $io->error('Command aborted'); + $this->io->error('Command aborted'); $this->abort(127); } } diff --git a/tests/test_app/TestApp/Command/BridgeCommand.php b/tests/test_app/TestApp/Command/BridgeCommand.php index adac1a847be..4fa05a18562 100644 --- a/tests/test_app/TestApp/Command/BridgeCommand.php +++ b/tests/test_app/TestApp/Command/BridgeCommand.php @@ -4,29 +4,27 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class BridgeCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $name = $io->ask('What is your name'); + $name = $this->io->ask('What is your name'); if ($name !== 'cake') { - $io->err('No!'); + $this->io->err('No!'); return static::CODE_ERROR; } - $color = $io->ask('What is your favorite color?'); + $color = $this->io->ask('What is your favorite color?'); if ($color !== 'blue') { - $io->err('Wrong! Aaaahh'); + $this->io->err('Wrong! Aaaahh'); return static::CODE_ERROR; } - $io->out('You may pass.'); + $this->io->out('You may pass.'); } } diff --git a/tests/test_app/TestApp/Command/DemoCommand.php b/tests/test_app/TestApp/Command/DemoCommand.php index 7e408de1200..4c0e718630a 100644 --- a/tests/test_app/TestApp/Command/DemoCommand.php +++ b/tests/test_app/TestApp/Command/DemoCommand.php @@ -4,8 +4,6 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class DemoCommand extends Command { @@ -14,13 +12,13 @@ public static function getDescription(): string return 'This is a demo command'; } - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $io->quiet('Quiet!'); - $io->out('Demo Command!'); - $io->verbose('Verbose!'); - if ($args->hasArgumentAt(0)) { - $io->out($args->getArgumentAt(0)); + $this->io->quiet('Quiet!'); + $this->io->out('Demo Command!'); + $this->io->verbose('Verbose!'); + if ($this->args->hasArgumentAt(0)) { + $this->io->out($this->args->getArgumentAt(0)); } return null; diff --git a/tests/test_app/TestApp/Command/DependencyCommand.php b/tests/test_app/TestApp/Command/DependencyCommand.php index 34d06ca04f0..fc8fdd0d094 100644 --- a/tests/test_app/TestApp/Command/DependencyCommand.php +++ b/tests/test_app/TestApp/Command/DependencyCommand.php @@ -4,23 +4,19 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use stdClass; class DependencyCommand extends Command { - public $inject; - - public function __construct(stdClass $inject) - { - $this->inject = $inject; + public function __construct( + public stdClass $inject, + ) { } - public function execute(Arguments $args, ConsoleIoInterface $io): int + public function execute(): int { - $io->out('Dependency Command'); - $io->out('constructor inject: ' . json_encode($this->inject)); + $this->io->out('Dependency Command'); + $this->io->out('constructor inject: ' . json_encode($this->inject)); return static::CODE_SUCCESS; } diff --git a/tests/test_app/TestApp/Command/EventsCommand.php b/tests/test_app/TestApp/Command/EventsCommand.php index 5e5f63f3368..5ed01e9c4eb 100644 --- a/tests/test_app/TestApp/Command/EventsCommand.php +++ b/tests/test_app/TestApp/Command/EventsCommand.php @@ -15,20 +15,20 @@ public static function getDescription(): string return 'This is a command that uses events'; } - public function execute(Arguments $args, ConsoleIoInterface $io): ?int + public function execute(): ?int { - $io->out('execute run'); + $this->io->out('execute run'); return null; } public function beforeExecute(EventInterface $event, Arguments $args, ConsoleIoInterface $io): void { - $io->out('beforeExecute run'); + $this->io->out('beforeExecute run'); } public function afterExecute(EventInterface $event, Arguments $args, ConsoleIoInterface $io, mixed $result): void { - $io->out('afterExecute run'); + $this->io->out('afterExecute run'); } } diff --git a/tests/test_app/TestApp/Command/FormatSpecifierCommand.php b/tests/test_app/TestApp/Command/FormatSpecifierCommand.php index 84ebd9d6413..daff0246204 100644 --- a/tests/test_app/TestApp/Command/FormatSpecifierCommand.php +++ b/tests/test_app/TestApp/Command/FormatSpecifierCommand.php @@ -4,13 +4,11 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class FormatSpecifierCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $io->out('Be careful! %s is a format specifier!'); + $this->io->out('Be careful! %s is a format specifier!'); } } diff --git a/tests/test_app/TestApp/Command/GroupedCommand.php b/tests/test_app/TestApp/Command/GroupedCommand.php index dd5a0d4601a..dd85aea595c 100644 --- a/tests/test_app/TestApp/Command/GroupedCommand.php +++ b/tests/test_app/TestApp/Command/GroupedCommand.php @@ -4,8 +4,6 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class GroupedCommand extends Command { @@ -14,8 +12,8 @@ public static function getGroup(): string return 'custom_group'; } - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $io->out('Grouped Command!'); + $this->io->out('Grouped Command!'); } } diff --git a/tests/test_app/TestApp/Command/IntegrationCommand.php b/tests/test_app/TestApp/Command/IntegrationCommand.php index 1418ecead52..1633a4f3b3e 100644 --- a/tests/test_app/TestApp/Command/IntegrationCommand.php +++ b/tests/test_app/TestApp/Command/IntegrationCommand.php @@ -4,16 +4,14 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; use Cake\Console\ConsoleOptionParser; class IntegrationCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $io->out('arg: ' . $args->getArgument('arg')); - $io->out('opt: ' . $args->getOption('opt')); + $this->io->out('arg: ' . $this->args->getArgument('arg')); + $this->io->out('opt: ' . $this->args->getOption('opt')); } public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser diff --git a/tests/test_app/TestApp/Command/NonInteractiveCommand.php b/tests/test_app/TestApp/Command/NonInteractiveCommand.php index b7c4d8f5850..bfa5d21d12b 100644 --- a/tests/test_app/TestApp/Command/NonInteractiveCommand.php +++ b/tests/test_app/TestApp/Command/NonInteractiveCommand.php @@ -4,14 +4,12 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class NonInteractiveCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $result = $io->ask('What?', 'Default!'); - $io->quiet('Result: ' . $result); + $result = $this->io->ask('What?', 'Default!'); + $this->io->quiet('Result: ' . $result); } } diff --git a/tests/test_app/TestApp/Command/SampleCommand.php b/tests/test_app/TestApp/Command/SampleCommand.php index 9325fcce79d..e16d5c79aa0 100644 --- a/tests/test_app/TestApp/Command/SampleCommand.php +++ b/tests/test_app/TestApp/Command/SampleCommand.php @@ -4,13 +4,11 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class SampleCommand extends Command { - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { - $io->out('This is the main method called from SampleCommand'); + $this->io->out('This is the main method called from SampleCommand'); } } diff --git a/tests/test_app/TestApp/Command/SampleSubCommand.php b/tests/test_app/TestApp/Command/SampleSubCommand.php index bddf45e4a6c..8b2f650b0b6 100644 --- a/tests/test_app/TestApp/Command/SampleSubCommand.php +++ b/tests/test_app/TestApp/Command/SampleSubCommand.php @@ -17,8 +17,6 @@ namespace TestApp\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIoInterface; class SampleSubCommand extends Command { @@ -32,7 +30,7 @@ public static function defaultName(): string return 'sample sub'; } - public function execute(Arguments $args, ConsoleIoInterface $io) + public function execute() { } }