Skip to content

Commit 07c6649

Browse files
committed
feat: add event posts for spark
1 parent 340ddf6 commit 07c6649

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

system/CLI/Commands.php

+8-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
namespace CodeIgniter\CLI;
1515

1616
use CodeIgniter\Autoloader\FileLocatorInterface;
17+
use CodeIgniter\Events\Events;
1718
use CodeIgniter\Log\Logger;
1819
use ReflectionClass;
1920
use ReflectionException;
@@ -64,7 +65,13 @@ public function run(string $command, array $params)
6465
$className = $this->commands[$command]['class'];
6566
$class = new $className($this->logger, $this);
6667

67-
return $class->run($params);
68+
Events::trigger('pre_command');
69+
70+
$exit = $class->run($params);
71+
72+
Events::trigger('post_command');
73+
74+
return $exit;
6875
}
6976

7077
/**

tests/system/CLI/ConsoleTest.php

+33
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use CodeIgniter\CodeIgniter;
1717
use CodeIgniter\Config\DotEnv;
18+
use CodeIgniter\Events\Events;
1819
use CodeIgniter\Test\CIUnitTestCase;
1920
use CodeIgniter\Test\Mock\MockCLIConfig;
2021
use CodeIgniter\Test\Mock\MockCodeIgniter;
@@ -79,6 +80,38 @@ public function testRun(): void
7980
$this->assertStringContainsString('Displays basic usage information.', $this->getStreamFilterBuffer());
8081
}
8182

83+
public function testRunEventsPreCommand(): void
84+
{
85+
$result = '';
86+
Events::on('pre_command', static function () use (&$result): void {
87+
$result = 'fired';
88+
});
89+
90+
$this->initCLI();
91+
92+
$console = new Console();
93+
$console->run();
94+
95+
$this->assertEventTriggered('pre_command');
96+
$this->assertSame('fired', $result);
97+
}
98+
99+
public function testRunEventsPostCommand(): void
100+
{
101+
$result = '';
102+
Events::on('post_command', static function () use (&$result): void {
103+
$result = 'fired';
104+
});
105+
106+
$this->initCLI();
107+
108+
$console = new Console();
109+
$console->run();
110+
111+
$this->assertEventTriggered('post_command');
112+
$this->assertSame('fired', $result);
113+
}
114+
82115
public function testBadCommand(): void
83116
{
84117
$this->initCLI('bogus');

user_guide_src/source/extending/events.rst

+8
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,14 @@ invoked by **public/index.php**:
100100
* **post_system** Called right before the final rendered page is sent to the browser,
101101
at the end of system execution, after the execution of "after" controller filters.
102102

103+
For CLI Apps
104+
------------
105+
106+
The following is a list of available event points for :doc:`../cli/spark_commands`:
107+
108+
* **pre_command** Called right before the command code execution.
109+
* **post_command** Called right after the command code execution.
110+
103111
Others
104112
------
105113

0 commit comments

Comments
 (0)