forked from palantirnet/drupal-rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEntityViewRector.php
94 lines (76 loc) · 2.41 KB
/
EntityViewRector.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
88
89
90
91
92
93
94
<?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;
/**
* Replaced deprecated entity_view() calls.
*
* See https://www.drupal.org/node/3033656 for change record.
*
* What is covered:
* - Static replacement
* - The reset parameter is excluded.
*
* Improvement opportunities
* - Include support for cache rest parameter.
*/
final class EntityViewRector extends AbstractRector
{
/**
* {@inheritdoc}
*/
public function getNodeTypes(): array
{
return [
Node\Expr\FuncCall::class,
];
}
/**
* {@inheritdoc}
*/
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Fixes deprecated entity_view() use', [
new CodeSample(
<<<'CODE_BEFORE'
$rendered = entity_view($entity, 'default');
CODE_BEFORE
,
<<<'CODE_AFTER'
$rendered = \Drupal::entityTypeManager()->getViewBuilder($entity
->getEntityTypeId())->view($entity, 'default');
CODE_AFTER
),
]);
}
/**
* {@inheritdoc}
*/
public function refactor(Node $node): ?Node
{
assert($node instanceof Node\Expr\FuncCall);
if ($this->getName($node->name) !== 'entity_view') {
return null;
}
$name = new Node\Name\FullyQualified('Drupal');
$entityTypManager = new Node\Identifier('entityTypeManager');
$var = new Node\Expr\StaticCall($name, $entityTypManager);
$getViewBuilder_method_name = new Node\Identifier('getViewBuilder');
$entity_reference = $node->args[0]->value;
$getEntityTypeId_method_name = new Node\Identifier('getEntityTypeId');
$entityRef_type_id = new Node\Expr\MethodCall($entity_reference, $getEntityTypeId_method_name);
$view_builder = new Node\Expr\MethodCall($var, $getViewBuilder_method_name, [new Node\Arg($entityRef_type_id)]);
$view_method_name = new Node\Identifier('view');
$view_args = [
$node->args[0],
$node->args[1],
];
if (isset($node->args[2])) {
$view_args[] = $node->args[2];
}
return new Node\Expr\MethodCall($view_builder, $view_method_name, $view_args);
}
}