UndefinedMethodFatalErrorHandler.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.4, use "%s" instead.', UndefinedMethodFatalErrorHandler::class, \Symfony\Component\ErrorHandler\ErrorEnhancer\UndefinedMethodErrorEnhancer::class), E_USER_DEPRECATED);
  14. /**
  15. * ErrorHandler for undefined methods.
  16. *
  17. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  18. *
  19. * @deprecated since Symfony 4.4, use Symfony\Component\ErrorHandler\ErrorEnhancer\UndefinedMethodErrorEnhancer instead.
  20. */
  21. class UndefinedMethodFatalErrorHandler implements FatalErrorHandlerInterface
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function handleError(array $error, FatalErrorException $exception)
  27. {
  28. preg_match('/^Call to undefined method (.*)::(.*)\(\)$/', $error['message'], $matches);
  29. if (!$matches) {
  30. return null;
  31. }
  32. $className = $matches[1];
  33. $methodName = $matches[2];
  34. $message = sprintf('Attempted to call an undefined method named "%s" of class "%s".', $methodName, $className);
  35. if (!class_exists($className) || null === $methods = get_class_methods($className)) {
  36. // failed to get the class or its methods on which an unknown method was called (for example on an anonymous class)
  37. return new UndefinedMethodException($message, $exception);
  38. }
  39. $candidates = [];
  40. foreach ($methods as $definedMethodName) {
  41. $lev = levenshtein($methodName, $definedMethodName);
  42. if ($lev <= \strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) {
  43. $candidates[] = $definedMethodName;
  44. }
  45. }
  46. if ($candidates) {
  47. sort($candidates);
  48. $last = array_pop($candidates).'"?';
  49. if ($candidates) {
  50. $candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last;
  51. } else {
  52. $candidates = '"'.$last;
  53. }
  54. $message .= "\nDid you mean to call ".$candidates;
  55. }
  56. return new UndefinedMethodException($message, $exception);
  57. }
  58. }