|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Ray\Compiler; |
|
6
|
|
|
|
|
7
|
|
|
use Ray\Compiler\Annotation\Compile; |
|
8
|
|
|
use Ray\Di\AbstractModule; |
|
9
|
|
|
use Ray\Di\Annotation\ScriptDir; |
|
10
|
|
|
use Ray\Di\Exception\Unbound; |
|
11
|
|
|
use Ray\Di\Injector as RayInjector; |
|
12
|
|
|
use Ray\Di\InjectorInterface; |
|
13
|
|
|
use RuntimeException; |
|
14
|
|
|
|
|
15
|
|
|
use function is_dir; |
|
16
|
|
|
use function mkdir; |
|
17
|
|
|
use function sprintf; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @psalm-immutable |
|
21
|
|
|
* @psalm-import-type ScriptDir from Types |
|
22
|
|
|
* @psalm-suppress DeprecatedClass |
|
23
|
|
|
*/ |
|
24
|
|
|
final class InjectorFactory |
|
25
|
|
|
{ |
|
26
|
|
|
/** |
|
27
|
|
|
* @param callable(): AbstractModule $modules |
|
28
|
|
|
* @param ScriptDir $scriptDir |
|
29
|
|
|
*/ |
|
30
|
|
|
public static function getInstance(callable $modules, string $scriptDir): InjectorInterface |
|
31
|
|
|
{ |
|
32
|
|
|
if (! is_dir($scriptDir) && ! mkdir($scriptDir, 0777, true)) { |
|
33
|
|
|
// @codeCoverageIgnoreStart |
|
34
|
|
|
throw new RuntimeException(sprintf('Failed to create script directory: %s', $scriptDir)); |
|
35
|
|
|
// @codeCoverageIgnoreEnd |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
$module = $modules(); |
|
39
|
|
|
$rayInjector = new RayInjector($module, $scriptDir); |
|
40
|
|
|
$isProd = false; |
|
|
|
|
|
|
41
|
|
|
try { |
|
42
|
|
|
/** @var bool $isProd */ |
|
43
|
|
|
$isProd = $rayInjector->getInstance('', Compile::class); |
|
44
|
|
|
} catch (Unbound) { |
|
|
|
|
|
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
if ($isProd === false) { |
|
48
|
|
|
return $rayInjector; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
if ($modules instanceof LazyModuleInterface) { |
|
52
|
|
|
return self::getCompiledInjector($scriptDir, ($modules)()); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return self::getCompiledInjector($scriptDir, $module); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** @param ScriptDir $scriptDir */ |
|
59
|
|
|
private static function getCompiledInjector(string $scriptDir, AbstractModule $module): InjectorInterface |
|
60
|
|
|
{ |
|
61
|
|
|
(new Compiler())->compile($module, $scriptDir); |
|
62
|
|
|
|
|
63
|
|
|
return new CompiledInjector($scriptDir); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|