Convert @method annotation for magical __call into actual method implementation #6960
-
|
For context, I'm working on php-fig/log-util#6 The class contains Is there a rule for that? I'd like code like this: /**
* @method bool isMagicalMethod(string $param)
*/
class MyClass
{
function __call() { ... }
}To be refactored to something like this: class MyClass
{
public function isMagicalMethod(string $param): bool
{
return $this->__call('isMagicalMethod', [$param]);
}
function __call() { ... }
}The contents of the method cannot be guessed and should be modified manually. |
Beta Was this translation helpful? Give feedback.
Answered by
samsonasik
Jan 22, 2022
Replies: 1 comment
-
|
It seems you can create custom rector rule for that, which uses use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueNode;
public function __construct(private readonly PhpDocInfoFactory $phpDocInfoFactory)
{
}
public function refactor(Node $node): ?Node
{
// check class has __call method
if (! $node->getMethod('__call') instanceof ClassMethod) {
return null;
}
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);
$method = $phpDocInfo->getByName(MethodTagValueNode::class);
if ($method instanceof MethodTagValueNode) {
// check method exists ..
$methodName = $method->methodName;
if ($node->getMethod($methodName) instanceof ClassMethod) {
return null;
}
// logic extract parameters ...
$parameters = $method->parameters;
// create new method
$classMethod = new ClassMethod(MethodName::CONSTRUCT, [
'flags' => Class_::MODIFIER_PUBLIC,
'params' => [
new Param(...) // fill from parameters
],
'stmts' => [
new Return_(new MethodCall(methodname, [$params])
],
]);
$node->addStmt($classMethod);
return $node;
}
return null;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
samsonasik
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It seems you can create custom rector rule for that, which uses
Class_as node type, and check with the PhpDocInfo service, eg: