UndefinedMethodFatalErrorHandler.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. if (!class_exists($className) || null === $methods = get_class_methods($className)) {
  33. // failed to get the class or its methods on which an unknown method was called (for example on an anonymous class)
  34. return new UndefinedMethodException($message, $exception);
  35. }
  36. $candidates = array();
  37. foreach ($methods as $definedMethodName) {
  38. $lev = levenshtein($methodName, $definedMethodName);
  39. if ($lev <= \strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) {
  40. $candidates[] = $definedMethodName;
  41. }
  42. }
  43. if ($candidates) {
  44. sort($candidates);
  45. $last = array_pop($candidates).'"?';
  46. if ($candidates) {
  47. $candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last;
  48. } else {
  49. $candidates = '"'.$last;
  50. }
  51. $message .= "\nDid you mean to call ".$candidates;
  52. }
  53. return new UndefinedMethodException($message, $exception);
  54. }
  55. }