-
Notifications
You must be signed in to change notification settings - Fork 67
/
ModelMethodHandler.php
87 lines (73 loc) · 2.81 KB
/
ModelMethodHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
declare(strict_types=1);
namespace Psalm\LaravelPlugin\Handlers\Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Class_;
use Psalm\FileManipulation;
use Psalm\Internal\Analyzer\StatementsAnalyzer;
use Psalm\Internal\MethodIdentifier;
use Psalm\LaravelPlugin\Util\ProxyMethodReturnTypeProvider;
use Psalm\Plugin\EventHandler\AfterClassLikeVisitInterface;
use Psalm\Plugin\EventHandler\Event\AfterClassLikeVisitEvent;
use Psalm\Plugin\EventHandler\Event\MethodReturnTypeProviderEvent;
use Psalm\Plugin\EventHandler\MethodReturnTypeProviderInterface;
use Psalm\Type;
use Psalm\Type\Union;
use function strtolower;
final class ModelMethodHandler implements MethodReturnTypeProviderInterface, AfterClassLikeVisitInterface
{
/**
* @return array<string>
*/
public static function getClassLikeNames(): array
{
return [Model::class];
}
public static function getMethodReturnType(MethodReturnTypeProviderEvent $event): ?Type\Union
{
$source = $event->getSource();
if (!$source instanceof StatementsAnalyzer) {
return null;
}
// proxy to builder object
if ($event->getMethodNameLowercase() === '__callstatic') {
$called_fq_classlike_name = $event->getCalledFqClasslikeName();
$called_method_name_lowercase = $event->getCalledMethodNameLowercase();
if (!$called_fq_classlike_name || !$called_method_name_lowercase) {
return null;
}
$methodId = new MethodIdentifier($called_fq_classlike_name, $called_method_name_lowercase);
$fake_method_call = new MethodCall(
new Variable('builder'),
$methodId->method_name,
$event->getCallArgs()
);
$fakeProxy = new Type\Atomic\TGenericObject(Builder::class, [
new Union([
new Type\Atomic\TNamedObject($called_fq_classlike_name),
]),
]);
return ProxyMethodReturnTypeProvider::executeFakeCall($source, $fake_method_call, $event->getContext(), $fakeProxy);
}
return null;
}
/** @inheritDoc */
public static function afterClassLikeVisit(AfterClassLikeVisitEvent $event): void
{
$storage = $event->getStorage();
if (
$event->getStmt() instanceof Class_
&& !$storage->abstract
&& isset($storage->parent_classes[strtolower(Model::class)])
) {
unset(
$storage->pseudo_static_methods['newmodelquery'],
$storage->pseudo_static_methods['newquery'],
$storage->pseudo_static_methods['query']
);
}
}
}