From b046ebf692667a903e5356aaf785d92ab13199e6 Mon Sep 17 00:00:00 2001 From: Thomas Hauschild <7961978+Morgy93@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:47:50 +0100 Subject: [PATCH 1/3] feat(cli): add unified --format=json output to commands Add a shared --format=table|json option (plus --json shortcut) to AbstractCommand and use it in theme:list, theme:info, theme:build, template:obsolete, dependencies:update, hyva:compatibility:check, system:version and system:check. In JSON mode stdout only carries the JSON document; progress and messages go to stderr, prompts are disabled and failures write {"error": "..."} with a non-zero exit code. Refs #307 --- docs/commands_reference.md | 29 +++- src/Console/Command/AbstractCommand.php | 151 +++++++++++++++++- .../Command/Dependencies/UpdateCommand.php | 20 ++- .../Hyva/CompatibilityCheckCommand.php | 95 +++++++++++ src/Console/Command/System/CheckCommand.php | 29 +++- src/Console/Command/System/VersionCommand.php | 38 +++++ .../Command/Template/ObsoleteCommand.php | 47 +++--- src/Console/Command/Theme/BuildCommand.php | 38 ++++- src/Console/Command/Theme/InfoCommand.php | 15 +- src/Console/Command/Theme/ListCommand.php | 16 ++ .../Console/Command/AbstractCommandTest.php | 62 +++++++ .../Console/Command/ConcreteTestCommand.php | 20 +++ .../Dependencies/UpdateCommandTest.php | 36 +++++ .../Hyva/CompatibilityCheckCommandTest.php | 72 +++++++++ .../Command/System/CheckCommandTest.php | 27 ++++ .../Command/System/VersionCommandTest.php | 29 ++++ .../Command/Theme/BuildCommandTest.php | 37 +++++ .../Console/Command/Theme/ListCommandTest.php | 27 ++++ 18 files changed, 746 insertions(+), 42 deletions(-) diff --git a/docs/commands_reference.md b/docs/commands_reference.md index a18ec9a1..563ed449 100644 --- a/docs/commands_reference.md +++ b/docs/commands_reference.md @@ -22,6 +22,33 @@ Complete reference of all CLI commands provided by the MageForge module. --- +## Machine-readable output + +These commands accept `--format=json` (or the shortcut `--json`) for scripts, CI and AI agents: `theme:list`, `theme:info`, `theme:build`, `template:obsolete`, `dependencies:update`, `hyva:compatibility:check`, `system:version` and `system:check`. + +- stdout contains only the JSON document. Progress, warnings and errors go to stderr. +- Prompts are never shown in JSON mode, so pass all arguments explicitly. +- On failure the exit code is non-zero and stdout contains `{"error": ""}`. +- An unknown `--format` value fails with an error. + +```bash +bin/magento mageforge:theme:list --format=json +bin/magento mageforge:theme:build Magento/luma --json +``` + +Top-level structure per command: + +- `theme:list` — array of `{code, title, area, path}`. +- `theme:info` — object with the theme details (same keys as the table view). +- `theme:build` — `{success, duration_seconds, built: [{theme, builder, hyva_version}], failed: [codes]}`. +- `template:obsolete` — array of `{theme, template, file, reason, details, safe_to_delete}`. +- `dependencies:update` — `{dry_run, duration_seconds, updated, skipped, failed}`. +- `hyva:compatibility:check` — `{summary, modules: [{name, version, status, hyva_aware, files}], tailwind4}`; `tailwind4` is `null` when the readiness check did not run. +- `system:version` — `{module_version, latest_version, update_available}`; unknown values are `null`. +- `system:check` — `{php, composer, node, npm, git, database, xdebug, redis, search_engine, os, disk_space, magento, php_extensions}`. + +--- + ## Theme Commands ### `mageforge:theme:list` @@ -44,7 +71,7 @@ Shows details about a theme: area, path, Composer package and version, parent ch ```bash bin/magento mageforge:theme:info [] -bin/magento mageforge:theme:info Magento/luma --json +bin/magento mageforge:theme:info Magento/luma --format=json ``` ### `mageforge:theme:build` diff --git a/src/Console/Command/AbstractCommand.php b/src/Console/Command/AbstractCommand.php index a77fad32..f99b98a1 100644 --- a/src/Console/Command/AbstractCommand.php +++ b/src/Console/Command/AbstractCommand.php @@ -13,6 +13,8 @@ use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\NullOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; @@ -28,11 +30,29 @@ abstract class AbstractCommand extends Command */ protected const COMMAND_PREFIX = 'mageforge'; + protected const FORMAT_TABLE = 'table'; + protected const FORMAT_JSON = 'json'; + /** * @var SymfonyStyle */ protected SymfonyStyle $io; + /** + * @var bool Whether the current run produces JSON on stdout + */ + private bool $jsonOutput = false; + + /** + * @var bool Whether a JSON document was already written during the current run + */ + private bool $jsonWritten = false; + + /** + * @var OutputInterface|null Real standard output, kept separate from $io which logs to stderr in JSON mode + */ + private ?OutputInterface $stdout = null; + /** * @var array */ @@ -69,14 +89,138 @@ protected function getCommandName(string $group, string $command): string */ protected function execute(InputInterface $input, OutputInterface $output): int { + $this->stdout = $output; + $this->jsonWritten = false; + $this->jsonOutput = false; + + $format = $this->resolveFormat($input); + if ($format === null) { + $this->io = new SymfonyStyle($input, $output); + $this->io->error(sprintf( + "Invalid format '%s'. Use '%s' or '%s'.", + $this->getFormatOptionValue($input), + self::FORMAT_TABLE, + self::FORMAT_JSON, + )); + return Cli::RETURN_FAILURE; + } + + $this->jsonOutput = $format === self::FORMAT_JSON; + if ($this->jsonOutput) { + // Keep stdout reserved for the JSON document; progress and messages go to stderr + $output = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : new NullOutput(); + } + $this->io = new SymfonyStyle($input, $output); try { - return $this->executeCommand($input, $output); + $result = $this->executeCommand($input, $output); } catch (\Exception $e) { $this->io->error($e->getMessage()); + $this->writeJsonError($e->getMessage()); return Cli::RETURN_FAILURE; } + + if ($result !== Cli::RETURN_SUCCESS) { + $this->writeJsonError('The command failed. See stderr for details.'); + } + + return $result; + } + + /** + * Add the --format and --json options for machine-readable output + * + * @return void + */ + protected function addFormatOption(): void + { + $this->addOption( + 'format', + null, + InputOption::VALUE_REQUIRED, + sprintf('Output format: %s or %s', self::FORMAT_TABLE, self::FORMAT_JSON), + self::FORMAT_TABLE, + )->addOption('json', null, InputOption::VALUE_NONE, 'Shortcut for --format=json'); + } + + /** + * Check whether the current run outputs JSON + * + * @return bool + */ + protected function isJsonOutput(): bool + { + return $this->jsonOutput; + } + + /** + * Write a JSON document to stdout + * + * @param mixed $data + * @return void + */ + protected function writeJson(mixed $data): void + { + $this->stdout?->writeln( + json_encode( + $data, + JSON_PRETTY_PRINT + | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + | JSON_THROW_ON_ERROR + | JSON_INVALID_UTF8_SUBSTITUTE, + ), + OutputInterface::OUTPUT_RAW, + ); + $this->jsonWritten = true; + } + + /** + * Write a JSON error document to stdout when running in JSON mode + * + * @param string $message + * @return void + */ + protected function writeJsonError(string $message): void + { + if ($this->jsonOutput && !$this->jsonWritten) { + $this->writeJson(['error' => $message]); + } + } + + /** + * Resolve the requested output format + * + * @param InputInterface $input + * @return string|null The format, or null if it is invalid + */ + private function resolveFormat(InputInterface $input): ?string + { + $definition = $this->getDefinition(); + if (!$definition->hasOption('format')) { + return self::FORMAT_TABLE; + } + if ($definition->hasOption('json') && $input->getOption('json')) { + return self::FORMAT_JSON; + } + + $format = $this->getFormatOptionValue($input); + + return in_array($format, [self::FORMAT_TABLE, self::FORMAT_JSON], true) ? $format : null; + } + + /** + * Get the raw value of the --format option + * + * @param InputInterface $input + * @return string + */ + private function getFormatOptionValue(InputInterface $input): string + { + $format = $input->getOption('format'); + + return is_string($format) ? $format : self::FORMAT_TABLE; } /** @@ -302,6 +446,11 @@ protected function renderInheritanceTree(string $themeCode, array $chain): void */ protected function isInteractiveTerminal(OutputInterface $output): bool { + // Prompts would corrupt the JSON document and cannot be answered by agents + if ($this->jsonOutput) { + return false; + } + // Check if output supports ANSI if (!$output->isDecorated()) { return false; diff --git a/src/Console/Command/Dependencies/UpdateCommand.php b/src/Console/Command/Dependencies/UpdateCommand.php index dcce00c8..b75c9ae7 100644 --- a/src/Console/Command/Dependencies/UpdateCommand.php +++ b/src/Console/Command/Dependencies/UpdateCommand.php @@ -60,6 +60,7 @@ protected function configure(): void ) ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Show outdated packages without changing anything') ->setAliases(['dependencies:update']); + $this->addFormatOption(); } /** @@ -81,6 +82,12 @@ protected function executeCommand(InputInterface $input, OutputInterface $output $themeCodes = $this->resolveThemeCodes($input, $output); if ($themeCodes === null) { + if ($this->isJsonOutput()) { + $this->writeJsonError('No themes to update. Pass one or more theme codes.'); + + return Cli::RETURN_FAILURE; + } + return Cli::RETURN_SUCCESS; } @@ -88,7 +95,18 @@ protected function executeCommand(InputInterface $input, OutputInterface $output [$updatedThemes, $skippedThemes, $failedThemes] = $this->processThemes($themeCodes, $latest, $dryRun, $output); - $this->displaySummary($updatedThemes, $skippedThemes, $failedThemes, $dryRun, microtime(true) - $startTime); + $duration = microtime(true) - $startTime; + if ($this->isJsonOutput()) { + $this->writeJson([ + 'dry_run' => $dryRun, + 'duration_seconds' => round($duration, 2), + 'updated' => $updatedThemes, + 'skipped' => $skippedThemes, + 'failed' => $failedThemes, + ]); + } else { + $this->displaySummary($updatedThemes, $skippedThemes, $failedThemes, $dryRun, $duration); + } if (!empty($failedThemes)) { return Cli::RETURN_FAILURE; diff --git a/src/Console/Command/Hyva/CompatibilityCheckCommand.php b/src/Console/Command/Hyva/CompatibilityCheckCommand.php index de476deb..8c392e1b 100644 --- a/src/Console/Command/Hyva/CompatibilityCheckCommand.php +++ b/src/Console/Command/Hyva/CompatibilityCheckCommand.php @@ -105,6 +105,7 @@ protected function configure(): void InputOption::VALUE_NONE, 'Force the Tailwind CSS v4 readiness check (runs automatically if Hyvä is installed via Composer)', ); + $this->addFormatOption(); } /** @@ -296,6 +297,10 @@ private function runScan( // Run the compatibility check $results = $this->compatibilityChecker->check($this->io, $showAll, $scanThirdPartyOnly, !$includeVendor); + if ($this->isJsonOutput()) { + return $this->outputJson($results, $showAll, $scanThirdPartyOnly, !$includeVendor, $tailwind4); + } + // Determine display mode: // showAll = show all modules including compatible ones // incompatibleOnly = show only modules with critical issues @@ -333,6 +338,96 @@ private function runScan( : Cli::RETURN_SUCCESS; } + /** + * Write the scan results as JSON + * + * @param array $results + * @phpstan-param CheckResults $results + * @param bool $showAll + * @param bool $thirdPartyOnly + * @param bool $excludeVendor + * @param bool $tailwind4 + * @return int + */ + private function outputJson( + array $results, + bool $showAll, + bool $thirdPartyOnly, + bool $excludeVendor, + bool $tailwind4, + ): int { + $modules = []; + foreach ($results['modules'] as $moduleName => $data) { + if (!$showAll && $data['compatible'] && !$data['hasWarnings']) { + continue; + } + + $modules[] = [ + 'name' => $moduleName, + 'version' => $data['moduleInfo']['version'], + 'status' => match (true) { + !$data['compatible'] => 'incompatible', + $data['hasWarnings'] => 'warnings', + default => 'compatible', + }, + 'hyva_aware' => $data['moduleInfo']['isHyvaAware'], + 'files' => $this->compatibilityChecker->getDetailedIssues($data), + ]; + } + + $hyvaVersion = $this->hyvaVersionDetector->getVersion(); + $tailwind4Results = null; + $tailwind4Errors = 0; + if ($tailwind4 || $hyvaVersion !== null) { + $tailwind4Check = $this->tailwind4Checker->check($thirdPartyOnly, $excludeVendor); + $tailwind4Errors = $tailwind4Check['errors']; + $tailwind4Results = $this->tailwind4ToArray($tailwind4Check, $hyvaVersion); + } + + $this->writeJson([ + 'summary' => $results['summary'], + 'modules' => $modules, + 'tailwind4' => $tailwind4Results, + ]); + + return $results['summary']['criticalIssues'] > 0 || $tailwind4Errors > 0 + ? Cli::RETURN_FAILURE + : Cli::RETURN_SUCCESS; + } + + /** + * Convert the Tailwind CSS v4 readiness results to a JSON-serialisable array + * + * @param array $results + * @phpstan-param Tailwind4Results $results + * @param string|null $hyvaVersion + * @return array + */ + private function tailwind4ToArray(array $results, ?string $hyvaVersion): array + { + $findings = []; + foreach ($results['sections'] as $name => $sectionFindings) { + foreach ($sectionFindings as $finding) { + $findings[] = [ + 'section' => $name, + 'severity' => $finding->severity->value, + 'message' => $finding->message, + 'hint' => $finding->hint, + 'location' => $finding->getLocation(), + ]; + } + } + + return [ + 'hyva_version' => $hyvaVersion, + 'themes' => $results['themes'], + 'modules' => $results['modules'], + 'errors' => $results['errors'], + 'warnings' => $results['warnings'], + 'findings' => $findings, + ]; + } + /** * Run the Tailwind CSS v4 readiness check and display its results * diff --git a/src/Console/Command/System/CheckCommand.php b/src/Console/Command/System/CheckCommand.php index ff15da32..2f8783fb 100644 --- a/src/Console/Command/System/CheckCommand.php +++ b/src/Console/Command/System/CheckCommand.php @@ -51,6 +51,7 @@ protected function configure(): void ->setName($this->getCommandName('system', 'check')) ->setDescription('Displays system information like PHP version and Node.js version') ->setAliases(['system:check']); + $this->addFormatOption(); } /** @@ -78,7 +79,33 @@ protected function executeCommand(InputInterface $input, OutputInterface $output $phpExtensions = $this->getImportantPhpExtensions(); $diskSpace = $this->getDiskSpace(); - $nodeVersionDisplay = Comparator::lessThan($nodeVersion, $latestLtsNodeVersion) + $nodeOutdated = Comparator::lessThan($nodeVersion, $latestLtsNodeVersion); + + if ($this->isJsonOutput()) { + $this->writeJson([ + 'php' => ['version' => $phpVersion, 'memory_limit' => $this->getPhpMemoryLimit()], + 'composer' => $composerVersion, + 'node' => [ + 'version' => $nodeVersion, + 'latest_lts' => $latestLtsNodeVersion, + 'outdated' => $nodeOutdated, + ], + 'npm' => $npmVersion, + 'git' => $gitVersion, + 'database' => ['type' => $dbType, 'version' => $mysqlVersion], + 'xdebug' => $xdebugStatus, + 'redis' => $redisStatus, + 'search_engine' => $searchEngineStatus, + 'os' => $osInfo, + 'disk_space' => $diskSpace, + 'magento' => $magentoVersion, + 'php_extensions' => array_column($phpExtensions, 1, 0), + ]); + + return Cli::RETURN_SUCCESS; + } + + $nodeVersionDisplay = $nodeOutdated ? "$nodeVersion (Latest LTS: $latestLtsNodeVersion)" : "$nodeVersion (Latest LTS: $latestLtsNodeVersion)"; diff --git a/src/Console/Command/System/VersionCommand.php b/src/Console/Command/System/VersionCommand.php index 0201786f..02e53d6b 100644 --- a/src/Console/Command/System/VersionCommand.php +++ b/src/Console/Command/System/VersionCommand.php @@ -41,6 +41,7 @@ protected function configure(): void ->setName($this->getCommandName('system', 'version')) ->setDescription('Displays the module version and the latest version') ->setAliases(['system:version']); + $this->addFormatOption(); } /** @@ -55,6 +56,16 @@ protected function executeCommand(InputInterface $input, OutputInterface $output $moduleVersion = $this->getModuleVersion(); $latestVersion = $this->getLatestVersion(); + if ($this->isJsonOutput()) { + $this->writeJson([ + 'module_version' => $this->knownVersion($moduleVersion), + 'latest_version' => $this->knownVersion($latestVersion), + 'update_available' => $this->isUpdateAvailable($moduleVersion, $latestVersion), + ]); + + return Cli::RETURN_SUCCESS; + } + $this->io->title('MageForge Version Information'); $this->io->section('Versions'); $this->io->listing([ @@ -65,6 +76,33 @@ protected function executeCommand(InputInterface $input, OutputInterface $output return Cli::RETURN_SUCCESS; } + /** + * Map the unknown placeholder to null + * + * @param string $version + * @return string|null + */ + private function knownVersion(string $version): ?string + { + return $version === self::UNKNOWN_VERSION ? null : $version; + } + + /** + * Check whether a newer release than the installed one exists + * + * @param string $moduleVersion + * @param string $latestVersion + * @return bool|null Null if either version is unknown + */ + private function isUpdateAvailable(string $moduleVersion, string $latestVersion): ?bool + { + if ($moduleVersion === self::UNKNOWN_VERSION || $latestVersion === self::UNKNOWN_VERSION) { + return null; + } + + return version_compare(ltrim($latestVersion, 'v'), ltrim($moduleVersion, 'v'), '>'); + } + /** * Get the current module version * diff --git a/src/Console/Command/Template/ObsoleteCommand.php b/src/Console/Command/Template/ObsoleteCommand.php index d45b2ba2..02ceb2c6 100644 --- a/src/Console/Command/Template/ObsoleteCommand.php +++ b/src/Console/Command/Template/ObsoleteCommand.php @@ -82,7 +82,6 @@ protected function configure(): void 'Delete the overrides that are safe to remove (identical or belonging to a missing module)', ) ->addOption('yes', 'y', InputOption::VALUE_NONE, 'Delete without asking for confirmation') - ->addOption('format', null, InputOption::VALUE_REQUIRED, 'Output format: table or json', 'table') ->addOption( 'fail-on-found', null, @@ -90,6 +89,7 @@ protected function configure(): void 'Return a failure exit code when obsolete overrides were found (for CI)', ) ->setAliases(['template:obsolete']); + $this->addFormatOption(); } /** @@ -101,27 +101,23 @@ protected function configure(): void */ protected function executeCommand(InputInterface $input, OutputInterface $output): int { - /** @var string $format */ - $format = $input->getOption('format'); + $isJson = $this->isJsonOutput(); $isDelete = (bool) $input->getOption('delete'); - if (!in_array($format, ['table', 'json'], true)) { - $this->io->error("Invalid format '$format'. Use 'table' or 'json'."); - return Cli::RETURN_FAILURE; - } - if ($isDelete && $format === 'json') { + if ($isDelete && $isJson) { $this->io->error('--delete cannot be combined with --format=json.'); + $this->writeJsonError('--delete cannot be combined with --format=json.'); return Cli::RETURN_FAILURE; } - $isInteractive = $format === 'table' && $input->isInteractive() && $this->isInteractiveTerminal($output); + $isInteractive = !$isJson && $input->isInteractive() && $this->isInteractiveTerminal($output); $themes = $this->resolveThemes($input, $output, $isInteractive); if ($themes === null) { return Cli::RETURN_FAILURE; } if ($themes === []) { - if ($format === 'json') { - $this->io->writeln('[]'); + if ($isJson) { + $this->writeJson([]); } else { $this->io->warning('No frontend themes found to check.'); } @@ -141,8 +137,8 @@ protected function executeCommand(InputInterface $input, OutputInterface $output array_push($findings, ...$this->scanner->scan($theme, $isDeep)); } - if ($format === 'json') { - $this->io->writeln($this->toJson($findings)); + if ($isJson) { + $this->writeJson($this->toArray($findings)); } else { $this->displayFindings($findings, array_map(static fn($theme) => $theme->getCode(), $themes)); } @@ -391,24 +387,21 @@ private function deleteSafeFindings(array $findings, bool $assumeYes, OutputInte } /** - * Encode the findings as JSON + * Convert the findings to a JSON-serialisable list * * @param ObsoleteOverride[] $findings - * @return string + * @return array> */ - private function toJson(array $findings): string + private function toArray(array $findings): array { - return json_encode( - array_map(fn(ObsoleteOverride $finding): array => [ - 'theme' => $finding->getThemeCode(), - 'template' => $finding->getTemplateId(), - 'file' => $this->toRelativePath($finding->getFile()), - 'reason' => $finding->getReason()->value, - 'details' => $finding->getDetails(), - 'safe_to_delete' => $finding->isSafeToDelete(), - ], $findings), - JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, - ); + return array_map(fn(ObsoleteOverride $finding): array => [ + 'theme' => $finding->getThemeCode(), + 'template' => $finding->getTemplateId(), + 'file' => $this->toRelativePath($finding->getFile()), + 'reason' => $finding->getReason()->value, + 'details' => $finding->getDetails(), + 'safe_to_delete' => $finding->isSafeToDelete(), + ], $findings); } /** diff --git a/src/Console/Command/Theme/BuildCommand.php b/src/Console/Command/Theme/BuildCommand.php index 230be94e..d1720da1 100644 --- a/src/Console/Command/Theme/BuildCommand.php +++ b/src/Console/Command/Theme/BuildCommand.php @@ -67,6 +67,7 @@ protected function configure(): void ) ->setAliases(['frontend:build']); $this->addParentThemeOptions(); + $this->addFormatOption(); } /** @@ -98,6 +99,11 @@ protected function executeCommand(InputInterface $input, OutputInterface $output $options = array_values(array_map(static fn($theme) => $theme->getCode(), $themes)); // Check if we're in an interactive terminal environment + if ($this->isJsonOutput()) { + $this->writeJsonError('No themes specified. Pass one or more theme codes, e.g. Magento/luma.'); + return Command::FAILURE; + } + if (!$this->isInteractiveTerminal($output)) { // Fallback for non-interactive environments $this->displayAvailableThemes($this->io); @@ -143,24 +149,25 @@ protected function executeCommand(InputInterface $input, OutputInterface $output // Correct theme names first so parents are resolved for the final theme codes $validatedCodes = []; - $invalidCount = 0; + $invalidCodes = []; foreach ($themeCodes as $themeCode) { $validated = $this->validateAndCorrectTheme($themeCode, $this->io, $output); if ($validated === null) { - $invalidCount++; + $invalidCodes[] = $themeCode; continue; } $validatedCodes[] = $validated; } if ($validatedCodes === []) { + $this->writeJsonError(sprintf('No valid themes found: %s', implode(', ', $invalidCodes))); return Command::FAILURE; } $validatedCodes = $this->expandWithParents($input, $output, $validatedCodes); - $result = $this->processBuildThemes($validatedCodes, $this->io, $output, $isVerbose); + $result = $this->processBuildThemes($validatedCodes, $this->io, $output, $isVerbose, $invalidCodes); - return $invalidCount > 0 ? Command::FAILURE : $result; + return $invalidCodes !== [] ? Command::FAILURE : $result; } /** @@ -236,6 +243,7 @@ private function displayAvailableThemes(SymfonyStyle $io): void * @param SymfonyStyle $io * @param OutputInterface $output * @param bool $isVerbose + * @param array $failedCodes Theme codes that were already rejected as invalid * @return int */ private function processBuildThemes( @@ -243,18 +251,20 @@ private function processBuildThemes( SymfonyStyle $io, OutputInterface $output, bool $isVerbose, + array $failedCodes = [], ): int { $startTime = microtime(true); $successList = []; $failedCount = 0; $totalThemes = count($themeCodes); - if ($isVerbose) { + if ($isVerbose || $this->isJsonOutput()) { $io->title(sprintf('Building %d theme(s)', $totalThemes)); foreach ($themeCodes as $themeCode) { if (!$this->processTheme($themeCode, $io, $output, $isVerbose, $successList)) { $failedCount++; + $failedCodes[] = $themeCode; } } } else { @@ -268,6 +278,7 @@ private function processBuildThemes( if ($validatedTheme === null) { // Theme validation failed or user cancelled - skip this theme $failedCount++; + $failedCodes[] = $themeCode; continue; } @@ -296,6 +307,7 @@ private function processBuildThemes( )); } else { $failedCount++; + $failedCodes[] = $validatedTheme; // Show that an error occurred while building the theme $io->writeln(sprintf( ' Building %s (%d of %d) ... failed', @@ -307,7 +319,21 @@ private function processBuildThemes( } } - $this->displayBuildSummary($io, $successList, microtime(true) - $startTime); + $duration = microtime(true) - $startTime; + if ($this->isJsonOutput()) { + $this->writeJson([ + 'success' => $failedCount === 0 && $failedCodes === [], + 'duration_seconds' => round($duration, 2), + 'built' => array_map(static fn(array $entry): array => [ + 'theme' => $entry['theme'], + 'builder' => $entry['builder'], + 'hyva_version' => $entry['hyvaVersion'], + ], $successList), + 'failed' => $failedCodes, + ]); + } else { + $this->displayBuildSummary($io, $successList, $duration); + } return $failedCount > 0 ? Command::FAILURE : Command::SUCCESS; } diff --git a/src/Console/Command/Theme/InfoCommand.php b/src/Console/Command/Theme/InfoCommand.php index ec7a1c89..3121d666 100644 --- a/src/Console/Command/Theme/InfoCommand.php +++ b/src/Console/Command/Theme/InfoCommand.php @@ -19,7 +19,6 @@ use OpenForgeProject\MageForge\Service\ThemeSuggester; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** @@ -70,8 +69,8 @@ protected function configure(): void InputArgument::OPTIONAL, 'Theme code (format: Vendor/theme), omit to select interactively', ) - ->addOption('json', null, InputOption::VALUE_NONE, 'Output the information as JSON') ->setAliases(['m:t:i', 'frontend:info']); + $this->addFormatOption(); } /** @@ -85,9 +84,14 @@ protected function executeCommand(InputInterface $input, OutputInterface $output { /** @var string|null $themeCode */ $themeCode = $input->getArgument('themeCode'); - $asJson = (bool) $input->getOption('json'); if ($themeCode === null) { + if ($this->isJsonOutput()) { + $this->writeJsonError('No theme specified. Pass a theme code, e.g. Magento/luma.'); + + return Cli::RETURN_FAILURE; + } + $themeCode = $this->selectThemeInteractively($input, $output); if ($themeCode === null) { return Cli::RETURN_SUCCESS; @@ -100,6 +104,7 @@ protected function executeCommand(InputInterface $input, OutputInterface $output if ($path === null || $theme === null) { $suggestions = $this->themeSuggester->findSimilarThemes($themeCode); $this->io->error("Theme '$themeCode' is not installed."); + $this->writeJsonError("Theme '$themeCode' is not installed."); if ($suggestions !== []) { $this->io->writeln('Did you mean: ' . implode(', ', $suggestions) . '?'); } @@ -126,8 +131,8 @@ protected function executeCommand(InputInterface $input, OutputInterface $output 'locales' => $this->infoCollector->getDeployedLocales($theme->getArea(), $theme->getCode()), ]; - if ($asJson) { - $output->writeln(json_encode($info, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)); + if ($this->isJsonOutput()) { + $this->writeJson($info); return Cli::RETURN_SUCCESS; } diff --git a/src/Console/Command/Theme/ListCommand.php b/src/Console/Command/Theme/ListCommand.php index b029f0f0..aed63ebc 100644 --- a/src/Console/Command/Theme/ListCommand.php +++ b/src/Console/Command/Theme/ListCommand.php @@ -36,6 +36,7 @@ protected function configure(): void ->setName($this->getCommandName('theme', 'list')) ->setDescription('Lists all available Magento themes') ->setAliases(['frontend:list']); + $this->addFormatOption(); } /** @@ -49,6 +50,21 @@ protected function executeCommand(InputInterface $input, OutputInterface $output { $themes = $this->themeList->getAllThemes(); + if ($this->isJsonOutput()) { + $this->writeJson(array_map( + static fn($path, $theme): array => [ + 'code' => $theme->getCode(), + 'title' => $theme->getThemeTitle(), + 'area' => $theme->getArea(), + 'path' => $path, + ], + array_keys($themes), + $themes, + )); + + return Cli::RETURN_SUCCESS; + } + if (empty($themes)) { $this->io->info('No themes found.'); return Cli::RETURN_SUCCESS; diff --git a/tests/Unit/Console/Command/AbstractCommandTest.php b/tests/Unit/Console/Command/AbstractCommandTest.php index 5aee2f57..3078ed9b 100644 --- a/tests/Unit/Console/Command/AbstractCommandTest.php +++ b/tests/Unit/Console/Command/AbstractCommandTest.php @@ -59,6 +59,68 @@ public function testExecuteCatchesExceptionsAndReturnsFailure(): void $this->assertStringContainsString('boom', $tester->getDisplay()); } + public function testJsonModeWritesOnlyTheDocumentToStdoutAndLogsToStderr(): void + { + $this->command->setJsonPayload(['key' => 'a/b']); + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--format' => 'json'], ['capture_stderr_separately' => true]); + + $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + $this->assertSame(['key' => 'a/b'], json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR)); + $this->assertStringContainsString('"key": "a/b"', $tester->getDisplay()); + $this->assertStringContainsString('diagnostic message', $tester->getErrorOutput()); + } + + public function testJsonFlagIsShortcutForJsonFormat(): void + { + $this->command->setJsonPayload(['ok' => true]); + $tester = new CommandTester($this->command); + $tester->execute(['--json' => true], ['capture_stderr_separately' => true]); + + $this->assertSame(['ok' => true], json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR)); + } + + public function testTableFormatKeepsHumanReadableOutput(): void + { + $this->command->setJsonPayload(['ok' => true]); + $tester = new CommandTester($this->command); + $tester->execute([]); + + $this->assertStringContainsString('diagnostic message', $tester->getDisplay()); + $this->assertStringNotContainsString('"ok"', $tester->getDisplay()); + } + + public function testInvalidFormatFails(): void + { + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--format' => 'xml']); + + $this->assertSame(Cli::RETURN_FAILURE, $exitCode); + $this->assertStringContainsString("Invalid format 'xml'", $tester->getDisplay()); + } + + public function testJsonModeWritesErrorDocumentForExceptions(): void + { + $this->command->setThrowOnExecute(new \RuntimeException('boom')); + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--format' => 'json']); + + $this->assertSame(Cli::RETURN_FAILURE, $exitCode); + $this->assertSame(['error' => 'boom'], json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR)); + } + + public function testJsonModeWritesFallbackErrorWhenCommandFailsWithoutDocument(): void + { + $this->command->setExecuteCommandReturn(Cli::RETURN_FAILURE); + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--format' => 'json']); + + $this->assertSame(Cli::RETURN_FAILURE, $exitCode); + /** @var array $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertArrayHasKey('error', $json); + } + #[DataProvider('verbosityProvider')] public function testVerbosityHelpersReflectOutputVerbosity( int $verbosity, diff --git a/tests/Unit/Console/Command/ConcreteTestCommand.php b/tests/Unit/Console/Command/ConcreteTestCommand.php index ce997892..ebd7c539 100644 --- a/tests/Unit/Console/Command/ConcreteTestCommand.php +++ b/tests/Unit/Console/Command/ConcreteTestCommand.php @@ -29,6 +29,10 @@ class ConcreteTestCommand extends AbstractCommand * @var ?bool */ private ?bool $realTtyAvailableOverride = null; + /** + * @var ?array + */ + private ?array $jsonPayload = null; /** * Configures the command name. @@ -36,6 +40,7 @@ class ConcreteTestCommand extends AbstractCommand protected function configure(): void { $this->setName('test:concrete-command'); + $this->addFormatOption(); } /** @@ -50,9 +55,24 @@ protected function executeCommand(InputInterface $input, OutputInterface $output throw $this->throwOnExecute; } + $this->io->warning('diagnostic message'); + if ($this->jsonPayload !== null && $this->isJsonOutput()) { + $this->writeJson($this->jsonPayload); + } + return $this->executeCommandReturn; } + /** + * Sets the document written by executeCommand() in JSON mode. + * + * @param array $payload + */ + public function setJsonPayload(array $payload): void + { + $this->jsonPayload = $payload; + } + /** * Returns the overridden TTY availability, falling back to the parent implementation. */ diff --git a/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php b/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php index fef5562c..f16a094b 100644 --- a/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php +++ b/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php @@ -192,6 +192,42 @@ public function testContinuesWithRemainingThemesWhenOneFails(): void $this->assertStringContainsString('Failed to process 1 theme(s): Vendor/broken', $display); } + public function testJsonOutputListsUpdatedSkippedAndFailedThemes(): void + { + $this->themePath->method('getPath')->willReturn('/path'); + $this->dependencyUpdater->method('updateThemeDependencies')->willReturnOnConsecutiveCalls( + DependencyUpdateResult::Updated, + DependencyUpdateResult::Skipped, + DependencyUpdateResult::Failed, + ); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute([ + 'themeCodes' => ['Vendor/one', 'Vendor/two', 'Vendor/three'], + '--dry-run' => true, + '--format' => 'json', + ]); + + $this->assertSame(Cli::RETURN_FAILURE, $exitCode); + /** @var array $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertTrue($json['dry_run']); + $this->assertSame(['Vendor/one'], $json['updated']); + $this->assertSame(['Vendor/two'], $json['skipped']); + $this->assertSame(['Vendor/three'], $json['failed']); + } + + public function testJsonOutputFailsWithoutThemeCodes(): void + { + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--json' => true]); + + $this->assertSame(Cli::RETURN_FAILURE, $exitCode); + /** @var array $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertArrayHasKey('error', $json); + } + private function createCommand( ?DependencyUpdater $dependencyUpdater = null, ?ThemePath $themePath = null, diff --git a/tests/Unit/Console/Command/Hyva/CompatibilityCheckCommandTest.php b/tests/Unit/Console/Command/Hyva/CompatibilityCheckCommandTest.php index cafb3abf..a4727c81 100644 --- a/tests/Unit/Console/Command/Hyva/CompatibilityCheckCommandTest.php +++ b/tests/Unit/Console/Command/Hyva/CompatibilityCheckCommandTest.php @@ -648,4 +648,76 @@ public function testTailwind4HintsWhenNothingToCheck(): void $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); $this->assertStringContainsString('No Hyvä themes or modules with Tailwind sources', $tester->getDisplay()); } + + public function testJsonOutputContainsSummaryModulesAndTailwind4Findings(): void + { + $moduleData = [ + 'compatible' => false, + 'hasWarnings' => false, + 'scanResult' => ['files' => [], 'totalIssues' => 1, 'criticalIssues' => 1], + 'moduleInfo' => ['name' => 'Vendor_Module', 'version' => '1.0.0', 'isHyvaAware' => false], + ]; + $compatibleData = $moduleData; + $compatibleData['compatible'] = true; + $results = $this->makeResults([ + 'modules' => ['Vendor_Module' => $moduleData, 'Vendor_Ok' => $compatibleData], + 'summary' => [ + 'total' => 2, + 'compatible' => 1, + 'incompatible' => 1, + 'hyvaAware' => 0, + 'criticalIssues' => 1, + 'warningIssues' => 0, + ], + 'hasIssues' => true, + ]); + $this->compatibilityChecker->method('check')->willReturn($results); + $this->compatibilityChecker->method('getDetailedIssues')->willReturn([ + ['file' => 'view/a.js', 'issues' => [ + ['description' => 'Uses jQuery', 'severity' => 'critical', 'line' => 3, 'pattern' => 'jquery'], + ]], + ]); + $this->tailwind4Checker->method('check')->willReturn([ + 'sections' => ['Theme A' => [ + new Tailwind4Finding(Tailwind4Severity::Warning, 'Old config', 'Migrate it', 'tailwind.config.js', 4), + ]], + 'themes' => 1, + 'modules' => 0, + 'errors' => 0, + 'warnings' => 1, + ]); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--tailwind4' => true, '--format' => 'json']); + + $this->assertSame(Cli::RETURN_FAILURE, $exitCode); + /** + * @var array{ + * summary: array{criticalIssues: int}, + * modules: array}>, + * tailwind4: array{findings: array} + * } $json + */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame(1, $json['summary']['criticalIssues']); + $this->assertCount(1, $json['modules'], 'Compatible modules are hidden without --show-all'); + $this->assertSame('incompatible', $json['modules'][0]['status']); + $this->assertSame('view/a.js', $json['modules'][0]['files'][0]['file']); + $this->assertSame('tailwind.config.js:4', $json['tailwind4']['findings'][0]['location']); + $this->assertSame('warning', $json['tailwind4']['findings'][0]['severity']); + } + + public function testJsonOutputHasNullTailwind4WhenNotChecked(): void + { + $this->compatibilityChecker->method('check')->willReturn($this->makeResults()); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--format' => 'json']); + + $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + /** @var array $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertNull($json['tailwind4']); + $this->assertSame([], $json['modules']); + } } diff --git a/tests/Unit/Console/Command/System/CheckCommandTest.php b/tests/Unit/Console/Command/System/CheckCommandTest.php index 879b217d..23e9067d 100644 --- a/tests/Unit/Console/Command/System/CheckCommandTest.php +++ b/tests/Unit/Console/Command/System/CheckCommandTest.php @@ -97,6 +97,33 @@ public function testDisplaysFullSystemReport(): void ); } + public function testJsonOutputContainsStructuredSystemReport(): void + { + $this->givenShellVersions([ + 'node -v 2>/dev/null' => 'v20.11.0', + 'composer --version 2>/dev/null' => 'Composer version 2.7.1 2024-02-09 15:26:28', + 'npm --version 2>/dev/null' => '10.2.4', + 'git --version 2>/dev/null' => 'git version 2.44.0', + ]); + $this->givenDatabaseVersion('10.6.18-MariaDB'); + $this->givenHttpResponses([self::NODE_LTS_URL => [200, self::NODE_LTS_BODY]]); + + $tester = new CommandTester($this->createCommand()); + $exitCode = $tester->execute(['--format' => 'json']); + + $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + /** @var array> $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame(PHP_VERSION, $json['php']['version']); + $this->assertSame( + ['version' => '20.11.0', 'latest_lts' => '22.13.0', 'outdated' => true], + $json['node'], + ); + $this->assertSame('2.7.1', $json['composer']); + $this->assertSame('2.4.8', $json['magento']); + $this->assertSame('Enabled', $json['php_extensions']['curl']); + } + public function testReportsOpenSearchWhenConnectionSucceeds(): void { $this->givenShellVersions(['node -v 2>/dev/null' => 'v22.13.0']); diff --git a/tests/Unit/Console/Command/System/VersionCommandTest.php b/tests/Unit/Console/Command/System/VersionCommandTest.php index 21fa05e3..7f9fedf3 100644 --- a/tests/Unit/Console/Command/System/VersionCommandTest.php +++ b/tests/Unit/Console/Command/System/VersionCommandTest.php @@ -98,6 +98,35 @@ public function testDisplaysUnknownLatestVersionForInvalidApiResponse(): void $this->assertStringContainsString('Latest Version: Unknown', $tester->getDisplay()); } + public function testJsonOutputReportsVersionsAndAvailableUpdate(): void + { + $this->fileDriver->method('fileGetContents')->willReturn('{"version": "1.2.3"}'); + $command = $this->createCommand([new Response(200, [], '{"tag_name": "v1.3.0"}')]); + + $tester = new CommandTester($command); + $exitCode = $tester->execute(['--format' => 'json']); + + $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + $this->assertSame( + ['module_version' => '1.2.3', 'latest_version' => 'v1.3.0', 'update_available' => true], + json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), + ); + } + + public function testJsonOutputUsesNullForUnknownVersions(): void + { + $this->fileDriver->method('fileGetContents')->willReturn('{"version": "1.2.3"}'); + $command = $this->createCommand([new Response(500, [], 'Server Error')]); + + $tester = new CommandTester($command); + $tester->execute(['--json' => true]); + + $this->assertSame( + ['module_version' => '1.2.3', 'latest_version' => null, 'update_available' => null], + json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), + ); + } + /** * Build the command with a Guzzle client that replays canned responses * instead of calling the GitHub API. diff --git a/tests/Unit/Console/Command/Theme/BuildCommandTest.php b/tests/Unit/Console/Command/Theme/BuildCommandTest.php index 1d0dda55..70cf21cb 100644 --- a/tests/Unit/Console/Command/Theme/BuildCommandTest.php +++ b/tests/Unit/Console/Command/Theme/BuildCommandTest.php @@ -311,6 +311,43 @@ private function createCommand( ); } + public function testJsonOutputReportsBuiltAndFailedThemes(): void + { + $this->themePath->method('getPath')->willReturnCallback( + static fn(string $code): ?string => $code === 'Vendor/missing' ? null : '/p/' . $code, + ); + $builder = $this->createNamedBuilder('tailwind'); + $builder->method('build')->willReturnCallback(static fn(string $code): bool => $code !== 'Vendor/broken'); + $this->builderPool->method('getBuilder')->willReturn($builder); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute([ + 'themeCodes' => ['Vendor/ok', 'Vendor/broken', 'Vendor/missing'], + '--format' => 'json', + ]); + + $this->assertSame(Command::FAILURE, $exitCode); + /** @var array $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertFalse($json['success']); + $this->assertSame( + [['theme' => 'Vendor/ok', 'builder' => 'tailwind', 'hyva_version' => null]], + $json['built'], + ); + $this->assertEqualsCanonicalizing(['Vendor/broken', 'Vendor/missing'], $json['failed']); + } + + public function testJsonOutputFailsWithoutThemeCodes(): void + { + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--json' => true]); + + $this->assertSame(Command::FAILURE, $exitCode); + /** @var array $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertArrayHasKey('error', $json); + } + private function createNamedBuilder(string $name): BuilderInterface&Stub { $builder = $this->createStub(BuilderInterface::class); diff --git a/tests/Unit/Console/Command/Theme/ListCommandTest.php b/tests/Unit/Console/Command/Theme/ListCommandTest.php index 538371a4..ba78e713 100644 --- a/tests/Unit/Console/Command/Theme/ListCommandTest.php +++ b/tests/Unit/Console/Command/Theme/ListCommandTest.php @@ -56,6 +56,33 @@ public function testDisplaysTableOfAvailableThemes(): void $this->assertStringContainsString('frontend/Vendor/theme', $display); } + public function testJsonOutputListsThemes(): void + { + $theme = new FakeThemeWithTitle('Vendor/theme', 'Vendor Theme'); + $this->themeList->method('getAllThemes')->willReturn(['frontend/Vendor/theme' => $theme]); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--format' => 'json']); + + $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + /** @var array> $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame('Vendor/theme', $json[0]['code']); + $this->assertSame('Vendor Theme', $json[0]['title']); + $this->assertSame('frontend/Vendor/theme', $json[0]['path']); + $this->assertArrayHasKey('area', $json[0]); + } + + public function testJsonOutputIsEmptyArrayWithoutThemes(): void + { + $this->themeList->method('getAllThemes')->willReturn([]); + + $tester = new CommandTester($this->command); + $tester->execute(['--json' => true]); + + $this->assertSame([], json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR)); + } + public function testCommandNameAndAliases(): void { $this->assertSame('mageforge:theme:list', $this->command->getName()); From a0d6fb27862d761701b600757d0ad0caf35d24fa Mon Sep 17 00:00:00 2001 From: Thomas Hauschild <7961978+Morgy93@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:56:24 +0100 Subject: [PATCH 2/3] fix(cli): validate --format before --json and emit JSON for empty runs - Validate the --format value before applying the --json shortcut so that --format=xml --json is rejected instead of executing the command. - theme:build and dependencies:update write an empty JSON result when a wildcard matches no theme, keeping the no-op success exit code. - Return a list from the obsolete override serialiser to satisfy mago analyze. Refs #307 --- src/Console/Command/AbstractCommand.php | 8 ++--- .../Command/Dependencies/UpdateCommand.php | 32 +++++++++++++++++-- .../Command/Template/ObsoleteCommand.php | 4 +-- src/Console/Command/Theme/BuildCommand.php | 4 +++ .../Console/Command/AbstractCommandTest.php | 9 ++++++ .../Dependencies/UpdateCommandTest.php | 20 ++++++++++++ .../Command/Theme/BuildCommandTest.php | 14 ++++++++ 7 files changed, 82 insertions(+), 9 deletions(-) diff --git a/src/Console/Command/AbstractCommand.php b/src/Console/Command/AbstractCommand.php index f99b98a1..1a9ecb6f 100644 --- a/src/Console/Command/AbstractCommand.php +++ b/src/Console/Command/AbstractCommand.php @@ -201,13 +201,13 @@ private function resolveFormat(InputInterface $input): ?string if (!$definition->hasOption('format')) { return self::FORMAT_TABLE; } - if ($definition->hasOption('json') && $input->getOption('json')) { - return self::FORMAT_JSON; - } $format = $this->getFormatOptionValue($input); + if (!in_array($format, [self::FORMAT_TABLE, self::FORMAT_JSON], true)) { + return null; + } - return in_array($format, [self::FORMAT_TABLE, self::FORMAT_JSON], true) ? $format : null; + return $definition->hasOption('json') && $input->getOption('json') ? self::FORMAT_JSON : $format; } /** diff --git a/src/Console/Command/Dependencies/UpdateCommand.php b/src/Console/Command/Dependencies/UpdateCommand.php index b75c9ae7..ff6b1af3 100644 --- a/src/Console/Command/Dependencies/UpdateCommand.php +++ b/src/Console/Command/Dependencies/UpdateCommand.php @@ -83,9 +83,7 @@ protected function executeCommand(InputInterface $input, OutputInterface $output if ($themeCodes === null) { if ($this->isJsonOutput()) { - $this->writeJsonError('No themes to update. Pass one or more theme codes.'); - - return Cli::RETURN_FAILURE; + return $this->writeEmptyJsonResult($input, $dryRun); } return Cli::RETURN_SUCCESS; @@ -115,6 +113,34 @@ protected function executeCommand(InputInterface $input, OutputInterface $output return Cli::RETURN_SUCCESS; } + /** + * Write the JSON result for runs that selected no themes + * + * Wildcards that matched nothing are a successful no-op; omitting the theme codes is an error. + * + * @param InputInterface $input + * @param bool $dryRun + * @return int + */ + private function writeEmptyJsonResult(InputInterface $input, bool $dryRun): int + { + if ($input->getArgument('themeCodes') === []) { + $this->writeJsonError('No themes specified. Pass one or more theme codes, e.g. Magento/luma.'); + + return Cli::RETURN_FAILURE; + } + + $this->writeJson([ + 'dry_run' => $dryRun, + 'duration_seconds' => 0.0, + 'updated' => [], + 'skipped' => [], + 'failed' => [], + ]); + + return Cli::RETURN_SUCCESS; + } + /** * Resolve which themes to update based on input * diff --git a/src/Console/Command/Template/ObsoleteCommand.php b/src/Console/Command/Template/ObsoleteCommand.php index 02ceb2c6..a03dc88e 100644 --- a/src/Console/Command/Template/ObsoleteCommand.php +++ b/src/Console/Command/Template/ObsoleteCommand.php @@ -394,14 +394,14 @@ private function deleteSafeFindings(array $findings, bool $assumeYes, OutputInte */ private function toArray(array $findings): array { - return array_map(fn(ObsoleteOverride $finding): array => [ + return array_values(array_map(fn(ObsoleteOverride $finding): array => [ 'theme' => $finding->getThemeCode(), 'template' => $finding->getTemplateId(), 'file' => $this->toRelativePath($finding->getFile()), 'reason' => $finding->getReason()->value, 'details' => $finding->getDetails(), 'safe_to_delete' => $finding->isSafeToDelete(), - ], $findings); + ], $findings)); } /** diff --git a/src/Console/Command/Theme/BuildCommand.php b/src/Console/Command/Theme/BuildCommand.php index d1720da1..ec09a7f0 100644 --- a/src/Console/Command/Theme/BuildCommand.php +++ b/src/Console/Command/Theme/BuildCommand.php @@ -88,6 +88,10 @@ protected function executeCommand(InputInterface $input, OutputInterface $output // If wildcards matched nothing and no other explicit themes remain if (empty($themeCodes)) { + if ($this->isJsonOutput()) { + $this->writeJson(['success' => true, 'duration_seconds' => 0.0, 'built' => [], 'failed' => []]); + } + return Command::SUCCESS; } } diff --git a/tests/Unit/Console/Command/AbstractCommandTest.php b/tests/Unit/Console/Command/AbstractCommandTest.php index 3078ed9b..59b36af2 100644 --- a/tests/Unit/Console/Command/AbstractCommandTest.php +++ b/tests/Unit/Console/Command/AbstractCommandTest.php @@ -99,6 +99,15 @@ public function testInvalidFormatFails(): void $this->assertStringContainsString("Invalid format 'xml'", $tester->getDisplay()); } + public function testJsonShortcutDoesNotBypassFormatValidation(): void + { + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--format' => 'xml', '--json' => true]); + + $this->assertSame(Cli::RETURN_FAILURE, $exitCode); + $this->assertStringContainsString("Invalid format 'xml'", $tester->getDisplay()); + } + public function testJsonModeWritesErrorDocumentForExceptions(): void { $this->command->setThrowOnExecute(new \RuntimeException('boom')); diff --git a/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php b/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php index f16a094b..ad2cb054 100644 --- a/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php +++ b/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php @@ -217,6 +217,26 @@ public function testJsonOutputListsUpdatedSkippedAndFailedThemes(): void $this->assertSame(['Vendor/three'], $json['failed']); } + public function testJsonOutputIsEmptySuccessWhenWildcardMatchesNothing(): void + { + $this->themeList->method('getAllThemes')->willReturn([]); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['themeCodes' => ['Missing/*'], '--json' => true]); + + $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + $this->assertEquals( + [ + 'dry_run' => false, + 'duration_seconds' => 0.0, + 'updated' => [], + 'skipped' => [], + 'failed' => [], + ], + json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), + ); + } + public function testJsonOutputFailsWithoutThemeCodes(): void { $tester = new CommandTester($this->command); diff --git a/tests/Unit/Console/Command/Theme/BuildCommandTest.php b/tests/Unit/Console/Command/Theme/BuildCommandTest.php index 70cf21cb..2b9ae6bf 100644 --- a/tests/Unit/Console/Command/Theme/BuildCommandTest.php +++ b/tests/Unit/Console/Command/Theme/BuildCommandTest.php @@ -337,6 +337,20 @@ public function testJsonOutputReportsBuiltAndFailedThemes(): void $this->assertEqualsCanonicalizing(['Vendor/broken', 'Vendor/missing'], $json['failed']); } + public function testJsonOutputIsEmptySuccessWhenWildcardMatchesNothing(): void + { + $this->themeList->method('getAllThemes')->willReturn([]); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['themeCodes' => ['Missing/*'], '--format' => 'json']); + + $this->assertSame(Command::SUCCESS, $exitCode); + $this->assertEquals( + ['success' => true, 'duration_seconds' => 0.0, 'built' => [], 'failed' => []], + json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), + ); + } + public function testJsonOutputFailsWithoutThemeCodes(): void { $tester = new CommandTester($this->command); From a40d986e8270618abfddd0239d88b0bf0b1d492c Mon Sep 17 00:00:00 2001 From: Thomas Hauschild <7961978+Morgy93@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:16:06 +0100 Subject: [PATCH 3/3] test(cli): kill escaped mutants in JSON output - Assert exact JSON documents, error messages, stderr separation, unicode handling and success/failure exit codes in the JSON output tests. - Move duration rounding into AbstractCommand::roundSeconds() so it can be tested deterministically. - Remove equivalent mutants: drop the redundant jsonOutput reset, the nullable stdout, the redundant failedCount check and the 0 initialiser for the Tailwind CSS v4 error count. Refs #307 --- src/Console/Command/AbstractCommand.php | 18 +- .../Command/Dependencies/UpdateCommand.php | 2 +- .../Hyva/CompatibilityCheckCommand.php | 7 +- .../Command/Template/ObsoleteCommand.php | 8 +- src/Console/Command/Theme/BuildCommand.php | 4 +- .../Console/Command/AbstractCommandTest.php | 28 ++++ .../Console/Command/ConcreteTestCommand.php | 10 ++ .../Dependencies/UpdateCommandTest.php | 9 +- .../Hyva/CompatibilityCheckCommandTest.php | 154 ++++++++++++++---- .../Command/System/CheckCommandTest.php | 6 +- .../Command/System/VersionCommandTest.php | 16 +- .../Command/Theme/BuildCommandTest.php | 57 ++++++- .../Console/Command/Theme/ListCommandTest.php | 3 +- 13 files changed, 266 insertions(+), 56 deletions(-) diff --git a/src/Console/Command/AbstractCommand.php b/src/Console/Command/AbstractCommand.php index 1a9ecb6f..a803ec2f 100644 --- a/src/Console/Command/AbstractCommand.php +++ b/src/Console/Command/AbstractCommand.php @@ -49,9 +49,9 @@ abstract class AbstractCommand extends Command private bool $jsonWritten = false; /** - * @var OutputInterface|null Real standard output, kept separate from $io which logs to stderr in JSON mode + * @var OutputInterface Real standard output, kept separate from $io which logs to stderr in JSON mode */ - private ?OutputInterface $stdout = null; + private OutputInterface $stdout; /** * @var array @@ -91,7 +91,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int { $this->stdout = $output; $this->jsonWritten = false; - $this->jsonOutput = false; $format = $this->resolveFormat($input); if ($format === null) { @@ -162,7 +161,7 @@ protected function isJsonOutput(): bool */ protected function writeJson(mixed $data): void { - $this->stdout?->writeln( + $this->stdout->writeln( json_encode( $data, JSON_PRETTY_PRINT @@ -176,6 +175,17 @@ protected function writeJson(mixed $data): void $this->jsonWritten = true; } + /** + * Round a duration for JSON output + * + * @param float $seconds + * @return float + */ + protected function roundSeconds(float $seconds): float + { + return round($seconds, 2); + } + /** * Write a JSON error document to stdout when running in JSON mode * diff --git a/src/Console/Command/Dependencies/UpdateCommand.php b/src/Console/Command/Dependencies/UpdateCommand.php index ff6b1af3..7099afb9 100644 --- a/src/Console/Command/Dependencies/UpdateCommand.php +++ b/src/Console/Command/Dependencies/UpdateCommand.php @@ -97,7 +97,7 @@ protected function executeCommand(InputInterface $input, OutputInterface $output if ($this->isJsonOutput()) { $this->writeJson([ 'dry_run' => $dryRun, - 'duration_seconds' => round($duration, 2), + 'duration_seconds' => $this->roundSeconds($duration), 'updated' => $updatedThemes, 'skipped' => $skippedThemes, 'failed' => $failedThemes, diff --git a/src/Console/Command/Hyva/CompatibilityCheckCommand.php b/src/Console/Command/Hyva/CompatibilityCheckCommand.php index 8c392e1b..4a037a83 100644 --- a/src/Console/Command/Hyva/CompatibilityCheckCommand.php +++ b/src/Console/Command/Hyva/CompatibilityCheckCommand.php @@ -377,10 +377,9 @@ private function outputJson( $hyvaVersion = $this->hyvaVersionDetector->getVersion(); $tailwind4Results = null; - $tailwind4Errors = 0; + $tailwind4Check = null; if ($tailwind4 || $hyvaVersion !== null) { $tailwind4Check = $this->tailwind4Checker->check($thirdPartyOnly, $excludeVendor); - $tailwind4Errors = $tailwind4Check['errors']; $tailwind4Results = $this->tailwind4ToArray($tailwind4Check, $hyvaVersion); } @@ -390,7 +389,9 @@ private function outputJson( 'tailwind4' => $tailwind4Results, ]); - return $results['summary']['criticalIssues'] > 0 || $tailwind4Errors > 0 + $hasTailwind4Errors = $tailwind4Check !== null && $tailwind4Check['errors'] > 0; + + return $results['summary']['criticalIssues'] > 0 || $hasTailwind4Errors ? Cli::RETURN_FAILURE : Cli::RETURN_SUCCESS; } diff --git a/src/Console/Command/Template/ObsoleteCommand.php b/src/Console/Command/Template/ObsoleteCommand.php index a03dc88e..36e449fb 100644 --- a/src/Console/Command/Template/ObsoleteCommand.php +++ b/src/Console/Command/Template/ObsoleteCommand.php @@ -389,19 +389,19 @@ private function deleteSafeFindings(array $findings, bool $assumeYes, OutputInte /** * Convert the findings to a JSON-serialisable list * - * @param ObsoleteOverride[] $findings - * @return array> + * @param list $findings + * @return list> */ private function toArray(array $findings): array { - return array_values(array_map(fn(ObsoleteOverride $finding): array => [ + return array_map(fn(ObsoleteOverride $finding): array => [ 'theme' => $finding->getThemeCode(), 'template' => $finding->getTemplateId(), 'file' => $this->toRelativePath($finding->getFile()), 'reason' => $finding->getReason()->value, 'details' => $finding->getDetails(), 'safe_to_delete' => $finding->isSafeToDelete(), - ], $findings)); + ], $findings); } /** diff --git a/src/Console/Command/Theme/BuildCommand.php b/src/Console/Command/Theme/BuildCommand.php index ec09a7f0..9f4b6fe8 100644 --- a/src/Console/Command/Theme/BuildCommand.php +++ b/src/Console/Command/Theme/BuildCommand.php @@ -326,8 +326,8 @@ private function processBuildThemes( $duration = microtime(true) - $startTime; if ($this->isJsonOutput()) { $this->writeJson([ - 'success' => $failedCount === 0 && $failedCodes === [], - 'duration_seconds' => round($duration, 2), + 'success' => $failedCodes === [], + 'duration_seconds' => $this->roundSeconds($duration), 'built' => array_map(static fn(array $entry): array => [ 'theme' => $entry['theme'], 'builder' => $entry['builder'], diff --git a/tests/Unit/Console/Command/AbstractCommandTest.php b/tests/Unit/Console/Command/AbstractCommandTest.php index 59b36af2..aa347596 100644 --- a/tests/Unit/Console/Command/AbstractCommandTest.php +++ b/tests/Unit/Console/Command/AbstractCommandTest.php @@ -99,6 +99,34 @@ public function testInvalidFormatFails(): void $this->assertStringContainsString("Invalid format 'xml'", $tester->getDisplay()); } + public function testJsonOutputKeepsUnicodeAndSubstitutesInvalidUtf8(): void + { + $this->command->setJsonPayload(['text' => "caf\u{E9} \xB1"]); + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--format' => 'json']); + + $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + $this->assertStringContainsString("\"caf\u{E9} \u{FFFD}\"", $tester->getDisplay()); + } + + public function testJsonModeIsNeverInteractive(): void + { + $output = $this->createStub(OutputInterface::class); + $output->method('isDecorated')->willReturn(true); + $this->command->setRealTtyAvailable(true); + $this->assertTrue($this->command->callIsInteractiveTerminal($output)); + + (new CommandTester($this->command))->execute(['--format' => 'json']); + + $this->assertFalse($this->command->callIsInteractiveTerminal($output)); + } + + public function testRoundSecondsRoundsToTwoDecimals(): void + { + $this->assertSame(1.23, $this->command->callRoundSeconds(1.23456)); + $this->assertSame(1.24, $this->command->callRoundSeconds(1.2351)); + } + public function testJsonShortcutDoesNotBypassFormatValidation(): void { $tester = new CommandTester($this->command); diff --git a/tests/Unit/Console/Command/ConcreteTestCommand.php b/tests/Unit/Console/Command/ConcreteTestCommand.php index ebd7c539..c7296ed2 100644 --- a/tests/Unit/Console/Command/ConcreteTestCommand.php +++ b/tests/Unit/Console/Command/ConcreteTestCommand.php @@ -132,6 +132,16 @@ public function callGetCommandName(string $group, string $command): string return $this->getCommandName($group, $command); } + /** + * Exposes the protected roundSeconds(). + * + * @param float $seconds + */ + public function callRoundSeconds(float $seconds): float + { + return $this->roundSeconds($seconds); + } + /** * Exposes the protected isVerbose(). * diff --git a/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php b/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php index ad2cb054..0109f913 100644 --- a/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php +++ b/tests/Unit/Console/Command/Dependencies/UpdateCommandTest.php @@ -212,6 +212,8 @@ public function testJsonOutputListsUpdatedSkippedAndFailedThemes(): void /** @var array $json */ $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); $this->assertTrue($json['dry_run']); + $this->assertGreaterThanOrEqual(0, $json['duration_seconds']); + $this->assertLessThan(60, $json['duration_seconds']); $this->assertSame(['Vendor/one'], $json['updated']); $this->assertSame(['Vendor/two'], $json['skipped']); $this->assertSame(['Vendor/three'], $json['failed']); @@ -243,9 +245,10 @@ public function testJsonOutputFailsWithoutThemeCodes(): void $exitCode = $tester->execute(['--json' => true]); $this->assertSame(Cli::RETURN_FAILURE, $exitCode); - /** @var array $json */ - $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); - $this->assertArrayHasKey('error', $json); + $this->assertSame( + ['error' => 'No themes specified. Pass one or more theme codes, e.g. Magento/luma.'], + json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), + ); } private function createCommand( diff --git a/tests/Unit/Console/Command/Hyva/CompatibilityCheckCommandTest.php b/tests/Unit/Console/Command/Hyva/CompatibilityCheckCommandTest.php index a4727c81..4ca9c8f5 100644 --- a/tests/Unit/Console/Command/Hyva/CompatibilityCheckCommandTest.php +++ b/tests/Unit/Console/Command/Hyva/CompatibilityCheckCommandTest.php @@ -651,60 +651,146 @@ public function testTailwind4HintsWhenNothingToCheck(): void public function testJsonOutputContainsSummaryModulesAndTailwind4Findings(): void { - $moduleData = [ - 'compatible' => false, - 'hasWarnings' => false, + $files = [ + ['file' => 'view/a.js', 'issues' => [ + ['description' => 'Uses jQuery', 'severity' => 'critical', 'line' => 3, 'pattern' => 'jquery'], + ]], + ]; + $makeModule = static fn(bool $compatible, bool $hasWarnings, string $version, bool $aware): array => [ + 'compatible' => $compatible, + 'hasWarnings' => $hasWarnings, 'scanResult' => ['files' => [], 'totalIssues' => 1, 'criticalIssues' => 1], - 'moduleInfo' => ['name' => 'Vendor_Module', 'version' => '1.0.0', 'isHyvaAware' => false], + 'moduleInfo' => ['name' => 'unused', 'version' => $version, 'isHyvaAware' => $aware], ]; - $compatibleData = $moduleData; - $compatibleData['compatible'] = true; $results = $this->makeResults([ - 'modules' => ['Vendor_Module' => $moduleData, 'Vendor_Ok' => $compatibleData], + 'modules' => [ + 'Vendor_Broken' => $makeModule(false, false, '1.0.0', false), + 'Vendor_Warn' => $makeModule(true, true, '2.0.0', false), + 'Vendor_Ok' => $makeModule(true, false, '3.0.0', true), + ], 'summary' => [ - 'total' => 2, - 'compatible' => 1, + 'total' => 3, + 'compatible' => 2, 'incompatible' => 1, - 'hyvaAware' => 0, + 'hyvaAware' => 1, 'criticalIssues' => 1, - 'warningIssues' => 0, + 'warningIssues' => 1, ], 'hasIssues' => true, ]); $this->compatibilityChecker->method('check')->willReturn($results); - $this->compatibilityChecker->method('getDetailedIssues')->willReturn([ - ['file' => 'view/a.js', 'issues' => [ - ['description' => 'Uses jQuery', 'severity' => 'critical', 'line' => 3, 'pattern' => 'jquery'], - ]], - ]); + $this->compatibilityChecker->method('getDetailedIssues')->willReturn($files); + $this->hyvaVersionDetector->method('getVersion')->willReturn('1.4.2'); + $tailwind4Checker = $this->createMock(Tailwind4Checker::class); + $tailwind4Checker + ->expects($this->once()) + ->method('check') + ->with(true, true) + ->willReturn([ + 'sections' => ['Theme A' => [ + new Tailwind4Finding( + Tailwind4Severity::Warning, + 'Old config', + 'Migrate it', + 'tailwind.config.js', + 4, + ), + ]], + 'themes' => 1, + 'modules' => 2, + 'errors' => 0, + 'warnings' => 1, + ]); + + $tester = new CommandTester($this->createCommand(tailwind4Checker: $tailwind4Checker)); + $exitCode = $tester->execute(['--show-all' => true, '--format' => 'json']); + + $this->assertSame(Cli::RETURN_FAILURE, $exitCode); + $this->assertSame( + [ + 'summary' => $results['summary'], + 'modules' => [ + ['name' => 'Vendor_Broken', 'version' => '1.0.0', 'status' => 'incompatible', 'hyva_aware' => false, + 'files' => $files], + ['name' => 'Vendor_Warn', 'version' => '2.0.0', 'status' => 'warnings', 'hyva_aware' => false, + 'files' => $files], + ['name' => 'Vendor_Ok', 'version' => '3.0.0', 'status' => 'compatible', 'hyva_aware' => true, + 'files' => $files], + ], + 'tailwind4' => [ + 'hyva_version' => '1.4.2', + 'themes' => 1, + 'modules' => 2, + 'errors' => 0, + 'warnings' => 1, + 'findings' => [[ + 'section' => 'Theme A', + 'severity' => 'warning', + 'message' => 'Old config', + 'hint' => 'Migrate it', + 'location' => 'tailwind.config.js:4', + ]], + ], + ], + json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), + ); + } + + public function testJsonOutputHidesCompatibleModulesWithoutShowAll(): void + { + $compatible = [ + 'compatible' => true, + 'hasWarnings' => false, + 'scanResult' => ['files' => [], 'totalIssues' => 0, 'criticalIssues' => 0], + 'moduleInfo' => ['name' => 'Vendor_Ok', 'version' => '1.0.0', 'isHyvaAware' => false], + ]; + $broken = $compatible; + $broken['compatible'] = false; + $this->compatibilityChecker->method('check')->willReturn( + $this->makeResults(['modules' => ['Vendor_Ok' => $compatible, 'Vendor_Broken' => $broken]]), + ); + $this->compatibilityChecker->method('getDetailedIssues')->willReturn([]); + + $tester = new CommandTester($this->command); + $tester->execute(['--format' => 'json']); + + /** @var array{modules: array} $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame(['Vendor_Broken'], array_column($json['modules'], 'name')); + } + + public function testJsonOutputSucceedsWhenTailwind4HasOnlyWarnings(): void + { + $this->compatibilityChecker->method('check')->willReturn($this->makeResults()); $this->tailwind4Checker->method('check')->willReturn([ - 'sections' => ['Theme A' => [ - new Tailwind4Finding(Tailwind4Severity::Warning, 'Old config', 'Migrate it', 'tailwind.config.js', 4), - ]], + 'sections' => [], 'themes' => 1, 'modules' => 0, 'errors' => 0, - 'warnings' => 1, + 'warnings' => 3, + ]); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['--tailwind4' => true, '--format' => 'json']); + + $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + } + + public function testJsonOutputFailsOnTailwind4ErrorsEvenWithoutCriticalIssues(): void + { + $this->compatibilityChecker->method('check')->willReturn($this->makeResults()); + $this->tailwind4Checker->method('check')->willReturn([ + 'sections' => [], + 'themes' => 1, + 'modules' => 0, + 'errors' => 2, + 'warnings' => 0, ]); $tester = new CommandTester($this->command); $exitCode = $tester->execute(['--tailwind4' => true, '--format' => 'json']); $this->assertSame(Cli::RETURN_FAILURE, $exitCode); - /** - * @var array{ - * summary: array{criticalIssues: int}, - * modules: array}>, - * tailwind4: array{findings: array} - * } $json - */ - $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); - $this->assertSame(1, $json['summary']['criticalIssues']); - $this->assertCount(1, $json['modules'], 'Compatible modules are hidden without --show-all'); - $this->assertSame('incompatible', $json['modules'][0]['status']); - $this->assertSame('view/a.js', $json['modules'][0]['files'][0]['file']); - $this->assertSame('tailwind.config.js:4', $json['tailwind4']['findings'][0]['location']); - $this->assertSame('warning', $json['tailwind4']['findings'][0]['severity']); } public function testJsonOutputHasNullTailwind4WhenNotChecked(): void diff --git a/tests/Unit/Console/Command/System/CheckCommandTest.php b/tests/Unit/Console/Command/System/CheckCommandTest.php index 23e9067d..bcc9bac2 100644 --- a/tests/Unit/Console/Command/System/CheckCommandTest.php +++ b/tests/Unit/Console/Command/System/CheckCommandTest.php @@ -109,12 +109,16 @@ public function testJsonOutputContainsStructuredSystemReport(): void $this->givenHttpResponses([self::NODE_LTS_URL => [200, self::NODE_LTS_BODY]]); $tester = new CommandTester($this->createCommand()); - $exitCode = $tester->execute(['--format' => 'json']); + $exitCode = $tester->execute(['--format' => 'json'], ['capture_stderr_separately' => true]); $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + $this->assertStringNotContainsString('System Components', $tester->getErrorOutput()); /** @var array> $json */ $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); $this->assertSame(PHP_VERSION, $json['php']['version']); + $this->assertSame(ini_get('memory_limit'), $json['php']['memory_limit']); + $this->assertArrayHasKey('type', $json['database']); + $this->assertSame('10.6.18-MariaDB', $json['database']['version']); $this->assertSame( ['version' => '20.11.0', 'latest_lts' => '22.13.0', 'outdated' => true], $json['node'], diff --git a/tests/Unit/Console/Command/System/VersionCommandTest.php b/tests/Unit/Console/Command/System/VersionCommandTest.php index 7f9fedf3..8f4104d7 100644 --- a/tests/Unit/Console/Command/System/VersionCommandTest.php +++ b/tests/Unit/Console/Command/System/VersionCommandTest.php @@ -104,15 +104,29 @@ public function testJsonOutputReportsVersionsAndAvailableUpdate(): void $command = $this->createCommand([new Response(200, [], '{"tag_name": "v1.3.0"}')]); $tester = new CommandTester($command); - $exitCode = $tester->execute(['--format' => 'json']); + $exitCode = $tester->execute(['--format' => 'json'], ['capture_stderr_separately' => true]); $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + $this->assertStringNotContainsString('Version Information', $tester->getErrorOutput()); $this->assertSame( ['module_version' => '1.2.3', 'latest_version' => 'v1.3.0', 'update_available' => true], json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), ); } + public function testJsonOutputIgnoresVPrefixWhenComparingVersions(): void + { + $this->fileDriver->method('fileGetContents')->willReturn('{"version": "v1.3.0"}'); + $command = $this->createCommand([new Response(200, [], '{"tag_name": "v1.3.0"}')]); + + $tester = new CommandTester($command); + $tester->execute(['--json' => true]); + + /** @var array $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertFalse($json['update_available']); + } + public function testJsonOutputUsesNullForUnknownVersions(): void { $this->fileDriver->method('fileGetContents')->willReturn('{"version": "1.2.3"}'); diff --git a/tests/Unit/Console/Command/Theme/BuildCommandTest.php b/tests/Unit/Console/Command/Theme/BuildCommandTest.php index 2b9ae6bf..5d3ff360 100644 --- a/tests/Unit/Console/Command/Theme/BuildCommandTest.php +++ b/tests/Unit/Console/Command/Theme/BuildCommandTest.php @@ -330,6 +330,8 @@ public function testJsonOutputReportsBuiltAndFailedThemes(): void /** @var array $json */ $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); $this->assertFalse($json['success']); + $this->assertGreaterThanOrEqual(0, $json['duration_seconds']); + $this->assertLessThan(60, $json['duration_seconds']); $this->assertSame( [['theme' => 'Vendor/ok', 'builder' => 'tailwind', 'hyva_version' => null]], $json['built'], @@ -357,9 +359,60 @@ public function testJsonOutputFailsWithoutThemeCodes(): void $exitCode = $tester->execute(['--json' => true]); $this->assertSame(Command::FAILURE, $exitCode); - /** @var array $json */ + $this->assertSame( + ['error' => 'No themes specified. Pass one or more theme codes, e.g. Magento/luma.'], + json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), + ); + } + + public function testJsonOutputReportsSuccessWhenAllThemesBuild(): void + { + $this->themePath->method('getPath')->willReturn('/p/theme'); + $builder = $this->createNamedBuilder('tailwind'); + $builder->method('build')->willReturn(true); + $this->builderPool->method('getBuilder')->willReturn($builder); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['themeCodes' => ['Vendor/ok'], '--format' => 'json']); + + $this->assertSame(Command::SUCCESS, $exitCode); + /** @var array $json */ $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); - $this->assertArrayHasKey('error', $json); + $this->assertTrue($json['success']); + $this->assertSame([], $json['failed']); + } + + public function testJsonOutputReportsFailureWhenOnlySomeRequestedThemesAreInvalid(): void + { + $this->themePath->method('getPath')->willReturnCallback( + static fn(string $code): ?string => $code === 'Vendor/missing' ? null : '/p/' . $code, + ); + $builder = $this->createNamedBuilder('tailwind'); + $builder->method('build')->willReturn(true); + $this->builderPool->method('getBuilder')->willReturn($builder); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['themeCodes' => ['Vendor/ok', 'Vendor/missing'], '--format' => 'json']); + + $this->assertSame(Command::FAILURE, $exitCode); + /** @var array $json */ + $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); + $this->assertFalse($json['success']); + $this->assertSame(['Vendor/missing'], $json['failed']); + } + + public function testJsonOutputReportsErrorWhenNoRequestedThemeIsValid(): void + { + $this->themePath->method('getPath')->willReturn(null); + + $tester = new CommandTester($this->command); + $exitCode = $tester->execute(['themeCodes' => ['Vendor/missing'], '--format' => 'json']); + + $this->assertSame(Command::FAILURE, $exitCode); + $this->assertSame( + ['error' => 'No valid themes found: Vendor/missing'], + json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR), + ); } private function createNamedBuilder(string $name): BuilderInterface&Stub diff --git a/tests/Unit/Console/Command/Theme/ListCommandTest.php b/tests/Unit/Console/Command/Theme/ListCommandTest.php index ba78e713..7183e7ae 100644 --- a/tests/Unit/Console/Command/Theme/ListCommandTest.php +++ b/tests/Unit/Console/Command/Theme/ListCommandTest.php @@ -62,9 +62,10 @@ public function testJsonOutputListsThemes(): void $this->themeList->method('getAllThemes')->willReturn(['frontend/Vendor/theme' => $theme]); $tester = new CommandTester($this->command); - $exitCode = $tester->execute(['--format' => 'json']); + $exitCode = $tester->execute(['--format' => 'json'], ['capture_stderr_separately' => true]); $this->assertSame(Cli::RETURN_SUCCESS, $exitCode); + $this->assertStringNotContainsString('Available Themes', $tester->getErrorOutput()); /** @var array> $json */ $json = json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR); $this->assertSame('Vendor/theme', $json[0]['code']);