1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\PhpDocParser\Printer;
4:
5: use LogicException;
6: use PHPStan\PhpDocParser\Ast\Attribute;
7: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprArrayNode;
8: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNode;
9: use PHPStan\PhpDocParser\Ast\Node;
10: use PHPStan\PhpDocParser\Ast\PhpDoc\AssertTagMethodValueNode;
11: use PHPStan\PhpDocParser\Ast\PhpDoc\AssertTagPropertyValueNode;
12: use PHPStan\PhpDocParser\Ast\PhpDoc\AssertTagValueNode;
13: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineAnnotation;
14: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineArgument;
15: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineArray;
16: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineArrayItem;
17: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineTagValueNode;
18: use PHPStan\PhpDocParser\Ast\PhpDoc\ExtendsTagValueNode;
19: use PHPStan\PhpDocParser\Ast\PhpDoc\ImplementsTagValueNode;
20: use PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueNode;
21: use PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueParameterNode;
22: use PHPStan\PhpDocParser\Ast\PhpDoc\MixinTagValueNode;
23: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamClosureThisTagValueNode;
24: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamImmediatelyInvokedCallableTagValueNode;
25: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamLaterInvokedCallableTagValueNode;
26: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamOutTagValueNode;
27: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
28: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode;
29: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
30: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
31: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode;
32: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode;
33: use PHPStan\PhpDocParser\Ast\PhpDoc\PropertyTagValueNode;
34: use PHPStan\PhpDocParser\Ast\PhpDoc\PureUnlessCallableIsImpureTagValueNode;
35: use PHPStan\PhpDocParser\Ast\PhpDoc\RequireExtendsTagValueNode;
36: use PHPStan\PhpDocParser\Ast\PhpDoc\RequireImplementsTagValueNode;
37: use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode;
38: use PHPStan\PhpDocParser\Ast\PhpDoc\SelfOutTagValueNode;
39: use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
40: use PHPStan\PhpDocParser\Ast\PhpDoc\ThrowsTagValueNode;
41: use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode;
42: use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode;
43: use PHPStan\PhpDocParser\Ast\PhpDoc\UsesTagValueNode;
44: use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
45: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
46: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
47: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeUnsealedTypeNode;
48: use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
49: use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
50: use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode;
51: use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode;
52: use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode;
53: use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
54: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
55: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
56: use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
57: use PHPStan\PhpDocParser\Ast\Type\InvalidTypeNode;
58: use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
59: use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode;
60: use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
61: use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode;
62: use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode;
63: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
64: use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
65: use PHPStan\PhpDocParser\Lexer\Lexer;
66: use PHPStan\PhpDocParser\Parser\TokenIterator;
67: use function array_keys;
68: use function array_map;
69: use function count;
70: use function get_class;
71: use function get_object_vars;
72: use function implode;
73: use function in_array;
74: use function is_array;
75: use function preg_match_all;
76: use function sprintf;
77: use function strlen;
78: use function strpos;
79: use function trim;
80: use const PREG_SET_ORDER;
81:
82: /**
83: * Inspired by https://github.com/nikic/PHP-Parser/tree/36a6dcd04e7b0285e8f0868f44bd4927802f7df1
84: *
85: * Copyright (c) 2011, Nikita Popov
86: * All rights reserved.
87: */
88: final class Printer
89: {
90:
91: /** @var Differ<Node> */
92: private $differ;
93:
94: /**
95: * Map From "{$class}->{$subNode}" to string that should be inserted
96: * between elements of this list subnode
97: *
98: * @var array<string, string>
99: */
100: private $listInsertionMap = [
101: PhpDocNode::class . '->children' => "\n * ",
102: UnionTypeNode::class . '->types' => '|',
103: IntersectionTypeNode::class . '->types' => '&',
104: ArrayShapeNode::class . '->items' => ', ',
105: ObjectShapeNode::class . '->items' => ', ',
106: CallableTypeNode::class . '->parameters' => ', ',
107: CallableTypeNode::class . '->templateTypes' => ', ',
108: GenericTypeNode::class . '->genericTypes' => ', ',
109: ConstExprArrayNode::class . '->items' => ', ',
110: MethodTagValueNode::class . '->parameters' => ', ',
111: DoctrineArray::class . '->items' => ', ',
112: DoctrineAnnotation::class . '->arguments' => ', ',
113: ];
114:
115: /**
116: * [$find, $extraLeft, $extraRight]
117: *
118: * @var array<string, array{string|null, string, string}>
119: */
120: private $emptyListInsertionMap = [
121: CallableTypeNode::class . '->parameters' => ['(', '', ''],
122: ArrayShapeNode::class . '->items' => ['{', '', ''],
123: ObjectShapeNode::class . '->items' => ['{', '', ''],
124: DoctrineArray::class . '->items' => ['{', '', ''],
125: DoctrineAnnotation::class . '->arguments' => ['(', '', ''],
126: ];
127:
128: /** @var array<string, list<class-string<TypeNode>>> */
129: private $parenthesesMap = [
130: CallableTypeNode::class . '->returnType' => [
131: CallableTypeNode::class,
132: UnionTypeNode::class,
133: IntersectionTypeNode::class,
134: ],
135: ArrayTypeNode::class . '->type' => [
136: CallableTypeNode::class,
137: UnionTypeNode::class,
138: IntersectionTypeNode::class,
139: ConstTypeNode::class,
140: NullableTypeNode::class,
141: ],
142: OffsetAccessTypeNode::class . '->type' => [
143: CallableTypeNode::class,
144: UnionTypeNode::class,
145: IntersectionTypeNode::class,
146: NullableTypeNode::class,
147: ],
148: ];
149:
150: /** @var array<string, list<class-string<TypeNode>>> */
151: private $parenthesesListMap = [
152: IntersectionTypeNode::class . '->types' => [
153: IntersectionTypeNode::class,
154: UnionTypeNode::class,
155: NullableTypeNode::class,
156: ],
157: UnionTypeNode::class . '->types' => [
158: IntersectionTypeNode::class,
159: UnionTypeNode::class,
160: NullableTypeNode::class,
161: ],
162: ];
163:
164: public function printFormatPreserving(PhpDocNode $node, PhpDocNode $originalNode, TokenIterator $originalTokens): string
165: {
166: $this->differ = new Differ(static function ($a, $b) {
167: if ($a instanceof Node && $b instanceof Node) {
168: return $a === $b->getAttribute(Attribute::ORIGINAL_NODE);
169: }
170:
171: return false;
172: });
173:
174: $tokenIndex = 0;
175: $result = $this->printArrayFormatPreserving(
176: $node->children,
177: $originalNode->children,
178: $originalTokens,
179: $tokenIndex,
180: PhpDocNode::class,
181: 'children'
182: );
183: if ($result !== null) {
184: return $result . $originalTokens->getContentBetween($tokenIndex, $originalTokens->getTokenCount());
185: }
186:
187: return $this->print($node);
188: }
189:
190: public function print(Node $node): string
191: {
192: if ($node instanceof PhpDocNode) {
193: return "/**\n *" . implode("\n *", array_map(
194: function (PhpDocChildNode $child): string {
195: $s = $this->print($child);
196: return $s === '' ? '' : ' ' . $s;
197: },
198: $node->children
199: )) . "\n */";
200: }
201: if ($node instanceof PhpDocTextNode) {
202: return $node->text;
203: }
204: if ($node instanceof PhpDocTagNode) {
205: if ($node->value instanceof DoctrineTagValueNode) {
206: return $this->print($node->value);
207: }
208:
209: return trim(sprintf('%s %s', $node->name, $this->print($node->value)));
210: }
211: if ($node instanceof PhpDocTagValueNode) {
212: return $this->printTagValue($node);
213: }
214: if ($node instanceof TypeNode) {
215: return $this->printType($node);
216: }
217: if ($node instanceof ConstExprNode) {
218: return $this->printConstExpr($node);
219: }
220: if ($node instanceof MethodTagValueParameterNode) {
221: $type = $node->type !== null ? $this->print($node->type) . ' ' : '';
222: $isReference = $node->isReference ? '&' : '';
223: $isVariadic = $node->isVariadic ? '...' : '';
224: $default = $node->defaultValue !== null ? ' = ' . $this->print($node->defaultValue) : '';
225: return "{$type}{$isReference}{$isVariadic}{$node->parameterName}{$default}";
226: }
227: if ($node instanceof CallableTypeParameterNode) {
228: $type = $this->print($node->type) . ' ';
229: $isReference = $node->isReference ? '&' : '';
230: $isVariadic = $node->isVariadic ? '...' : '';
231: $isOptional = $node->isOptional ? '=' : '';
232: return trim("{$type}{$isReference}{$isVariadic}{$node->parameterName}") . $isOptional;
233: }
234: if ($node instanceof ArrayShapeUnsealedTypeNode) {
235: if ($node->keyType !== null) {
236: return sprintf('<%s, %s>', $this->printType($node->keyType), $this->printType($node->valueType));
237: }
238: return sprintf('<%s>', $this->printType($node->valueType));
239: }
240: if ($node instanceof DoctrineAnnotation) {
241: return (string) $node;
242: }
243: if ($node instanceof DoctrineArgument) {
244: return (string) $node;
245: }
246: if ($node instanceof DoctrineArray) {
247: return (string) $node;
248: }
249: if ($node instanceof DoctrineArrayItem) {
250: return (string) $node;
251: }
252:
253: throw new LogicException(sprintf('Unknown node type %s', get_class($node)));
254: }
255:
256: private function printTagValue(PhpDocTagValueNode $node): string
257: {
258: // only nodes that contain another node are handled here
259: // the rest falls back on (string) $node
260:
261: if ($node instanceof AssertTagMethodValueNode) {
262: $isNegated = $node->isNegated ? '!' : '';
263: $isEquality = $node->isEquality ? '=' : '';
264: $type = $this->printType($node->type);
265: return trim("{$isNegated}{$isEquality}{$type} {$node->parameter}->{$node->method}() {$node->description}");
266: }
267: if ($node instanceof AssertTagPropertyValueNode) {
268: $isNegated = $node->isNegated ? '!' : '';
269: $isEquality = $node->isEquality ? '=' : '';
270: $type = $this->printType($node->type);
271: return trim("{$isNegated}{$isEquality}{$type} {$node->parameter}->{$node->property} {$node->description}");
272: }
273: if ($node instanceof AssertTagValueNode) {
274: $isNegated = $node->isNegated ? '!' : '';
275: $isEquality = $node->isEquality ? '=' : '';
276: $type = $this->printType($node->type);
277: return trim("{$isNegated}{$isEquality}{$type} {$node->parameter} {$node->description}");
278: }
279: if ($node instanceof ExtendsTagValueNode || $node instanceof ImplementsTagValueNode) {
280: $type = $this->printType($node->type);
281: return trim("{$type} {$node->description}");
282: }
283: if ($node instanceof MethodTagValueNode) {
284: $static = $node->isStatic ? 'static ' : '';
285: $returnType = $node->returnType !== null ? $this->printType($node->returnType) . ' ' : '';
286: $parameters = implode(', ', array_map(function (MethodTagValueParameterNode $parameter): string {
287: return $this->print($parameter);
288: }, $node->parameters));
289: $description = $node->description !== '' ? " {$node->description}" : '';
290: $templateTypes = count($node->templateTypes) > 0 ? '<' . implode(', ', array_map(function (TemplateTagValueNode $templateTag): string {
291: return $this->print($templateTag);
292: }, $node->templateTypes)) . '>' : '';
293: return "{$static}{$returnType}{$node->methodName}{$templateTypes}({$parameters}){$description}";
294: }
295: if ($node instanceof MixinTagValueNode) {
296: $type = $this->printType($node->type);
297: return trim("{$type} {$node->description}");
298: }
299: if ($node instanceof RequireExtendsTagValueNode) {
300: $type = $this->printType($node->type);
301: return trim("{$type} {$node->description}");
302: }
303: if ($node instanceof RequireImplementsTagValueNode) {
304: $type = $this->printType($node->type);
305: return trim("{$type} {$node->description}");
306: }
307: if ($node instanceof ParamOutTagValueNode) {
308: $type = $this->printType($node->type);
309: return trim("{$type} {$node->parameterName} {$node->description}");
310: }
311: if ($node instanceof ParamTagValueNode) {
312: $reference = $node->isReference ? '&' : '';
313: $variadic = $node->isVariadic ? '...' : '';
314: $type = $this->printType($node->type);
315: return trim("{$type} {$reference}{$variadic}{$node->parameterName} {$node->description}");
316: }
317: if ($node instanceof ParamImmediatelyInvokedCallableTagValueNode) {
318: return trim("{$node->parameterName} {$node->description}");
319: }
320: if ($node instanceof ParamLaterInvokedCallableTagValueNode) {
321: return trim("{$node->parameterName} {$node->description}");
322: }
323: if ($node instanceof ParamClosureThisTagValueNode) {
324: return trim("{$node->type} {$node->parameterName} {$node->description}");
325: }
326: if ($node instanceof PureUnlessCallableIsImpureTagValueNode) {
327: return trim("{$node->parameterName} {$node->description}");
328: }
329: if ($node instanceof PropertyTagValueNode) {
330: $type = $this->printType($node->type);
331: return trim("{$type} {$node->propertyName} {$node->description}");
332: }
333: if ($node instanceof ReturnTagValueNode) {
334: $type = $this->printType($node->type);
335: return trim("{$type} {$node->description}");
336: }
337: if ($node instanceof SelfOutTagValueNode) {
338: $type = $this->printType($node->type);
339: return trim($type . ' ' . $node->description);
340: }
341: if ($node instanceof TemplateTagValueNode) {
342: $upperBound = $node->bound !== null ? ' of ' . $this->printType($node->bound) : '';
343: $lowerBound = $node->lowerBound !== null ? ' super ' . $this->printType($node->lowerBound) : '';
344: $default = $node->default !== null ? ' = ' . $this->printType($node->default) : '';
345: return trim("{$node->name}{$upperBound}{$lowerBound}{$default} {$node->description}");
346: }
347: if ($node instanceof ThrowsTagValueNode) {
348: $type = $this->printType($node->type);
349: return trim("{$type} {$node->description}");
350: }
351: if ($node instanceof TypeAliasImportTagValueNode) {
352: return trim(
353: "{$node->importedAlias} from " . $this->printType($node->importedFrom)
354: . ($node->importedAs !== null ? " as {$node->importedAs}" : '')
355: );
356: }
357: if ($node instanceof TypeAliasTagValueNode) {
358: $type = $this->printType($node->type);
359: return trim("{$node->alias} {$type}");
360: }
361: if ($node instanceof UsesTagValueNode) {
362: $type = $this->printType($node->type);
363: return trim("{$type} {$node->description}");
364: }
365: if ($node instanceof VarTagValueNode) {
366: $type = $this->printType($node->type);
367: return trim("{$type} " . trim("{$node->variableName} {$node->description}"));
368: }
369:
370: return (string) $node;
371: }
372:
373: private function printType(TypeNode $node): string
374: {
375: if ($node instanceof ArrayShapeNode) {
376: $items = array_map(function (ArrayShapeItemNode $item): string {
377: return $this->printType($item);
378: }, $node->items);
379:
380: if (! $node->sealed) {
381: $items[] = '...' . ($node->unsealedType === null ? '' : $this->print($node->unsealedType));
382: }
383:
384: return $node->kind . '{' . implode(', ', $items) . '}';
385: }
386: if ($node instanceof ArrayShapeItemNode) {
387: if ($node->keyName !== null) {
388: return sprintf(
389: '%s%s: %s',
390: $this->print($node->keyName),
391: $node->optional ? '?' : '',
392: $this->printType($node->valueType)
393: );
394: }
395:
396: return $this->printType($node->valueType);
397: }
398: if ($node instanceof ArrayTypeNode) {
399: return $this->printOffsetAccessType($node->type) . '[]';
400: }
401: if ($node instanceof CallableTypeNode) {
402: if ($node->returnType instanceof CallableTypeNode || $node->returnType instanceof UnionTypeNode || $node->returnType instanceof IntersectionTypeNode) {
403: $returnType = $this->wrapInParentheses($node->returnType);
404: } else {
405: $returnType = $this->printType($node->returnType);
406: }
407: $template = $node->templateTypes !== []
408: ? '<' . implode(', ', array_map(function (TemplateTagValueNode $templateNode): string {
409: return $this->print($templateNode);
410: }, $node->templateTypes)) . '>'
411: : '';
412: $parameters = implode(', ', array_map(function (CallableTypeParameterNode $parameterNode): string {
413: return $this->print($parameterNode);
414: }, $node->parameters));
415: return "{$node->identifier}{$template}({$parameters}): {$returnType}";
416: }
417: if ($node instanceof ConditionalTypeForParameterNode) {
418: return sprintf(
419: '(%s %s %s ? %s : %s)',
420: $node->parameterName,
421: $node->negated ? 'is not' : 'is',
422: $this->printType($node->targetType),
423: $this->printType($node->if),
424: $this->printType($node->else)
425: );
426: }
427: if ($node instanceof ConditionalTypeNode) {
428: return sprintf(
429: '(%s %s %s ? %s : %s)',
430: $this->printType($node->subjectType),
431: $node->negated ? 'is not' : 'is',
432: $this->printType($node->targetType),
433: $this->printType($node->if),
434: $this->printType($node->else)
435: );
436: }
437: if ($node instanceof ConstTypeNode) {
438: return $this->printConstExpr($node->constExpr);
439: }
440: if ($node instanceof GenericTypeNode) {
441: $genericTypes = [];
442:
443: foreach ($node->genericTypes as $index => $type) {
444: $variance = $node->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT;
445: if ($variance === GenericTypeNode::VARIANCE_INVARIANT) {
446: $genericTypes[] = $this->printType($type);
447: } elseif ($variance === GenericTypeNode::VARIANCE_BIVARIANT) {
448: $genericTypes[] = '*';
449: } else {
450: $genericTypes[] = sprintf('%s %s', $variance, $this->print($type));
451: }
452: }
453:
454: return $node->type . '<' . implode(', ', $genericTypes) . '>';
455: }
456: if ($node instanceof IdentifierTypeNode) {
457: return $node->name;
458: }
459: if ($node instanceof IntersectionTypeNode || $node instanceof UnionTypeNode) {
460: $items = [];
461: foreach ($node->types as $type) {
462: if (
463: $type instanceof IntersectionTypeNode
464: || $type instanceof UnionTypeNode
465: || $type instanceof NullableTypeNode
466: ) {
467: $items[] = $this->wrapInParentheses($type);
468: continue;
469: }
470:
471: $items[] = $this->printType($type);
472: }
473:
474: return implode($node instanceof IntersectionTypeNode ? '&' : '|', $items);
475: }
476: if ($node instanceof InvalidTypeNode) {
477: return (string) $node;
478: }
479: if ($node instanceof NullableTypeNode) {
480: if ($node->type instanceof IntersectionTypeNode || $node->type instanceof UnionTypeNode) {
481: return '?(' . $this->printType($node->type) . ')';
482: }
483:
484: return '?' . $this->printType($node->type);
485: }
486: if ($node instanceof ObjectShapeNode) {
487: $items = array_map(function (ObjectShapeItemNode $item): string {
488: return $this->printType($item);
489: }, $node->items);
490:
491: return 'object{' . implode(', ', $items) . '}';
492: }
493: if ($node instanceof ObjectShapeItemNode) {
494: if ($node->keyName !== null) {
495: return sprintf(
496: '%s%s: %s',
497: $this->print($node->keyName),
498: $node->optional ? '?' : '',
499: $this->printType($node->valueType)
500: );
501: }
502:
503: return $this->printType($node->valueType);
504: }
505: if ($node instanceof OffsetAccessTypeNode) {
506: return $this->printOffsetAccessType($node->type) . '[' . $this->printType($node->offset) . ']';
507: }
508: if ($node instanceof ThisTypeNode) {
509: return (string) $node;
510: }
511:
512: throw new LogicException(sprintf('Unknown node type %s', get_class($node)));
513: }
514:
515: private function wrapInParentheses(TypeNode $node): string
516: {
517: return '(' . $this->printType($node) . ')';
518: }
519:
520: private function printOffsetAccessType(TypeNode $type): string
521: {
522: if (
523: $type instanceof CallableTypeNode
524: || $type instanceof UnionTypeNode
525: || $type instanceof IntersectionTypeNode
526: || $type instanceof NullableTypeNode
527: ) {
528: return $this->wrapInParentheses($type);
529: }
530:
531: return $this->printType($type);
532: }
533:
534: private function printConstExpr(ConstExprNode $node): string
535: {
536: // this is fine - ConstExprNode classes do not contain nodes that need smart printer logic
537: return (string) $node;
538: }
539:
540: /**
541: * @param Node[] $nodes
542: * @param Node[] $originalNodes
543: */
544: private function printArrayFormatPreserving(array $nodes, array $originalNodes, TokenIterator $originalTokens, int &$tokenIndex, string $parentNodeClass, string $subNodeName): ?string
545: {
546: $diff = $this->differ->diffWithReplacements($originalNodes, $nodes);
547: $mapKey = $parentNodeClass . '->' . $subNodeName;
548: $insertStr = $this->listInsertionMap[$mapKey] ?? null;
549: $result = '';
550: $beforeFirstKeepOrReplace = true;
551: $delayedAdd = [];
552:
553: $insertNewline = false;
554: [$isMultiline, $beforeAsteriskIndent, $afterAsteriskIndent] = $this->isMultiline($tokenIndex, $originalNodes, $originalTokens);
555:
556: if ($insertStr === "\n * ") {
557: $insertStr = sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
558: }
559:
560: foreach ($diff as $i => $diffElem) {
561: $diffType = $diffElem->type;
562: $newNode = $diffElem->new;
563: $originalNode = $diffElem->old;
564: if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) {
565: $beforeFirstKeepOrReplace = false;
566: if (!$newNode instanceof Node || !$originalNode instanceof Node) {
567: return null;
568: }
569: $itemStartPos = $originalNode->getAttribute(Attribute::START_INDEX);
570: $itemEndPos = $originalNode->getAttribute(Attribute::END_INDEX);
571: if ($itemStartPos < 0 || $itemEndPos < 0 || $itemStartPos < $tokenIndex) {
572: throw new LogicException();
573: }
574:
575: $result .= $originalTokens->getContentBetween($tokenIndex, $itemStartPos);
576:
577: if (count($delayedAdd) > 0) {
578: foreach ($delayedAdd as $delayedAddNode) {
579: $parenthesesNeeded = isset($this->parenthesesListMap[$mapKey])
580: && in_array(get_class($delayedAddNode), $this->parenthesesListMap[$mapKey], true);
581: if ($parenthesesNeeded) {
582: $result .= '(';
583: }
584: $result .= $this->printNodeFormatPreserving($delayedAddNode, $originalTokens);
585: if ($parenthesesNeeded) {
586: $result .= ')';
587: }
588:
589: if ($insertNewline) {
590: $result .= $insertStr . sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
591: } else {
592: $result .= $insertStr;
593: }
594: }
595:
596: $delayedAdd = [];
597: }
598:
599: $parenthesesNeeded = isset($this->parenthesesListMap[$mapKey])
600: && in_array(get_class($newNode), $this->parenthesesListMap[$mapKey], true)
601: && !in_array(get_class($originalNode), $this->parenthesesListMap[$mapKey], true);
602: $addParentheses = $parenthesesNeeded && !$originalTokens->hasParentheses($itemStartPos, $itemEndPos);
603: if ($addParentheses) {
604: $result .= '(';
605: }
606:
607: $result .= $this->printNodeFormatPreserving($newNode, $originalTokens);
608: if ($addParentheses) {
609: $result .= ')';
610: }
611: $tokenIndex = $itemEndPos + 1;
612:
613: } elseif ($diffType === DiffElem::TYPE_ADD) {
614: if ($insertStr === null) {
615: return null;
616: }
617: if (!$newNode instanceof Node) {
618: return null;
619: }
620:
621: if ($insertStr === ', ' && $isMultiline) {
622: $insertStr = ',';
623: $insertNewline = true;
624: }
625:
626: if ($beforeFirstKeepOrReplace) {
627: // Will be inserted at the next "replace" or "keep" element
628: $delayedAdd[] = $newNode;
629: continue;
630: }
631:
632: $itemEndPos = $tokenIndex - 1;
633: if ($insertNewline) {
634: $result .= $insertStr . sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
635: } else {
636: $result .= $insertStr;
637: }
638:
639: $parenthesesNeeded = isset($this->parenthesesListMap[$mapKey])
640: && in_array(get_class($newNode), $this->parenthesesListMap[$mapKey], true);
641: if ($parenthesesNeeded) {
642: $result .= '(';
643: }
644:
645: $result .= $this->printNodeFormatPreserving($newNode, $originalTokens);
646: if ($parenthesesNeeded) {
647: $result .= ')';
648: }
649:
650: $tokenIndex = $itemEndPos + 1;
651:
652: } elseif ($diffType === DiffElem::TYPE_REMOVE) {
653: if (!$originalNode instanceof Node) {
654: return null;
655: }
656:
657: $itemStartPos = $originalNode->getAttribute(Attribute::START_INDEX);
658: $itemEndPos = $originalNode->getAttribute(Attribute::END_INDEX);
659: if ($itemStartPos < 0 || $itemEndPos < 0) {
660: throw new LogicException();
661: }
662:
663: if ($i === 0) {
664: // If we're removing from the start, keep the tokens before the node and drop those after it,
665: // instead of the other way around.
666: $originalTokensArray = $originalTokens->getTokens();
667: for ($j = $tokenIndex; $j < $itemStartPos; $j++) {
668: if ($originalTokensArray[$j][Lexer::TYPE_OFFSET] === Lexer::TOKEN_PHPDOC_EOL) {
669: break;
670: }
671: $result .= $originalTokensArray[$j][Lexer::VALUE_OFFSET];
672: }
673: }
674:
675: $tokenIndex = $itemEndPos + 1;
676: }
677: }
678:
679: if (count($delayedAdd) > 0) {
680: if (!isset($this->emptyListInsertionMap[$mapKey])) {
681: return null;
682: }
683:
684: [$findToken, $extraLeft, $extraRight] = $this->emptyListInsertionMap[$mapKey];
685: if ($findToken !== null) {
686: $originalTokensArray = $originalTokens->getTokens();
687: for (; $tokenIndex < count($originalTokensArray); $tokenIndex++) {
688: $result .= $originalTokensArray[$tokenIndex][Lexer::VALUE_OFFSET];
689: if ($originalTokensArray[$tokenIndex][Lexer::VALUE_OFFSET] !== $findToken) {
690: continue;
691: }
692:
693: $tokenIndex++;
694: break;
695: }
696: }
697: $first = true;
698: $result .= $extraLeft;
699: foreach ($delayedAdd as $delayedAddNode) {
700: if (!$first) {
701: $result .= $insertStr;
702: if ($insertNewline) {
703: $result .= sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
704: }
705: }
706:
707: $result .= $this->printNodeFormatPreserving($delayedAddNode, $originalTokens);
708: $first = false;
709: }
710: $result .= $extraRight;
711: }
712:
713: return $result;
714: }
715:
716: /**
717: * @param Node[] $nodes
718: * @return array{bool, string, string}
719: */
720: private function isMultiline(int $initialIndex, array $nodes, TokenIterator $originalTokens): array
721: {
722: $isMultiline = count($nodes) > 1;
723: $pos = $initialIndex;
724: $allText = '';
725: /** @var Node|null $node */
726: foreach ($nodes as $node) {
727: if (!$node instanceof Node) {
728: continue;
729: }
730:
731: $endPos = $node->getAttribute(Attribute::END_INDEX) + 1;
732: $text = $originalTokens->getContentBetween($pos, $endPos);
733: $allText .= $text;
734: if (strpos($text, "\n") === false) {
735: // We require that a newline is present between *every* item. If the formatting
736: // is inconsistent, with only some items having newlines, we don't consider it
737: // as multiline
738: $isMultiline = false;
739: }
740: $pos = $endPos;
741: }
742:
743: $c = preg_match_all('~\n(?<before>[\\x09\\x20]*)\*(?<after>\\x20*)~', $allText, $matches, PREG_SET_ORDER);
744: if ($c === 0) {
745: return [$isMultiline, '', ''];
746: }
747:
748: $before = '';
749: $after = '';
750: foreach ($matches as $match) {
751: if (strlen($match['before']) > strlen($before)) {
752: $before = $match['before'];
753: }
754: if (strlen($match['after']) <= strlen($after)) {
755: continue;
756: }
757:
758: $after = $match['after'];
759: }
760:
761: return [$isMultiline, $before, $after];
762: }
763:
764: private function printNodeFormatPreserving(Node $node, TokenIterator $originalTokens): string
765: {
766: /** @var Node|null $originalNode */
767: $originalNode = $node->getAttribute(Attribute::ORIGINAL_NODE);
768: if ($originalNode === null) {
769: return $this->print($node);
770: }
771:
772: $class = get_class($node);
773: if ($class !== get_class($originalNode)) {
774: throw new LogicException();
775: }
776:
777: $startPos = $originalNode->getAttribute(Attribute::START_INDEX);
778: $endPos = $originalNode->getAttribute(Attribute::END_INDEX);
779: if ($startPos < 0 || $endPos < 0) {
780: throw new LogicException();
781: }
782:
783: $result = '';
784: $pos = $startPos;
785: $subNodeNames = array_keys(get_object_vars($node));
786: foreach ($subNodeNames as $subNodeName) {
787: $subNode = $node->$subNodeName;
788: $origSubNode = $originalNode->$subNodeName;
789:
790: if (
791: (!$subNode instanceof Node && $subNode !== null)
792: || (!$origSubNode instanceof Node && $origSubNode !== null)
793: ) {
794: if ($subNode === $origSubNode) {
795: // Unchanged, can reuse old code
796: continue;
797: }
798:
799: if (is_array($subNode) && is_array($origSubNode)) {
800: // Array subnode changed, we might be able to reconstruct it
801: $listResult = $this->printArrayFormatPreserving(
802: $subNode,
803: $origSubNode,
804: $originalTokens,
805: $pos,
806: $class,
807: $subNodeName
808: );
809:
810: if ($listResult === null) {
811: return $this->print($node);
812: }
813:
814: $result .= $listResult;
815: continue;
816: }
817:
818: return $this->print($node);
819: }
820:
821: if ($origSubNode === null) {
822: if ($subNode === null) {
823: // Both null, nothing to do
824: continue;
825: }
826:
827: return $this->print($node);
828: }
829:
830: $subStartPos = $origSubNode->getAttribute(Attribute::START_INDEX);
831: $subEndPos = $origSubNode->getAttribute(Attribute::END_INDEX);
832: if ($subStartPos < 0 || $subEndPos < 0) {
833: throw new LogicException();
834: }
835:
836: if ($subEndPos < $subStartPos) {
837: return $this->print($node);
838: }
839:
840: if ($subNode === null) {
841: return $this->print($node);
842: }
843:
844: $result .= $originalTokens->getContentBetween($pos, $subStartPos);
845: $mapKey = get_class($node) . '->' . $subNodeName;
846: $parenthesesNeeded = isset($this->parenthesesMap[$mapKey])
847: && in_array(get_class($subNode), $this->parenthesesMap[$mapKey], true);
848:
849: if ($subNode->getAttribute(Attribute::ORIGINAL_NODE) !== null) {
850: $parenthesesNeeded = $parenthesesNeeded
851: && !in_array(get_class($subNode->getAttribute(Attribute::ORIGINAL_NODE)), $this->parenthesesMap[$mapKey], true);
852: }
853:
854: $addParentheses = $parenthesesNeeded && !$originalTokens->hasParentheses($subStartPos, $subEndPos);
855: if ($addParentheses) {
856: $result .= '(';
857: }
858:
859: $result .= $this->printNodeFormatPreserving($subNode, $originalTokens);
860: if ($addParentheses) {
861: $result .= ')';
862: }
863:
864: $pos = $subEndPos + 1;
865: }
866:
867: return $result . $originalTokens->getContentBetween($pos, $endPos + 1);
868: }
869:
870: }
871: