forked from palantirnet/drupal-rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDrupalURLRector.php
83 lines (71 loc) · 2.2 KB
/
DrupalURLRector.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
<?php
declare(strict_types=1);
namespace DrupalRector\Drupal8\Rector\Deprecation;
use PhpParser\Node;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* Replaces deprecated \Drupal::url() calls.
*
* There is no referenced change record for this. This may be related, https://www.drupal.org/node/2046643.
*
* What is covered:
* - Static replacement
*
* Improvement opportunities
* - Dependency injection
*/
final class DrupalURLRector extends AbstractRector
{
/**
* {@inheritdoc}
*/
public function getNodeTypes(): array
{
return [
Node\Expr\StaticCall::class,
];
}
/**
* {@inheritdoc}
*/
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Fixes deprecated \Drupal::url() calls', [
new CodeSample(
<<<'CODE_BEFORE'
\Drupal::url('user.login');
CODE_BEFORE
,
<<<'CODE_AFTER'
\Drupal\Core\Url::fromRoute('user.login')->toString();
CODE_AFTER
),
]);
}
/**
* {@inheritdoc}
*/
public function refactor(Node $node): ?Node
{
/** @var Node\Expr\StaticCall $node */
if ($this->getName($node->name) === 'url' && $this->getName($node->class) === 'Drupal') {
$toString_argument = null;
$fromRoute_arguments = $node->args;
// If we are the optional fourth argument, we need to chain a `toString($collect_bubbleable_metadata)`.
if (count($fromRoute_arguments) === 4) {
$toString_argument = $fromRoute_arguments[3];
unset($fromRoute_arguments[3]);
}
$new_node = new Node\Expr\StaticCall(new Node\Name\FullyQualified('Drupal\Core\Url'), 'fromRoute', $fromRoute_arguments);
if (is_null($toString_argument)) {
$new_node = new Node\Expr\MethodCall($new_node, 'toString');
} else {
$new_node = new Node\Expr\MethodCall($new_node, 'toString', [$toString_argument]);
}
return $new_node;
}
return null;
}
}