diff --git a/src/ComposerReader.php b/src/ComposerReader.php index 9511bcb..4b0da16 100755 --- a/src/ComposerReader.php +++ b/src/ComposerReader.php @@ -157,6 +157,62 @@ public function removeSection($section) $this->_content = $content; } + private ?string $_commandOutput = null; + + private ?int $_commandStatus = null; + + public function createCommand(string $command, ?string $folder = null): self + { + $this->_commandOutput = null; + $this->_commandStatus = null; + + $olddir = null; + if ($folder === null) { + $folder = dirname($this->file); + $olddir = getcwd(); + } + + chdir($folder); + + // Execute the command and capture its full output + $outputLines = []; + $status = null; + exec('composer ' . $command . ' 2>&1', $outputLines, $status); + + // Store full output in case of failure + if ($status !== 0) { + // Failure: Keep all lines + $this->_commandOutput = implode("\n", $outputLines); + } else { + // Success: Keep only the last non-empty line + $filteredLines = array_filter($outputLines); // Remove empty lines + $this->_commandOutput = trim(end($filteredLines)); // Get last non-empty line + } + + $this->_commandStatus = $status; + + if ($olddir !== null) { + chdir($olddir); + } + + return $this; + } + + public function commandIsSuccessful(): bool + { + return $this->getCommandStatus() === 0; + } + + public function getCommandOutput(): ?string + { + return trim($this->_commandOutput); + } + + public function getCommandStatus(): ?int + { + return $this->_commandStatus; + } + /** * Run a composer command in the given composer.json. * @@ -172,17 +228,7 @@ public function removeSection($section) */ public function runCommand($command) { - $folder = dirname($this->file); - $olddir = getcwd(); - chdir($folder); - - ob_start(); - $output = null; - $cmd = system('composer ' . $command, $output); - $output = ob_end_clean(); - chdir($olddir); - - return $cmd !== false; + return $this->createCommand($command)->commandIsSuccessful(); } /** diff --git a/tests/ComposerReaderTest.php b/tests/ComposerReaderTest.php index 113f9c7..4168186 100755 --- a/tests/ComposerReaderTest.php +++ b/tests/ComposerReaderTest.php @@ -106,6 +106,23 @@ public function testRunCommand() $this->assertTrue($r); } + + public function testRunCommandOutput() + { + $reader = new ComposerReader($this->getWorkingComposerJson()); + + $this->assertTrue($reader->canRead()); + + $cmd = $reader->createCommand('dumpautoload'); + $this->assertTrue($cmd->commandIsSuccessful()); + $this->assertSame($cmd->getCommandOutput(), 'Generated autoload files'); + $this->assertSame($cmd->getCommandStatus(), 0); + + $cmdError = $reader->createCommand('dumpautoload --no-such-option'); + $this->assertFalse($cmdError->commandIsSuccessful()); + $this->assertSame($cmdError->getCommandStatus(), 1); + $this->assertStringContainsString('tion does not ex', $cmdError->getCommandOutput()); + } public function testRemove() {