Validate method name, suggesting correct

2

I'm using an email library class from the framework Nette .

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

So the following error was returned to me:

  

Method addSubject does not exist. Did you mean setSubject?

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

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

Example:

class Myclass
{
    public function callMethod()
    {
    }
}


(new MyClass)->callMyMethod(); // Lança a exceção sugerindo o nome correto
    
asked by anonymous 27.10.2015 / 16:00

1 answer

3

Magic Methods

This should be an implementation of the __ call magic method.

  

__ call () fires when unreachable 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
    
27.10.2015 / 16:48