1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Tests; |
5
|
|
|
|
6
|
|
|
use PHPUnit\Framework\TestCase; |
7
|
|
|
use VPA\DI\Container; |
8
|
|
|
use VPA\DI\Injectable; |
9
|
|
|
use VPA\DI\NotFoundException; |
10
|
|
|
|
11
|
|
|
#[Injectable] |
12
|
|
|
class A { |
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
#[Injectable] |
16
|
|
|
class B { |
17
|
|
|
|
18
|
|
|
public function __construct(protected A $a, private int $num) { |
19
|
|
|
} |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
#[Injectable] |
23
|
|
|
class D { |
24
|
|
|
|
25
|
|
|
public function __construct(protected A $a) { |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
class C { |
30
|
|
|
|
31
|
|
|
public function __construct(protected A $a) { |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
|
36
|
|
|
class DITest extends TestCase |
37
|
|
|
{ |
38
|
|
|
/** |
39
|
|
|
* @var Container |
40
|
|
|
*/ |
41
|
|
|
private Container $di; |
42
|
|
|
|
43
|
|
|
public function setUp(): void |
44
|
|
|
{ |
45
|
|
|
parent::setUp(); |
46
|
|
|
$this->di = new Container(); |
47
|
|
|
$this->di->registerContainers([ |
48
|
|
|
'\E'=>A::class |
49
|
|
|
]); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function testInitClassWithoutDependencies() |
53
|
|
|
{ |
54
|
|
|
|
55
|
|
|
$a = $this->di->get(A::class); |
56
|
|
|
$this->assertTrue($a instanceof A); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function testInitClassWithDependencies() |
60
|
|
|
{ |
61
|
|
|
$d = $this->di->get(D::class); |
62
|
|
|
$this->assertTrue($d instanceof D); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function testInitClassWithParams() |
66
|
|
|
{ |
67
|
|
|
$b = $this->di->get(B::class, ['num'=>10]); |
68
|
|
|
$this->assertTrue($b instanceof B); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function testInitClassWithoutAttributeInjection() |
72
|
|
|
{ |
73
|
|
|
try { |
74
|
|
|
$this->di->get(C::class); |
75
|
|
|
$this->assertTrue(false); |
76
|
|
|
} catch (NotFoundException $e) { |
77
|
|
|
$this->assertTrue(true); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
public function testInitAilasedClass() |
82
|
|
|
{ |
83
|
|
|
$a = $this->di->get('\E'); |
84
|
|
|
$this->assertTrue($a instanceof A); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
public function testInitDISingleton() |
88
|
|
|
{ |
89
|
|
|
$di = new Container(); |
90
|
|
|
$a = $di->get(A::class); |
91
|
|
|
$this->assertTrue($a instanceof A); |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
public function testInitDISingletonAliasedClass() |
95
|
|
|
{ |
96
|
|
|
$di = new Container(); |
97
|
|
|
$a = $di->get('\E'); |
98
|
|
|
$this->assertTrue($a instanceof A); |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
} |