Brak opisu

UndefinedMethodErrorEnhancer.php 2.1KB

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