Skip to content

Commit 0b1722c

Browse files
author
Cosmologist
committed
CallableType refactoring
1 parent bde532a commit 0b1722c

File tree

2 files changed

+16
-21
lines changed

2 files changed

+16
-21
lines changed

Type/CallableType.php

+15-20
Original file line numberDiff line numberDiff line change
@@ -8,36 +8,31 @@
88
class CallableType extends GearsCallableType
99
{
1010
/**
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
1218
*/
13-
public static function parse(string $expression): callable
19+
public static function toCallable(string $expression): callable
1420
{
15-
if (self::validateServiceCallable($expression) === false) {
16-
return parent::parse($expression);
21+
if (parent::validate($expression)) {
22+
return $expression;
1723
}
1824

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+
};
2229
}
2330

2431
/**
2532
* {@inheritDoc}
2633
*/
2734
public static function validate(string $expression): bool
2835
{
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)));
4237
}
4338
}

composer.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"license": "MIT",
1313
"require": {
1414
"php": ">=5.4",
15-
"cosmologist/gears": "^2.7.0"
15+
"cosmologist/gears": "^3.0.0"
1616
},
1717
"autoload": {
1818
"psr-4": {

0 commit comments

Comments
 (0)