Skip to content

Commit ddf5aa8

Browse files
committed
Utils: add container builder
1 parent abbef02 commit ddf5aa8

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/Utils/ContainerBuilder.php

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Contributte\Tester\Utils;
4+
5+
use Contributte\Tester\Environment;
6+
use Nette\DI\Compiler;
7+
use Nette\DI\Container as NetteContainer;
8+
use Nette\DI\ContainerLoader;
9+
10+
class ContainerBuilder
11+
{
12+
13+
/** @var callable[] */
14+
private array $onCompile = [];
15+
16+
private string|null $tempDir = null;
17+
18+
private function __construct(private string $key)
19+
{
20+
}
21+
22+
public static function of(?string $key = null): self
23+
{
24+
return new self($key ?? uniqid(random_bytes(16)));
25+
}
26+
27+
public function withCompiler(callable $cb): self
28+
{
29+
$this->onCompile[] = static function (Compiler $compiler) use ($cb): void {
30+
$cb($compiler);
31+
};
32+
33+
return $this;
34+
}
35+
36+
public function withTempDir(string $tempDir): self
37+
{
38+
$this->tempDir = $tempDir;
39+
40+
return $this;
41+
}
42+
43+
public function build(): NetteContainer
44+
{
45+
$loader = new ContainerLoader($this->getTempDir(), true);
46+
$class = $loader->load(function (Compiler $compiler): void {
47+
foreach ($this->onCompile as $cb) {
48+
$cb($compiler);
49+
}
50+
}, $this->key);
51+
52+
return new $class();
53+
}
54+
55+
private function getTempDir(): string
56+
{
57+
if ($this->tempDir === null) {
58+
return Environment::getTmpDir();
59+
}
60+
61+
return $this->tempDir;
62+
}
63+
64+
}

0 commit comments

Comments
 (0)