@@ -23,11 +23,7 @@ public function __construct()
2323 $ this ->request = new Http \Request ;
2424 $ this ->response = new Http \Response ;
2525
26- if (count ($ this ->services ) > 0 ) {
27- foreach ($ this ->services as $ name => $ value ) {
28- $ this ->services [$ name ] = make ($ value );
29- }
30- }
26+ $ this ->injectServices ();
3127 }
3228
3329 /**
@@ -95,6 +91,54 @@ public function errors()
9591 ];
9692 }
9793
94+ protected function getImports (\ReflectionClass $ ref ): array
95+ {
96+ $ file = file ($ ref ->getFileName ());
97+ $ imports = [];
98+
99+ foreach ($ file as $ line ) {
100+ if (preg_match ('/^use\s+([^;]+);/ ' , trim ($ line ), $ m )) {
101+ $ fqcn = trim ($ m [1 ]);
102+ $ short = basename (str_replace ('\\' , '/ ' , $ fqcn ));
103+ $ imports [$ short ] = $ fqcn ;
104+ }
105+
106+ if (strpos (trim ($ line ), 'class ' ) === 0 ) {
107+ break ;
108+ }
109+ }
110+
111+ return $ imports ;
112+ }
113+
114+
115+ protected function injectServices ()
116+ {
117+ $ ref = new \ReflectionClass (static ::class);
118+ $ doc = $ ref ->getDocComment ();
119+
120+ if (!$ doc ) {
121+ return ;
122+ }
123+
124+ $ imports = $ this ->getImports ($ ref );
125+
126+ preg_match_all ('/@property\s+([\w \\\\]+)\s+\$([\w]+)/ ' , $ doc , $ matches , PREG_SET_ORDER );
127+
128+ foreach ($ matches as $ match ) {
129+ list ($ full , $ className , $ name ) = $ match ;
130+
131+ if (!str_contains ($ className , '\\' )) {
132+ $ className = isset ($ imports [$ className ]) ? $ imports [$ className ] : $ ref ->getNamespaceName () . "\\" . $ className ;
133+ }
134+
135+ if (class_exists ($ className )) {
136+ $ this ->services [$ name ] = make ($ className );
137+ }
138+ }
139+ }
140+
141+
98142 public function __get (string $ name )
99143 {
100144 if (isset ($ this ->services [$ name ])) {
0 commit comments