UndefinedMethodFatalErrorHandler.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Debug\FatalErrorHandler;
  11. use Symfony\Component\Debug\Exception\FatalErrorException;
  12. use Symfony\Component\Debug\Exception\UndefinedMethodException;
  13. /**
  14. * ErrorHandler for undefined methods.
  15. *
  16. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  17. */
  18. class UndefinedMethodFatalErrorHandler implements FatalErrorHandlerInterface
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function handleError(array $error, FatalErrorException $exception)
  24. {
  25. preg_match('/^Call to undefined method (.*)::(.*)\(\)$/', $error['message'], $matches);
  26. if (!$matches) {
  27. return;
  28. }
  29. $className = $matches[1];
  30. $methodName = $matches[2];
  31. $message = sprintf('Attempted to call an undefined method named "%s" of class "%s".', $methodName, $className);
  32. $candidates = array();
  33. foreach (get_class_methods($className) as $definedMethodName) {
  34. $lev = levenshtein($methodName, $definedMethodName);
  35. if ($lev <= strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) {
  36. $candidates[] = $definedMethodName;
  37. }
  38. }
  39. if ($candidates) {
  40. sort($candidates);
  41. $last = array_pop($candidates).'"?';
  42. if ($candidates) {
  43. $candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last;
  44. } else {
  45. $candidates = '"'.$last;
  46. }
  47. $message .= "\nDid you mean to call ".$candidates;
  48. }
  49. return new UndefinedMethodException($message, $exception);
  50. }
  51. }