-
-
Notifications
You must be signed in to change notification settings - Fork 440
Expand file tree
/
Copy pathLaravelModelGuard.php
More file actions
79 lines (65 loc) · 2.22 KB
/
LaravelModelGuard.php
File metadata and controls
79 lines (65 loc) · 2.22 KB
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
<?php
declare(strict_types=1);
namespace Rector\Privatization\Guard;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\ObjectType;
use Rector\Enum\LaravelClassName;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\NodeTypeResolver;
use Rector\Php80\NodeAnalyzer\PhpAttributeAnalyzer;
use Rector\Util\StringUtils;
/**
* Guards against privatizing Laravel model attributes and scopes
*/
final readonly class LaravelModelGuard
{
/**
* @var string
* @see https://regex101.com/r/Dx0WN5/2
*/
private const LARAVEL_MODEL_ATTRIBUTE_REGEX = '#^[gs]et.+Attribute$#';
/**
* @var string
* @see https://regex101.com/r/hxOGeN/2
*/
private const LARAVEL_MODEL_SCOPE_REGEX = '#^scope.+$#';
public function __construct(
private PhpAttributeAnalyzer $phpAttributeAnalyzer,
private NodeNameResolver $nodeNameResolver,
private NodeTypeResolver $nodeTypeResolver,
) {
}
public function isProtectedMethod(ClassReflection $classReflection, ClassMethod $classMethod): bool
{
if (! $classReflection->is(LaravelClassName::MODEL)) {
return false;
}
$name = (string) $this->nodeNameResolver->getName($classMethod->name);
if ($this->isAttributeMethod($name, $classMethod)) {
return true;
}
return $this->isScopeMethod($name, $classMethod);
}
private function isAttributeMethod(string $name, ClassMethod $classMethod): bool
{
if (StringUtils::isMatch($name, self::LARAVEL_MODEL_ATTRIBUTE_REGEX)) {
return true;
}
if (! $classMethod->returnType instanceof Node) {
return false;
}
return $this->nodeTypeResolver->isObjectType(
$classMethod->returnType,
new ObjectType(LaravelClassName::CAST_ATTRIBUTE)
);
}
private function isScopeMethod(string $name, ClassMethod $classMethod): bool
{
if (StringUtils::isMatch($name, self::LARAVEL_MODEL_SCOPE_REGEX)) {
return true;
}
return $this->phpAttributeAnalyzer->hasPhpAttribute($classMethod, LaravelClassName::ATTRIBUTES_SCOPE);
}
}