getSolutionDescription()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Facade\Ignition\SolutionProviders;
4
5
use BadMethodCallException;
6
use Facade\IgnitionContracts\BaseSolution;
7
use Facade\IgnitionContracts\HasSolutionsForThrowable;
8
use Illuminate\Support\Collection;
9
use ReflectionClass;
10
use ReflectionMethod;
11
use Throwable;
12
13
class BadMethodCallSolutionProvider implements HasSolutionsForThrowable
14
{
15
    protected const REGEX = '/([a-zA-Z\\\\]+)::([a-zA-Z]+)/m';
16
17
    public function canSolve(Throwable $throwable): bool
18
    {
19
        if (! $throwable instanceof BadMethodCallException) {
20
            return false;
21
        }
22
23
        if (is_null($this->getClassAndMethodFromExceptionMessage($throwable->getMessage()))) {
24
            return false;
25
        }
26
27
        return true;
28
    }
29
30
    public function getSolutions(Throwable $throwable): array
31
    {
32
        return [
33
            BaseSolution::create('Bad Method Call')
34
            ->setSolutionDescription($this->getSolutionDescription($throwable)),
35
        ];
36
    }
37
38
    public function getSolutionDescription(Throwable $throwable): string
39
    {
40
        if (! $this->canSolve($throwable)) {
41
            return '';
42
        }
43
44
        extract($this->getClassAndMethodFromExceptionMessage($throwable->getMessage()), EXTR_OVERWRITE);
0 ignored issues
show
Bug introduced by
$this->getClassAndMethod...hrowable->getMessage()) cannot be passed to extract() as the parameter $var_array expects a reference.
Loading history...
45
46
        $possibleMethod = $this->findPossibleMethod($class, $method);
47
48
        return "Did you mean {$class}::{$possibleMethod->name}() ?";
49
    }
50
51
    protected function getClassAndMethodFromExceptionMessage(string $message): ?array
52
    {
53
        if (! preg_match(self::REGEX, $message, $matches)) {
54
            return null;
55
        }
56
57
        return [
58
            'class' => $matches[1],
59
            'method' => $matches[2],
60
        ];
61
    }
62
63
    protected function findPossibleMethod(string $class, string $invalidMethodName)
64
    {
65
        return $this->getAvailableMethods($class)
66
            ->sortByDesc(function (ReflectionMethod $method) use ($invalidMethodName) {
67
                similar_text($invalidMethodName, $method->name, $percentage);
68
69
                return $percentage;
70
            })->first();
71
    }
72
73
    protected function getAvailableMethods($class): Collection
74
    {
75
        $class = new ReflectionClass($class);
76
77
        return Collection::make($class->getMethods());
78
    }
79
}
80