Created
December 14, 2013 05:00
-
-
Save ymkjp/7955866 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once './MethodSuggestion.php'; | |
class SampleClass extends ArrayObject | |
{ | |
// Your code here ... | |
/** | |
* Add 3 lines as below to use method suggestion | |
*/ | |
public function __call($method, $args) | |
{ | |
throw new MethodSuggestionException($method, $this); | |
} | |
} | |
$sugestee = new SampleClass(); | |
$sugestee->couunt(); // typo `couunt` not `count` | |
// This code will show following error message: | |
// PHP Fatal error: Uncaught exception 'MethodSuggestionException' with message '`couunt` is not a valid method. Did you mean `count` ?' in /Users/keso/Dropbox/workspace/MethodSuggestionPHP/SampleClass.php:13 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MethodSuggestionException extends BadMethodCallException | |
{ | |
public function __construct($called_method, $that) | |
{ | |
$this->suggest($called_method, get_class_methods($that)); | |
} | |
protected function suggest($called_method, $methods) | |
{ | |
$distance_hash = array(); | |
foreach ($methods as $method) { | |
$distance_hash[$method] = levenshtein($called_method, $method); | |
} | |
asort($distance_hash); | |
$this->setMessage( | |
$called_method, | |
key(array_slice($distance_hash, 0, 1, true)) | |
); | |
} | |
protected function setMessage($called_method, $similar_method) | |
{ | |
$message = ''; | |
$message .= "`$called_method` is not a valid method. "; | |
$message .= "Did you mean `$similar_method` ?"; | |
$this->message = $message; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment