Skip to content

Commit 96d526e

Browse files
committed
feat: allow cli container injection
1 parent 4efef26 commit 96d526e

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

src/CLI/CLI.php

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,11 @@ class CLI
8383
*
8484
* @param Adapter|null $adapter
8585
* @param array $args
86+
* @param Container|null $container
8687
*
8788
* @throws Exception
8889
*/
89-
public function __construct(?Adapter $adapter = null, array $args = [])
90+
public function __construct(?Adapter $adapter = null, array $args = [], ?Container $container = null)
9091
{
9192
if (\php_sapi_name() !== 'cli') {
9293
throw new Exception('CLI tasks can only work from the command line');
@@ -97,7 +98,7 @@ public function __construct(?Adapter $adapter = null, array $args = [])
9798
@\cli_set_process_title($this->command);
9899

99100
$this->adapter = $adapter ?? new Generic();
100-
$this->container = new Container();
101+
$this->container = $container ?? new Container();
101102
}
102103

103104
/**
@@ -213,6 +214,11 @@ public function setResource(string $name, callable $callback, array $dependencie
213214
$this->container->set($name, $callback, $dependencies);
214215
}
215216

217+
public function getContainer(): Container
218+
{
219+
return $this->container;
220+
}
221+
216222
/**
217223
* task-name --foo=test
218224
*
@@ -401,7 +407,7 @@ protected function validate(string $key, array $param, $value): void
401407
}
402408
}
403409

404-
public function setContainer($container): self
410+
public function setContainer(Container $container): self
405411
{
406412
$this->container = $container;
407413

tests/CLI/CLITest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use PHPUnit\Framework\TestCase;
66
use Utopia\CLI\Adapters\Generic;
77
use Utopia\CLI\CLI;
8+
use Utopia\DI\Container;
89
use Utopia\Validator\ArrayList;
910
use Utopia\Validator\Text;
1011

@@ -201,6 +202,30 @@ public function testInjection()
201202
$this->assertEquals('test-value-me@example.com', $result);
202203
}
203204

205+
public function testProvidedContainer()
206+
{
207+
ob_start();
208+
209+
$container = new Container();
210+
$container->set('test', fn () => 'test-value');
211+
212+
$cli = new CLI(new Generic(), ['test.php', 'build'], $container);
213+
214+
$this->assertSame($container, $cli->getContainer());
215+
216+
$cli->task('build')
217+
->inject('test')
218+
->action(function ($test) {
219+
echo $test;
220+
});
221+
222+
$cli->run();
223+
224+
$result = ob_get_clean();
225+
226+
$this->assertEquals('test-value', $result);
227+
}
228+
204229
public function testMatch()
205230
{
206231
$cli = new CLI(new Generic(), ['test.php', 'build2', '--email=me@example.com', '--list=item1', '--list=item2']); // Mock command request

0 commit comments

Comments
 (0)