Skip to content

Instantly share code, notes, and snippets.

@ymkjp
Created December 14, 2013 05:00
Show Gist options
  • Save ymkjp/7955866 to your computer and use it in GitHub Desktop.
Save ymkjp/7955866 to your computer and use it in GitHub Desktop.
<?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
<?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