| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
/*
|
|
|
4 |
* This file is part of the Symfony package.
|
|
|
5 |
*
|
|
|
6 |
* (c) Fabien Potencier <fabien@symfony.com>
|
|
|
7 |
*
|
|
|
8 |
* For the full copyright and license information, please view the LICENSE
|
|
|
9 |
* file that was distributed with this source code.
|
|
|
10 |
*/
|
|
|
11 |
|
|
|
12 |
namespace Symfony\Component\ErrorHandler\ErrorEnhancer;
|
|
|
13 |
|
|
|
14 |
use Symfony\Component\ErrorHandler\Error\FatalError;
|
|
|
15 |
use Symfony\Component\ErrorHandler\Error\UndefinedMethodError;
|
|
|
16 |
|
|
|
17 |
/**
|
|
|
18 |
* @author Grégoire Pineau <lyrixx@lyrixx.info>
|
|
|
19 |
*/
|
|
|
20 |
class UndefinedMethodErrorEnhancer implements ErrorEnhancerInterface
|
|
|
21 |
{
|
|
|
22 |
public function enhance(\Throwable $error): ?\Throwable
|
|
|
23 |
{
|
|
|
24 |
if ($error instanceof FatalError) {
|
|
|
25 |
return null;
|
|
|
26 |
}
|
|
|
27 |
|
|
|
28 |
$message = $error->getMessage();
|
|
|
29 |
preg_match('/^Call to undefined method (.*)::(.*)\(\)$/', $message, $matches);
|
|
|
30 |
if (!$matches) {
|
|
|
31 |
return null;
|
|
|
32 |
}
|
|
|
33 |
|
|
|
34 |
$className = $matches[1];
|
|
|
35 |
$methodName = $matches[2];
|
|
|
36 |
|
|
|
37 |
$message = sprintf('Attempted to call an undefined method named "%s" of class "%s".', $methodName, $className);
|
|
|
38 |
|
|
|
39 |
if ('' === $methodName || !class_exists($className) || null === $methods = get_class_methods($className)) {
|
|
|
40 |
// failed to get the class or its methods on which an unknown method was called (for example on an anonymous class)
|
|
|
41 |
return new UndefinedMethodError($message, $error);
|
|
|
42 |
}
|
|
|
43 |
|
|
|
44 |
$candidates = [];
|
|
|
45 |
foreach ($methods as $definedMethodName) {
|
|
|
46 |
$lev = levenshtein($methodName, $definedMethodName);
|
|
|
47 |
if ($lev <= \strlen($methodName) / 3 || str_contains($definedMethodName, $methodName)) {
|
|
|
48 |
$candidates[] = $definedMethodName;
|
|
|
49 |
}
|
|
|
50 |
}
|
|
|
51 |
|
|
|
52 |
if ($candidates) {
|
|
|
53 |
sort($candidates);
|
|
|
54 |
$last = array_pop($candidates).'"?';
|
|
|
55 |
if ($candidates) {
|
|
|
56 |
$candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last;
|
|
|
57 |
} else {
|
|
|
58 |
$candidates = '"'.$last;
|
|
|
59 |
}
|
|
|
60 |
|
|
|
61 |
$message .= "\nDid you mean to call ".$candidates;
|
|
|
62 |
}
|
|
|
63 |
|
|
|
64 |
return new UndefinedMethodError($message, $error);
|
|
|
65 |
}
|
|
|
66 |
}
|