-
-
Notifications
You must be signed in to change notification settings - Fork 394
/
ModelRuleHelper.php
63 lines (50 loc) · 1.82 KB
/
ModelRuleHelper.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
<?php
declare(strict_types=1);
namespace NunoMaduro\Larastan\Rules;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\Generic\GenericObjectType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeWithClassName;
final class ModelRuleHelper
{
public function findModelReflectionFromType(Type $type): ?ClassReflection
{
if (! (new ObjectType(Builder::class))->isSuperTypeOf($type)->yes() &&
! (new ObjectType(EloquentBuilder::class))->isSuperTypeOf($type)->yes() &&
! (new ObjectType(Relation::class))->isSuperTypeOf($type)->yes() &&
! (new ObjectType(Model::class))->isSuperTypeOf($type)->yes()
) {
return null;
}
// We expect it to be generic builder or relation class with model type inside
if ((! $type instanceof GenericObjectType) && (new ObjectType(Model::class))->isSuperTypeOf($type)->no()) {
return null;
}
if ($type instanceof GenericObjectType) {
$modelType = $type->getTypes()[0];
} else {
$modelType = $type;
}
$modelType = TypeCombinator::removeNull($modelType);
if (! $modelType instanceof TypeWithClassName) {
return null;
}
if ($modelType->getClassName() === Model::class) {
return null;
}
$modelReflection = $modelType->getClassReflection();
if ($modelReflection === null) {
return null;
}
if ($modelReflection->isAbstract()) {
return null;
}
return $modelReflection;
}
}