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