Skip to content

Commit

Permalink
feat: add event posts for spark
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Feb 1, 2024
1 parent 0b21b08 commit 4ad7183
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
9 changes: 8 additions & 1 deletion system/CLI/Commands.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace CodeIgniter\CLI;

use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\Events\Events;
use CodeIgniter\Log\Logger;
use ReflectionClass;
use ReflectionException;
Expand Down Expand Up @@ -64,7 +65,13 @@ public function run(string $command, array $params)
$className = $this->commands[$command]['class'];
$class = new $className($this->logger, $this);

return $class->run($params);
Events::trigger('pre_command');

$exit = $class->run($params);

Events::trigger('post_command');

return $exit;
}

/**
Expand Down
33 changes: 33 additions & 0 deletions tests/system/CLI/ConsoleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use CodeIgniter\CodeIgniter;
use CodeIgniter\Config\DotEnv;
use CodeIgniter\Events\Events;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Mock\MockCLIConfig;
use CodeIgniter\Test\Mock\MockCodeIgniter;
Expand Down Expand Up @@ -79,6 +80,38 @@ public function testRun(): void
$this->assertStringContainsString('Displays basic usage information.', $this->getStreamFilterBuffer());
}

public function testRunEventsPreCommand(): void
{
$result = '';
Events::on('pre_command', static function () use (&$result): void {
$result = 'fired';
});

$this->initCLI();

$console = new Console();
$console->run();

$this->assertEventTriggered('pre_command');
$this->assertSame('fired', $result);
}

public function testRunEventsPostCommand(): void
{
$result = '';
Events::on('post_command', static function () use (&$result): void {
$result = 'fired';
});

$this->initCLI();

$console = new Console();
$console->run();

$this->assertEventTriggered('post_command');
$this->assertSame('fired', $result);
}

public function testBadCommand(): void
{
$this->initCLI('bogus');
Expand Down
8 changes: 8 additions & 0 deletions user_guide_src/source/extending/events.rst
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ invoked by **public/index.php**:
* **post_system** Called right before the final rendered page is sent to the browser,
at the end of system execution, after the execution of "after" controller filters.

For CLI Apps
------------

The following is a list of available event points for :doc:`../cli/spark_commands`:

* **pre_command** Called right before the command code execution.
* **post_command** Called right after the command code execution.

Others
------

Expand Down

0 comments on commit 4ad7183

Please sign in to comment.