Validate method name by suggesting the correct one

Asked

Viewed 62 times

2

I am using a framework email library class Nette.

Then at some point, instead of calling the method setSubject - which is the correct method, I called addSubject, because I had forgotten the name of the method.

Soon I was returned the following error:

Method addSubject does not exist. Did you Mean setSubject?

That is, he suggested that the correct name of the class method was setSubject.

How can I do this in one (or several) of my PHP classes?

Example:

class Myclass
{
    public function callMethod()
    {
    }
}


(new MyClass)->callMyMethod(); // Lança a exceção sugerindo o nome correto

1 answer

3


Magic Methods

This must be an implementation of the magic method __call.

__call() is triggered when inaccessible methods are invoked on an object.

Example

class MyClass{

    private $methods = array(
        'runTest' => array(
            'run',
            'RunTest',
            'runstest',
            'runMyTest',
        ),
    );

    public function __call($name, $args){

        $realName = null;
        foreach ($this->methods as $method => $alias){
            foreach ($alias as $k => $wrong){
                if(preg_match("~{$wrong}~i", $name)){
                    $realName = $method;
                    break 2;
                }
            }
        }

        echo "Method {$name} does not exists.";
        if(!empty($realName)){
            echo " Did you mean {$realName}?";
        }
    }

    public function runTest(){
        echo 'HERE';
    }
}

$obj = new MyClass;
$obj->run('in object context'); // Method run does not exists. Did you mean runTest?
$obj->runTest('in object context'); // HERE
  • 1

    +1 legal. I believe it’s right there :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.