-
-
Notifications
You must be signed in to change notification settings - Fork 671
/
BetterStandardPrinter.php
606 lines (514 loc) · 17.1 KB
/
BetterStandardPrinter.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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
<?php
declare(strict_types=1);
namespace Rector\Core\PhpParser\Printer;
use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\Yield_;
use PhpParser\Node\Name;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Scalar\DNumber;
use PhpParser\Node\Scalar\EncapsedStringPart;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Declare_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Nop;
use PhpParser\Node\Stmt\TraitUse;
use PhpParser\Node\Stmt\Use_;
use PhpParser\PrettyPrinter\Standard;
use Rector\Core\PhpParser\Node\CustomNode\FileNode;
use Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\NodeTypeResolver\PhpDoc\NodeAnalyzer\DocBlockManipulator;
use Symplify\SmartFileSystem\SmartFileInfo;
/**
* @see \Rector\Core\Tests\PhpParser\Printer\BetterStandardPrinterTest
*/
final class BetterStandardPrinter extends Standard
{
/**
* @var string
* @see https://regex101.com/r/jUFizd/1
*/
private const NEWLINE_END_REGEX = "#\n$#";
/**
* @var string
* @see https://regex101.com/r/w5E8Rh/1
*/
private const FOUR_SPACE_START_REGEX = '#^ {4}#m';
/**
* @var string
* @see https://regex101.com/r/F5x783/1
*/
private const USE_REGEX = '#( use)\(#';
/**
* @var string
* @see https://regex101.com/r/DrsMY4/1
*/
private const QUOTED_SLASH_REGEX = "#'|\\\\(?=[\\\\']|$)#";
/**
* Remove extra spaces before new Nop_ nodes
* @see https://regex101.com/r/iSvroO/1
* @var string
*/
private const EXTRA_SPACE_BEFORE_NOP_REGEX = '#^[ \t]+$#m';
/**
* @see https://regex101.com/r/qZiqGo/4
* @var string
*/
private const REPLACE_COLON_WITH_SPACE_REGEX = '#(function .*?\(.*?\)) : #';
/**
* Use space by default
* @var string
*/
private $tabOrSpaceIndentCharacter = ' ';
/**
* @var DocBlockManipulator
*/
private $docBlockManipulator;
/**
* @var CommentRemover
*/
private $commentRemover;
/**
* @var ContentPatcher
*/
private $contentPatcher;
/**
* @param mixed[] $options
*/
public function __construct(CommentRemover $commentRemover, ContentPatcher $contentPatcher, array $options = [])
{
parent::__construct($options);
// print return type double colon right after the bracket "function(): string"
$this->initializeInsertionMap();
$this->insertionMap['Stmt_ClassMethod->returnType'] = [')', false, ': ', null];
$this->insertionMap['Stmt_Function->returnType'] = [')', false, ': ', null];
$this->insertionMap['Expr_Closure->returnType'] = [')', false, ': ', null];
$this->commentRemover = $commentRemover;
$this->contentPatcher = $contentPatcher;
}
/**
* @required
*/
public function autowireBetterStandardPrinter(DocBlockManipulator $docBlockManipulator): void
{
$this->docBlockManipulator = $docBlockManipulator;
}
/**
* @param Node[] $stmts
* @param Node[] $origStmts
* @param mixed[] $origTokens
*/
public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens): string
{
$newStmts = $this->resolveNewStmts($stmts);
// detect per print
$this->detectTabOrSpaceIndentCharacter($newStmts);
$content = parent::printFormatPreserving($newStmts, $origStmts, $origTokens);
$content = $this->contentPatcher->cleanUpDuplicateContent($content);
$contentOriginal = $this->print($origStmts);
$content = $this->contentPatcher->rollbackValidAnnotation(
$contentOriginal,
$content,
ContentPatcher::VALID_ANNOTATION_STRING_REGEX,
ContentPatcher::INVALID_ANNOTATION_STRING_REGEX
);
$content = $this->contentPatcher->rollbackValidAnnotation(
$contentOriginal,
$content,
ContentPatcher::VALID_ANNOTATION_ROUTE_REGEX,
ContentPatcher::INVALID_ANNOTATION_ROUTE_REGEX
);
$content = $this->contentPatcher->rollbackValidAnnotation(
$contentOriginal,
$content,
ContentPatcher::VALID_ANNOTATION_COMMENT_REGEX,
ContentPatcher::INVALID_ANNOTATION_COMMENT_REGEX
);
$content = $this->contentPatcher->rollbackValidAnnotation(
$contentOriginal,
$content,
ContentPatcher::VALID_ANNOTATION_CONSTRAINT_REGEX,
ContentPatcher::INVALID_ANNOTATION_CONSTRAINT_REGEX
);
$content = $this->contentPatcher->rollbackValidAnnotation(
$contentOriginal,
$content,
ContentPatcher::VALID_ANNOTATION_ROUTE_OPTION_REGEX,
ContentPatcher::INVALID_ANNOTATION_ROUTE_OPTION_REGEX
);
$content = $this->contentPatcher->rollbackValidAnnotation(
$contentOriginal,
$content,
ContentPatcher::VALID_ANNOTATION_ROUTE_LOCALIZATION_REGEX,
ContentPatcher::INVALID_ANNOTATION_ROUTE_LOCALIZATION_REGEX
);
$content = $this->contentPatcher->rollbackValidAnnotation(
$contentOriginal,
$content,
ContentPatcher::VALID_ANNOTATION_VAR_RETURN_EXPLICIT_FORMAT_REGEX,
ContentPatcher::INVALID_ANNOTATION_VAR_RETURN_EXPLICIT_FORMAT_REGEX
);
// add new line in case of added stmts
if (count($stmts) !== count($origStmts) && ! (bool) Strings::match($content, self::NEWLINE_END_REGEX)) {
$content .= $this->nl;
}
return $content;
}
/**
* @param Node|Node[]|null $node
*/
public function printWithoutComments($node): string
{
$printerNode = $this->print($node);
$nodeWithoutComments = $this->commentRemover->remove($printerNode);
return trim($nodeWithoutComments);
}
/**
* @param Node|Node[]|null $node
*/
public function print($node): string
{
if ($node === null) {
$node = [];
}
if (! is_array($node)) {
$node = [$node];
}
return $this->prettyPrint($node);
}
/**
* Removes all comments from both nodes
*
* @param Node|Node[]|null $firstNode
* @param Node|Node[]|null $secondNode
*/
public function areNodesEqual($firstNode, $secondNode): bool
{
return $this->printWithoutComments($firstNode) === $this->printWithoutComments($secondNode);
}
/**
* @param Node[] $stmts Array of statements
*/
public function prettyPrintFile(array $stmts): string
{
// to keep indexes from 0
$stmts = array_values($stmts);
return parent::prettyPrintFile($stmts) . PHP_EOL;
}
public function pFileWithoutNamespace(FileWithoutNamespace $fileWithoutNamespace): string
{
$content = self::pStmts((array) $fileWithoutNamespace->stmts, false);
return ltrim($content);
}
public function pFileNode(FileNode $fileNode): string
{
return self::pStmts((array) $fileNode->stmts);
}
/**
* @param Node[] $availableNodes
*/
public function isNodeEqual(Node $singleNode, array $availableNodes): bool
{
// remove comments, only content is relevant
$singleNode = clone $singleNode;
$singleNode->setAttribute(AttributeKey::COMMENTS, null);
foreach ($availableNodes as $availableNode) {
// remove comments, only content is relevant
$availableNode = clone $availableNode;
$availableNode->setAttribute(AttributeKey::COMMENTS, null);
if ($this->areNodesEqual($singleNode, $availableNode)) {
return true;
}
}
return false;
}
/**
* This allows to use both spaces and tabs vs. original space-only
*/
protected function setIndentLevel(int $level): void
{
$level = max($level, 0);
$this->indentLevel = $level;
$this->nl = "\n" . str_repeat($this->tabOrSpaceIndentCharacter, $level);
}
/**
* This allows to use both spaces and tabs vs. original space-only
*/
protected function indent(): void
{
$multiplier = $this->tabOrSpaceIndentCharacter === ' ' ? 4 : 1;
$this->indentLevel += $multiplier;
$this->nl .= str_repeat($this->tabOrSpaceIndentCharacter, $multiplier);
}
/**
* This allows to use both spaces and tabs vs. original space-only
*/
protected function outdent(): void
{
if ($this->tabOrSpaceIndentCharacter === ' ') {
// - 4 spaces
assert($this->indentLevel >= 4);
$this->indentLevel -= 4;
} else {
// - 1 tab
assert($this->indentLevel >= 1);
--$this->indentLevel;
}
$this->nl = "\n" . str_repeat($this->tabOrSpaceIndentCharacter, $this->indentLevel);
}
/**
* @param mixed[] $nodes
* @param mixed[] $origNodes
* @param int|null $fixup
*/
protected function pArray(
array $nodes,
array $origNodes,
int &$pos,
int $indentAdjustment,
string $parentNodeType,
string $subNodeName,
$fixup
): ?string {
// reindex positions for printer
$nodes = array_values($nodes);
$this->moveCommentsFromAttributeObjectToCommentsAttribute($nodes);
$content = parent::pArray($nodes, $origNodes, $pos, $indentAdjustment, $parentNodeType, $subNodeName, $fixup);
if ($content === null) {
return $content;
}
if (! $this->containsNop($nodes)) {
return $content;
}
return Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX, '');
}
/**
* Do not preslash all slashes (parent behavior), but only those:
*
* - followed by "\"
* - by "'"
* - or the end of the string
*
* Prevents `Vendor\Class` => `Vendor\\Class`.
*/
protected function pSingleQuotedString(string $string): string
{
return "'" . Strings::replace($string, self::QUOTED_SLASH_REGEX, '\\\\$0') . "'";
}
/**
* Emulates 1_000 in PHP 7.3- version
*/
protected function pScalar_DNumber(DNumber $dNumber): string
{
if (is_string($dNumber->value)) {
return $dNumber->value;
}
return parent::pScalar_DNumber($dNumber);
}
/**
* Add space:
* "use("
* ↓
* "use ("
*/
protected function pExpr_Closure(Closure $closure): string
{
$closureContent = parent::pExpr_Closure($closure);
return Strings::replace($closureContent, self::USE_REGEX, '$1 (');
}
/**
* Do not add "()" on Expressions
* @see https://github.com/rectorphp/rector/pull/401#discussion_r181487199
*/
protected function pExpr_Yield(Yield_ $yield): string
{
if ($yield->value === null) {
return 'yield';
}
$parentNode = $yield->getAttribute(AttributeKey::PARENT_NODE);
$shouldAddBrackets = $parentNode instanceof Expression;
return sprintf(
'%syield %s%s%s',
$shouldAddBrackets ? '(' : '',
$yield->key !== null ? $this->p($yield->key) . ' => ' : '',
$this->p($yield->value),
$shouldAddBrackets ? ')' : ''
);
}
/**
* Print arrays in short [] by default,
* to prevent manual explicit array shortening.
*/
protected function pExpr_Array(Array_ $array): string
{
if (! $array->hasAttribute(AttributeKey::KIND)) {
$array->setAttribute(AttributeKey::KIND, Array_::KIND_SHORT);
}
return parent::pExpr_Array($array);
}
/**
* Fixes escaping of regular patterns
*/
protected function pScalar_String(String_ $string): string
{
$isRegularPattern = $string->getAttribute(AttributeKey::IS_REGULAR_PATTERN);
if ($isRegularPattern) {
$kind = $string->getAttribute(AttributeKey::KIND, String_::KIND_SINGLE_QUOTED);
if ($kind === String_::KIND_DOUBLE_QUOTED) {
return $this->wrapValueWith($string, '"');
}
if ($kind === String_::KIND_SINGLE_QUOTED) {
return $this->wrapValueWith($string, "'");
}
}
return parent::pScalar_String($string);
}
/**
* @param Node[] $nodes
*/
protected function pStmts(array $nodes, bool $indent = true): string
{
$this->moveCommentsFromAttributeObjectToCommentsAttribute($nodes);
return parent::pStmts($nodes, $indent);
}
/**
* "...$params) : ReturnType"
* ↓
* "...$params): ReturnType"
*/
protected function pStmt_ClassMethod(ClassMethod $classMethod): string
{
$content = parent::pStmt_ClassMethod($classMethod);
// this approach is chosen, to keep changes in parent pStmt_ClassMethod() updated
return Strings::replace($content, self::REPLACE_COLON_WITH_SPACE_REGEX, '$1: ');
}
/**
* Clean class and trait from empty "use x;" for traits causing invalid code
*/
protected function pStmt_Class(Class_ $class): string
{
$shouldReindex = false;
foreach ($class->stmts as $key => $stmt) {
// remove empty ones
if ($stmt instanceof TraitUse && $stmt->traits === []) {
unset($class->stmts[$key]);
$shouldReindex = true;
}
}
if ($shouldReindex) {
$class->stmts = array_values($class->stmts);
}
return parent::pStmt_Class($class);
}
/**
* It remove all spaces extra to parent
*/
protected function pStmt_Declare(Declare_ $declare): string
{
$declareString = parent::pStmt_Declare($declare);
return Strings::replace($declareString, '#\s+#', '');
}
/**
* Remove extra \\ from FQN use imports, for easier use in the code
*/
protected function pStmt_Use(Use_ $use): string
{
if ($use->type === Use_::TYPE_NORMAL) {
foreach ($use->uses as $useUse) {
if ($useUse->name instanceof FullyQualified) {
$useUse->name = new Name($useUse->name);
}
}
}
return parent::pStmt_Use($use);
}
protected function pScalar_EncapsedStringPart(EncapsedStringPart $encapsedStringPart): string
{
// parent throws exception, but we need to compare string
return '`' . $encapsedStringPart->value . '`';
}
/**
* @param Node[] $stmts
* @return Node[]|mixed[]
*/
private function resolveNewStmts(array $stmts): array
{
if (count($stmts) === 1) {
$onlyStmt = $stmts[0];
if ($onlyStmt instanceof FileWithoutNamespace) {
return $onlyStmt->stmts;
}
}
return $stmts;
}
/**
* Solves https://github.com/rectorphp/rector/issues/1964
*
* Some files have spaces, some have tabs. Keep the original indent if possible.
*
* @param Stmt[] $stmts
*/
private function detectTabOrSpaceIndentCharacter(array $stmts): void
{
// use space by default
$this->tabOrSpaceIndentCharacter = ' ';
foreach ($stmts as $stmt) {
if (! $stmt instanceof Node) {
continue;
}
/** @var SmartFileInfo|null $fileInfo */
$fileInfo = $stmt->getAttribute(AttributeKey::FILE_INFO);
if ($fileInfo === null) {
continue;
}
$whitespaces = count(Strings::matchAll($fileInfo->getContents(), self::FOUR_SPACE_START_REGEX));
$tabs = count(Strings::matchAll($fileInfo->getContents(), '#^\t#m'));
// tab vs space
$this->tabOrSpaceIndentCharacter = ($whitespaces <=> $tabs) >= 0 ? ' ' : "\t";
}
}
/**
* @param Node[] $nodes
*/
private function moveCommentsFromAttributeObjectToCommentsAttribute(array $nodes): void
{
// move phpdoc from node to "comment" attribute
foreach ($nodes as $node) {
if (! $node instanceof Node) {
continue;
}
$this->docBlockManipulator->updateNodeWithPhpDocInfo($node);
}
}
/**
* @param Node[] $nodes
*/
private function containsNop(array $nodes): bool
{
foreach ($nodes as $node) {
if ($node instanceof Nop) {
return true;
}
}
return false;
}
private function wrapValueWith(String_ $string, string $wrap): string
{
return $wrap . $string->value . $wrap;
}
protected function pCommaSeparated(array $nodes): string
{
$result = parent::pCommaSeparated($nodes);
$last = end($nodes);
if ($last->getAttribute('trailing_comma') === false) {
$result = rtrim($result, ',');
}
return $result;
}
}