8
8
class CallableType extends GearsCallableType
9
9
{
10
10
/**
11
- * {@inheritDoc}
11
+ * Creates and returns callable from a string expression
12
+ *
13
+ * Supports reference to container services:
14
+ * - 'foo.bar::baz' - returns the callable for the service identified "foo.bar" (Symfony 2.x style) and the "baz" method
15
+ * - 'Foo\Bar::baz' - returns the callable for the service identified "Foo\Bar" (Symfony 3.x style) and method "baz"
16
+ *
17
+ * @return callable
12
18
*/
13
- public static function parse (string $ expression ): callable
19
+ public static function toCallable (string $ expression ): callable
14
20
{
15
- if (self :: validateServiceCallable ($ expression ) === false ) {
16
- return parent :: parse ( $ expression) ;
21
+ if (parent :: validate ($ expression )) {
22
+ return $ expression ;
17
23
}
18
24
19
- [$ id , $ method ] = self ::parseComposite ($ expression );
20
-
21
- return [ContainerStatic::get ($ id ), $ method ];
25
+ // It uses closure to avoid initializing unnecessary services (when calling Container::get)
26
+ return function (...$ args ) use ($ expression ) {
27
+ return call_user_func_array ([ContainerStatic::get (self ::extractClassFromExpression ($ expression )), self ::extractMethodFromExpression ($ expression )], $ args );
28
+ };
22
29
}
23
30
24
31
/**
25
32
* {@inheritDoc}
26
33
*/
27
34
public static function validate (string $ expression ): bool
28
35
{
29
- return self ::validateServiceCallable ($ expression ) || parent ::validate ($ expression );
30
- }
31
-
32
- /**
33
- * @param string $expression
34
- *
35
- * @return bool
36
- */
37
- private static function validateServiceCallable (string $ expression )
38
- {
39
- [$ id , $ method ] = self ::parseComposite ($ expression );
40
-
41
- return self ::isCompositeFormat ($ expression ) && ContainerStatic::has ($ id ) && method_exists (ContainerStatic::get ($ id ), $ method );
36
+ return parent ::validate ($ expression ) || (self ::isCompositeFormat ($ expression ) && ContainerStatic::has (self ::extractClassFromExpression ($ expression )));
42
37
}
43
38
}
0 commit comments