Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,18 @@ there are several console specific events:
- `ConsoleEvents::COMMAND_ERROR` is triggered when the application catches any `Throwable` object directly from a command, this can be used to integrate extra error handling/reporting tools
- `ConsoleEvents::TERMINATE` is triggered immediately before the process is completed, developers may listen for this event to perform any actions required at the end of the process

#### Exit codes

When the application exits on its own (the default, see `setAutoExit()`), it exits with the command's return value as
modified by `TerminateEvent::setExitCode()`. A value outside the range 0 to 255 becomes 255; a negative value would
otherwise wrap around and could even end up as 0, i.e. success.

When a `Throwable` is not handled, the exit code is taken from the `APPLICATION_ERROR` event: the value given to
`ApplicationErrorEvent::setExitCode()`, otherwise the code of the `Throwable` or 1 if that is 0. An exit code of 0 is
turned into 1 here, since the application did fail. A listener for `COMMAND_ERROR` can call
`CommandErrorEvent::setExitCode(0)` to treat the error as handled; any other value is written to the code of the
`Throwable` (as in Symfony), which is how it reaches the `APPLICATION_ERROR` event.

## Things to know before you build on this

**Use `$defaultName`, not `#[AsCommand]`.** Symfony removed the static property in 7.0, but
Expand Down
3 changes: 2 additions & 1 deletion src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,8 @@ public function execute()
}

if ($this->shouldAutoExit() && isset($exitCode)) {
$exitCode = $exitCode > 255 ? 255 : $exitCode;
// Exit codes outside 0-255 are not portable, a negative one could even wrap to 0 (success)
$exitCode = $exitCode < 0 || $exitCode > 255 ? 255 : $exitCode;
$this->close($exitCode);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Event/ApplicationErrorEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public function getError(): \Throwable
*/
public function getExitCode(): int
{
return $this->exitCode ?: (\is_int($this->error->getCode()) && $this->error->getCode() !== 0 ? $this->error->getCode() : 1);
return $this->exitCode ?? (\is_int($this->error->getCode()) && $this->error->getCode() !== 0 ? $this->error->getCode() : 1);
}

/**
Expand Down
117 changes: 117 additions & 0 deletions tests/ApplicationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,123 @@ protected function doExecute(InputInterface $input, OutputInterface $output): in
$this->assertSame(1, $app->getExitCode());
}

/**
* Data provider for testExitCodeIsLimitedToTheValidRange
*
* @return array
*/
public static function dataExitCodes(): array
{
// Args: Command return value, expected exit code
return [
'Success' => [0, 0],
'Highest valid code' => [255, 255],
'Above the range' => [256, 255],
'Negative' => [-1, 255],
'Wrapping to 0' => [-256, 255],
];
}

#[DataProvider('dataExitCodes')]
public function testExitCodeIsLimitedToTheValidRange(int $returnValue, int $expected)
{
$command = new class ($returnValue) extends AbstractCommand {
protected static $defaultName = 'exit-code';

private $returnValue;

public function __construct(int $returnValue)
{
$this->returnValue = $returnValue;

parent::__construct();
}

protected function doExecute(InputInterface $input, OutputInterface $output): int
{
return $this->returnValue;
}
};

$input = new ArrayInput(
[
'command' => 'exit-code',
]
);
$output = new NullOutput();

$app = $this->buildMockClosingApplication($input, $output);

$app->addCommand($command);
$app->setAutoExit(true);
$app->execute();

$this->assertSame($expected, $app->getExitCode());
}

public function testErrorExitCodeIsLimitedToTheValidRange()
{
$command = new class () extends AbstractCommand {
protected static $defaultName = 'exception';

protected function doExecute(InputInterface $input, OutputInterface $output): int
{
throw new \Exception('Testing', -256);
}
};

$input = new ArrayInput(
[
'command' => 'exception',
]
);
$output = new NullOutput();

$app = $this->buildMockClosingApplication($input, $output);

$app->addCommand($command);
$app->setAutoExit(true);
$app->execute();

$this->assertSame(255, $app->getExitCode());
}

public function testCommandErrorExitCodeIsSetByEventListener()
{
$command = new class () extends AbstractCommand {
protected static $defaultName = 'exception';

protected function doExecute(InputInterface $input, OutputInterface $output): int
{
throw new \Exception('Testing', 3);
}
};

$dispatcher = new Dispatcher();
$dispatcher->addListener(
ConsoleEvents::COMMAND_ERROR,
function (CommandErrorEvent $event) {
$event->setExitCode(119);
}
);

$input = new ArrayInput(
[
'command' => 'exception',
]
);
$output = new NullOutput();

$app = $this->buildMockClosingApplication($input, $output);

$app->setDispatcher($dispatcher);
$app->addCommand($command);
$app->setAutoExit(true);
$app->execute();

$this->assertSame(119, $app->getExitCode());
}

public function testCommandIsNotExecutedIfEventSkipsCommand()
{
$command = new class () extends AbstractCommand {
Expand Down
72 changes: 72 additions & 0 deletions tests/Event/ApplicationErrorEventTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

/**
* @copyright Copyright (C) 2005 - 2026 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/

namespace Joomla\Console\Tests\Event;

use Joomla\Console\Application;
use Joomla\Console\Event\ApplicationErrorEvent;
use Joomla\Console\Event\CommandErrorEvent;
use Joomla\Console\Event\ConsoleEvent;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;

/**
* Test class for the exit code handling of \Joomla\Console\Event\ApplicationErrorEvent and \Joomla\Console\Event\CommandErrorEvent
*/
#[CoversClass(ApplicationErrorEvent::class)]
#[CoversClass(CommandErrorEvent::class)]
#[UsesClass(ConsoleEvent::class)]
#[UsesClass(Application::class)]
class ApplicationErrorEventTest extends TestCase
{
/**
* @return array
*/
public static function dataEventClasses(): array
{
return [
'ApplicationErrorEvent' => [ApplicationErrorEvent::class],
'CommandErrorEvent' => [CommandErrorEvent::class],
];
}

#[DataProvider('dataEventClasses')]
public function testTheExitCodeDefaultsToTheErrorCode(string $class)
{
$event = new $class(new \RuntimeException('Testing', 42), new Application());

$this->assertSame(42, $event->getExitCode());
}

#[DataProvider('dataEventClasses')]
public function testTheExitCodeIsOneForAnErrorWithoutCode(string $class)
{
$event = new $class(new \RuntimeException('Testing'), new Application());

$this->assertSame(1, $event->getExitCode());
}

#[DataProvider('dataEventClasses')]
public function testTheExitCodeCanBeSet(string $class)
{
$event = new $class(new \RuntimeException('Testing', 42), new Application());
$event->setExitCode(3);

$this->assertSame(3, $event->getExitCode());
}

#[DataProvider('dataEventClasses')]
public function testTheExitCodeCanBeSetToZero(string $class)
{
$event = new $class(new \RuntimeException('Testing', 42), new Application());
$event->setExitCode(0);

$this->assertSame(0, $event->getExitCode());
}
}
Loading