-
-
Notifications
You must be signed in to change notification settings - Fork 680
/
SimplifyRegexPatternRector.php
85 lines (83 loc) · 2.49 KB
/
SimplifyRegexPatternRector.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
<?php
declare (strict_types=1);
namespace Rector\CodeQuality\Rector\FuncCall;
use RectorPrefix202409\Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Scalar\String_;
use Rector\NodeNameResolver\Regex\RegexPatternDetector;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\CodeQuality\Rector\FuncCall\SimplifyRegexPatternRector\SimplifyRegexPatternRectorTest
*/
final class SimplifyRegexPatternRector extends AbstractRector
{
/**
* @readonly
* @var \Rector\NodeNameResolver\Regex\RegexPatternDetector
*/
private $regexPatternDetector;
/**
* @var array<string, string>
*/
private const COMPLEX_PATTERN_TO_SIMPLE = ['[0-9]' => '\\d', '[a-zA-Z0-9_]' => '\\w', '[A-Za-z0-9_]' => '\\w', '[0-9a-zA-Z_]' => '\\w', '[0-9A-Za-z_]' => '\\w', '[\\r\\n\\t\\f\\v ]' => '\\s'];
public function __construct(RegexPatternDetector $regexPatternDetector)
{
$this->regexPatternDetector = $regexPatternDetector;
}
public function getRuleDefinition() : RuleDefinition
{
return new RuleDefinition('Simplify regex pattern to known ranges', [new CodeSample(<<<'CODE_SAMPLE'
class SomeClass
{
public function run($value)
{
preg_match('#[a-zA-Z0-9+]#', $value);
}
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
class SomeClass
{
public function run($value)
{
preg_match('#[\w\d+]#', $value);
}
}
CODE_SAMPLE
)]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [String_::class];
}
/**
* @param String_ $node
*/
public function refactor(Node $node) : ?Node
{
if (!$this->regexPatternDetector->isRegexPattern($node->value)) {
return null;
}
foreach (self::COMPLEX_PATTERN_TO_SIMPLE as $complexPattern => $simple) {
$originalValue = $node->value;
$simplifiedValue = Strings::replace($node->value, '#' . \preg_quote($complexPattern, '#') . '#', $simple);
if ($originalValue === $simplifiedValue) {
continue;
}
if (\strpos($originalValue, '[^' . $complexPattern) !== \false) {
continue;
}
if ($complexPattern === $node->value) {
continue;
}
$node->value = $simplifiedValue;
return $node;
}
return null;
}
}