Wojciechk
Wojciechk

Reputation: 99

ReflectionMethod get method source and parameters

I would like to have access to the methods by ReflectionMethod:

$r = new ReflectionMethod($class, $method);
$params = $r->getParameters();

and if parameters are required ($Option), get source of that method to prepare the parameters:

public function GetFeedback($Options) {
    $this->checkConnection();
    return $this->_client->doGetFeedback(
        $Options['feedback-from'],
        $Options['feedback-to']
    );
}

so in my example to find $Option keys - 'feedback-from' and 'feedback-to'

Upvotes: 1

Views: 2088

Answers (1)

Gordon
Gordon

Reputation: 316979

Assuming a class like

class Foo
{
    public function GetFeedback($Options) {
        $this->checkConnection();
        return $this->_client->doGetFeedback(
            $Options['feedback-from'],
            $Options['feedback-to']
        );
    }
}

this code will do what you ask for

$reflector = new ReflectionMethod('Foo', 'GetFeedback');
$methodBody = implode(
    '',
    iterator_to_array(
        new LimitIterator(
            new SplFileObject($reflector->getFileName()),
            $reflector->getStartLine(),
            $reflector->getEndLine() - $reflector->getStartLine()
        )
    )
);
foreach ($reflector->getParameters() as $parameter) {
    if (!$parameter->isOptional()) {
        preg_match_all(
            sprintf('{\$%s\[[\'"](.*)[\'"]\]}', $parameter->getName()),
            $methodBody,
            $matches
        );
    }
    print_r($matches);
}

Output:

Array
(
    [0] => Array
        (
            [0] => $Options['feedback-from']
            [1] => $Options['feedback-to']
        )

    [1] => Array
        (
            [0] => feedback-from
            [1] => feedback-to
        )
)

However, the only valid usage for this approach IMO is to generate a docblock listing these options and agree that you are likely doing it wrong if you need this in production code.

Upvotes: 4

Related Questions