4
4
5
5
namespace DI \Definition ;
6
6
7
+ use DI \Definition \Exception \InvalidDefinition ;
8
+ use DI \ServiceLocator ;
7
9
use Psr \Container \ContainerInterface ;
8
10
9
11
/**
13
15
*/
14
16
class Reference implements Definition, SelfResolvingDefinition
15
17
{
18
+ public static $ serviceLocatorClass = ServiceLocator::class;
19
+
16
20
/** Entry name. */
17
21
private string $ name = '' ;
18
22
19
- /**
20
- * @param string $targetEntryName Name of the target entry
21
- */
23
+ private bool $ isServiceLocatorEntry ;
24
+
22
25
public function __construct (
26
+ /**
27
+ * @var string Name of the target entry
28
+ */
23
29
private string $ targetEntryName ,
30
+ /**
31
+ * @var string|null name of an entry - holder of a definition requesting this entry
32
+ */
33
+ private ?string $ requestingName = null ,
34
+ private ?ServiceLocatorDefinition $ serviceLocatorDefinition = null
24
35
) {
36
+ $ this ->isServiceLocatorEntry = $ targetEntryName === self ::$ serviceLocatorClass ;
25
37
}
26
38
27
39
public function getName () : string
@@ -39,13 +51,50 @@ public function getTargetEntryName() : string
39
51
return $ this ->targetEntryName ;
40
52
}
41
53
54
+ /**
55
+ * Returns the name of the entity requesting this entry.
56
+ */
57
+ public function getRequestingName () : string
58
+ {
59
+ return $ this ->requestingName ;
60
+ }
61
+
62
+ public function isServiceLocatorEntry () : bool
63
+ {
64
+ return $ this ->isServiceLocatorEntry ;
65
+ }
66
+
67
+ public function getServiceLocatorDefinition () : ServiceLocatorDefinition
68
+ {
69
+ if (!$ this ->isServiceLocatorEntry || $ this ->requestingName === null ) {
70
+ throw new InvalidDefinition (sprintf (
71
+ "Invalid service locator definition ('%s' for '%s') " ,
72
+ $ this ->targetEntryName ,
73
+ $ this ->requestingName
74
+ ));
75
+ }
76
+ if (!$ this ->serviceLocatorDefinition ) {
77
+ $ this ->serviceLocatorDefinition = new ServiceLocatorDefinition ($ this ->getTargetEntryName (), $ this ->requestingName );
78
+ }
79
+
80
+ return $ this ->serviceLocatorDefinition ;
81
+ }
82
+
42
83
public function resolve (ContainerInterface $ container ) : mixed
43
84
{
85
+ if ($ this ->isServiceLocatorEntry ) {
86
+ return $ this ->getServiceLocatorDefinition ()->resolve ($ container );
87
+ }
88
+
44
89
return $ container ->get ($ this ->getTargetEntryName ());
45
90
}
46
91
47
92
public function isResolvable (ContainerInterface $ container ) : bool
48
93
{
94
+ if ($ this ->isServiceLocatorEntry ) {
95
+ return $ this ->getServiceLocatorDefinition ()->isResolvable ($ container );
96
+ }
97
+
49
98
return $ container ->has ($ this ->getTargetEntryName ());
50
99
}
51
100
0 commit comments