forked from palantirnet/drupal-rector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHookConvertRector.php
More file actions
399 lines (358 loc) · 15.1 KB
/
HookConvertRector.php
File metadata and controls
399 lines (358 loc) · 15.1 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
<?php
declare(strict_types=1);
namespace DrupalRector\Rector\Convert;
use Composer\InstalledVersions;
use PhpParser\Modifiers;
use PhpParser\Node;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use PhpParser\Node\Stmt\Use_;
use PhpParser\NodeFinder;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor;
use PhpParser\NodeVisitorAbstract;
use Rector\Configuration\Option;
use Rector\Doctrine\CodeQuality\Utils\CaseStringHelper;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PhpParser\Printer\BetterStandardPrinter;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
class HookConvertRector extends AbstractRector
{
protected string $inputFilename = '';
/**
* @var Use_[]
*/
protected array $useStmts = [];
protected Class_ $hookClass;
protected string $module = '';
protected string $moduleDir = '';
/**
* The Drupal service call.
*
* For example \Drupal::service(UserHooks::CLASS)
*/
protected Node\Expr\StaticCall $drupalServiceCall;
private string $drupalCorePath = "\0";
/**
* @var BetterStandardPrinter
*/
private BetterStandardPrinter $printer;
private bool $isDryRun;
public function __construct(BetterStandardPrinter $printer)
{
$this->isDryRun = in_array('--'.Option::DRY_RUN, $_SERVER['argv'] ?? []) || in_array('-'.Option::DRY_RUN_SHORT, $_SERVER['argv'] ?? []);
$this->printer = $printer;
try {
if (class_exists(InstalledVersions::class) && ($corePath = InstalledVersions::getInstallPath('drupal/core'))) {
$this->drupalCorePath = realpath($corePath);
}
} catch (\OutOfBoundsException $e) {
}
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Hook conversion script', [
new CodeSample(
<<<'CODE_SAMPLE'
/**
* Implements hook_user_cancel().
*/
function hookconvertrector_user_cancel($edit, UserInterface $account, $method) {
$red = 'red';
$method = ['red', 'green', 'blue'];
$edit = [
'red' => 'red',
'green' => 'green',
'blue' => 'blue',
];
}
CODE_SAMPLE,
<<<'CODE_SAMPLE'
/**
* Hook implementations for hookconvertrector.
*/
class HookconvertrectorHooks
{
/**
* Implements hook_user_cancel().
*/
#[Hook('user_cancel')]
public function userCancel($edit, \UserInterface $account, $method)
{
$red = 'red';
$method = [
'red',
'green',
'blue',
];
$edit = [
'red' => 'red',
'green' => 'green',
'blue' => 'blue',
];
}
}
CODE_SAMPLE
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Function_::class, Use_::class];
}
public function refactor(Node $node): Node|int|null
{
$filePath = method_exists($this, 'getFile')
? $this->getFile()->getFilePath()
: $this->file->getFilePath();
$ext = pathinfo($filePath, \PATHINFO_EXTENSION);
if (!in_array($ext, ['inc', 'module'])) {
return null;
}
if ($filePath !== $this->inputFilename) {
$this->initializeHookClass();
}
if ($node instanceof Use_) {
// For some unknown reason some Use_ statements are passed twice
// to this method.
$newNode = new Use_($node->uses, $node->type, ['comments' => []] + $node->getAttributes());
$this->useStmts[$this->printer->prettyPrint([$newNode])] = $newNode;
}
if ($node instanceof Function_) {
if ($node->name->toString() === 'system_theme') {
return null;
}
// Skip already converted hooks marked with the LegacyHook attribute.
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attribute) {
if ($this->getName($attribute->name) == 'Drupal\\Core\\Hook\\Attribute\\LegacyHook') {
return null;
}
}
}
if ($this->module && ($method = $this->createMethodFromFunction($node))) {
$this->hookClass->stmts[] = $method;
if ($node->name->toString() === 'system_page_attachments') {
$method->stmts = [new Node\Stmt\Expression(new Node\Expr\FuncCall(new Node\Name('_system_page_attachments'), self::convertParamsToArgs($node)))];
$node->name = new Node\Identifier('_system_page_attachments');
return $node;
}
if (defined('\PhpParser\NodeVisitor::REMOVE_NODE')) {
$remove_node = NodeVisitor::REMOVE_NODE;
} else {
/* @phpstan-ignore-next-line */
$remove_node = NodeTraverser::REMOVE_NODE;
}
return str_starts_with($filePath, $this->drupalCorePath) ? $remove_node : $this->getLegacyHookFunction($node);
}
}
return null;
}
protected function initializeHookClass(): void
{
$this->__destruct();
$this->moduleDir = method_exists($this, 'getFile')
? $this->getFile()->getFilePath()
: $this->file->getFilePath();
$this->inputFilename = $this->moduleDir;
// Find the relevant info.yml: it's either in the current directory or
// one of the parents.
while (($this->moduleDir = dirname($this->moduleDir)) && !($info = glob("$this->moduleDir/*.info.yml"))) {
}
if (!empty($info)) {
$infoFile = reset($info);
$this->module = basename($infoFile, '.info.yml');
$filename = pathinfo(method_exists($this, 'getFile') ? $this->getFile()->getFilePath() : $this->file->getFilePath(), \PATHINFO_FILENAME);
$hookClassName = ucfirst(CaseStringHelper::camelCase(str_replace('.', '_', $filename).'_hooks'));
$counter = '';
do {
$candidate = "$hookClassName$counter";
$hookClassFilename = "$this->moduleDir/src/Hook/$candidate.php";
$counter = $counter ? $counter + 1 : 1;
} while (file_exists($hookClassFilename));
$namespace = implode('\\', ['Drupal', $this->module, 'Hook']);
$this->hookClass = new Class_(new Node\Identifier($candidate));
// Using $this->nodeFactory->createStaticCall() results in
// use \Drupal; on top which is not desirable.
$classConst = new Node\Expr\ClassConstFetch(new FullyQualified("$namespace\\$candidate"), 'class');
$this->drupalServiceCall = new Node\Expr\StaticCall(new FullyQualified('Drupal'), 'service', [new Node\Arg($classConst)]);
$this->useStmts = [];
}
}
public function __destruct()
{
if ($this->module && $this->hookClass->stmts) {
$className = $this->hookClass->name->toString();
// Put the file together.
$namespace = "Drupal\\$this->module\\Hook";
$hookClassStmts = [
new Node\Stmt\Namespace_(new Node\Name($namespace)),
...$this->useStmts,
new Use_([
class_exists('PhpParser\Node\UseItem')
? new Node\UseItem(new Node\Name('Drupal\Core\Hook\Attribute\Hook'))
: new Node\Stmt\UseUse(new Node\Name('Drupal\Core\Hook\Attribute\Hook')),
]),
$this->hookClass,
];
$this->hookClass->setDocComment(new \PhpParser\Comment\Doc("/**\n * Hook implementations for $this->module.\n */"));
// Write it out if not a dry run
if ($this->isDryRun === false) {
@mkdir("$this->moduleDir/src");
@mkdir("$this->moduleDir/src/Hook");
file_put_contents("$this->moduleDir/src/Hook/$className.php", $this->printer->prettyPrintFile($hookClassStmts));
if (!str_starts_with($this->moduleDir, $this->drupalCorePath)) {
static::writeServicesYml("$this->moduleDir/$this->module.services.yml", "$namespace\\$className");
}
}
}
$this->module = '';
}
protected function createMethodFromFunction(Function_ $node): ?ClassMethod
{
if ($info = $this->getHookAndModuleName($node)) {
['hook' => $hook, 'module' => $implementsModule] = $info;
$procOnly = [
'hook_info',
'install',
'install_tasks',
'install_tasks_alter',
'module_implements_alter',
'removed_post_updates',
'requirements',
'schema',
'uninstall',
'update_dependencies',
'update_last_removed',
];
if (in_array($hook, $procOnly)) {
return null;
}
// Resolve __FUNCTION__ and unqualify things so TRUE doesn't
// become \TRUE.
$visitor = new class(new String_($node->name->toString())) extends NodeVisitorAbstract {
public function __construct(protected String_ $functionName)
{
}
public function leaveNode(Node $node)
{
if (isset($node->name) && $node->name instanceof FullyQualified) {
$name = new Node\Name($node->name);
if ($name->isUnqualified()) {
$node->name = $name;
return $node;
}
}
if ($node instanceof Node\Expr\Array_) {
$node->setAttribute(AttributeKey::NEWLINED_ARRAY_PRINT, true);
}
return $node instanceof Node\Scalar\MagicConst\Function_ ? $this->functionName : parent::leaveNode($node);
}
};
$traverser = new NodeTraverser();
$traverser->addVisitor($visitor);
$traverser->traverse([$node]);
// Convert the function to a method.
$method = new ClassMethod($this->getMethodName($node), get_object_vars($node), $node->getAttributes());
$method->flags = Modifiers::PUBLIC;
// Assemble the arguments for the #[Hook] attribute.
$arguments = [new Node\Arg(new String_($hook))];
if ($implementsModule !== $this->module) {
$arguments[] = new Node\Arg(new String_($implementsModule), name: new Node\Identifier('module'));
}
$method->attrGroups[] = new Node\AttributeGroup([new Node\Attribute(new Node\Name('Hook'), $arguments)]);
return $method;
}
return null;
}
/**
* Get the hook and module name from a function name and doxygen.
*
* If the doxygen has Implements hook_foo() in it then this method attempts
* to find a matching module name and hook. Function names like
* user_access_test_user_access() are ambiguous: it could be the user module
* implementing the hook_ENTITY_TYPE_access hook for the access_test_user
* entity type or it could be the user_access_test module implementing it for
* the user entity type. The current module name is preferred by the method
* then the shortest possible module name producing a match is returned.
*
* @param Function_ $node
* A function node
*
* @return array<string, string>
* If a match was found then an associative array with keys hook and module
* with corresponding values. Otherwise, the array is empty.
*/
protected function getHookAndModuleName(Function_ $node): array
{
// If the doxygen contains "Implements hook_foo()" then parse the hook
// name. A difficulty here is "Implements hook_form_FORM_ID_alter".
if (preg_match('/^ \* Implements hook_([a-zA-Z0-9_]+)/m', (string) $node->getDocComment()?->getReformattedText(), $matches)) {
// Replace sections that start and end with an uppercase character
// and contain any number of uppercase characters or underscores
// inbetween.
$hookRegex = preg_replace('/([A-Z][A-Z0-9_]*[A-Z0-9])/', '[a-zA-Z0-9_]+', $matches[1]);
$hookRegex = "_(?<hook>$hookRegex)";
$functionName = $node->name->toString();
// And now find the module and the hook.
foreach ([$this->module, '.+?'] as $module) {
if (preg_match("/^(?<module>$module)$hookRegex$/", $functionName, $matches)) {
return $matches;
}
}
}
return [];
}
/**
* @param Function_ $node
* A function declaration for example the entire user_user_role_insert()
* function
*
* @return string
* The function name converted to camelCase for e.g. userRoleInsert. The
* current module name is removed from the beginning.
*/
protected function getMethodName(Function_ $node): string
{
$name = preg_replace("/^{$this->module}_/", '', $node->name->toString());
return CaseStringHelper::camelCase($name);
}
public function getLegacyHookFunction(Function_ $node): Function_
{
$methodCall = new Node\Expr\MethodCall($this->drupalServiceCall, $this->getMethodName($node), self::convertParamsToArgs($node));
$hasReturn = (new NodeFinder())->findFirstInstanceOf([$node], Node\Stmt\Return_::class);
$node->stmts = [$hasReturn ? new Node\Stmt\Return_($methodCall) : new Node\Stmt\Expression($methodCall)];
// Mark this function as a legacy hook.
$node->attrGroups[] = new Node\AttributeGroup([new Node\Attribute(new FullyQualified('Drupal\Core\Hook\Attribute\LegacyHook'))]);
return $node;
}
protected static function writeServicesYml(string $fileName, string $fullyClassifiedClassName): void
{
$services = is_file($fileName) ? file_get_contents($fileName) : '';
$id = "\n $fullyClassifiedClassName:\n";
if (!str_contains($services, $id)) {
if (!str_contains($services, 'services:')) {
$services .= "\nservices:";
}
$services .= "$id class: $fullyClassifiedClassName\n autowire: true\n";
file_put_contents($fileName, $services);
}
}
/**
* @param Function_ $node
*
* @return Node\Arg[]
*/
protected static function convertParamsToArgs(Function_ $node): array
{
return array_map(fn (Node\Param $param) => new Node\Arg($param->var), $node->getParams());
}
}