Repository navigation
Expand file tree
/
Copy pathAddFormClassesNodeVisitor.php
More file actions
806 lines (716 loc) · 30.3 KB
/
Copy pathAddFormClassesNodeVisitor.php
File metadata and controls
806 lines (716 loc) · 30.3 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
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
<?php
declare(strict_types=1);
namespace Efabrica\PHPStanLatte\Compiler\NodeVisitor;
use Efabrica\PHPStanLatte\Compiler\Helper\FormHelper;
use Efabrica\PHPStanLatte\Compiler\NodeVisitor\Behavior\FormsNodeVisitorBehavior;
use Efabrica\PHPStanLatte\Compiler\NodeVisitor\Behavior\FormsNodeVisitorInterface;
use Efabrica\PHPStanLatte\Error\Error;
use Efabrica\PHPStanLatte\Resolver\NameResolver\NameResolver;
use Efabrica\PHPStanLatte\Template\Form\Container;
use Efabrica\PHPStanLatte\Template\Form\ControlHolderInterface;
use Efabrica\PHPStanLatte\Template\Form\ControlInterface;
use Efabrica\PHPStanLatte\Template\Form\Form;
use Efabrica\PHPStanLatte\Template\Form\Group;
use PhpParser\Builder\Class_;
use PhpParser\Builder\Method;
use PhpParser\Builder\Param;
use PhpParser\Comment\Doc;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\LNumber;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_ as StmtClass_;
use PhpParser\Node\Stmt\Echo_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\PropertyProperty;
use PhpParser\Node\Stmt\Return_;
use PhpParser\NodeVisitorAbstract;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\VerbosityLevel;
use function array_merge;
use function array_reverse;
use function end;
use function explode;
use function in_array;
use function spl_object_hash;
use function str_replace;
final class AddFormClassesNodeVisitor extends NodeVisitorAbstract implements FormsNodeVisitorInterface
{
use FormsNodeVisitorBehavior;
private const COMPONENT_TYPE = '\Nette\Forms\Controls\BaseControl';
private const COMPONENT_TYPE_PLACEHOLDER = '%%COMPONENT_TYPE%%';
private const GROUP_TYPE_PLACEHOLDER = '%%GROUP_TYPE%%';
private const GROUP_TYPE = '\Nette\Forms\ControlGroup';
private NameResolver $nameResolver;
/** @var array<array{node: string, control: string}> */
private array $errorControlNodes = [];
/** @var string[] */
private array $possibleAlwaysTrueLabels = [];
public function __construct(NameResolver $nameResolver)
{
$this->nameResolver = $nameResolver;
}
public function enterNode(Node $node): ?Node
{
if ($node instanceof Assign) {
// nette/forms 3.3 starts a form with begin($form = $this->global->uiControl['name'])
if ($node->var instanceof Variable && $node->var->name === 'form'
&& $node->expr instanceof ArrayDimFetch
&& $node->expr->dim instanceof String_
&& $this->isUiControl($node->expr->var)
) {
$formName = $node->expr->dim->value;
$formClassName = $this->formClassNames[$formName] ?? null;
$this->actualForm = $this->forms[$formName] ?? null;
if ($formClassName === null) {
$this->actualForm = new Form($formName, new ObjectType('Nette\Forms\Form'));
$error = new Error('Form with name "' . $formName . '" probably does not exist.');
return new Assign(
new Variable('form'),
new ArrayDimFetch(
new Array_([
new ArrayItem(new New_(new Name('Nette\Forms\Form'))),
new ArrayItem($error->toNode()->expr),
]),
new LNumber(0)
)
);
}
return new Assign(new Variable('form'), new StaticCall(new Name(FormHelper::class), 'getForm', [
new Arg(new ClassConstFetch(new Name($formClassName), 'class')),
]));
}
if (!$node->expr instanceof Assign) {
return null;
}
$assign = $node->expr;
if (!$assign->expr instanceof ArrayDimFetch) {
return null;
}
$dimFetch = $assign->expr;
if (!$this->isUiControl($dimFetch->var)) {
return null;
}
if (!$dimFetch->dim instanceof String_) {
return null;
}
$formNameString = $dimFetch->dim;
$formName = $formNameString->value;
$formClassName = $this->formClassNames[$formName] ?? null;
if ($formClassName === null) {
$this->actualForm = new Form($formName, new ObjectType('Nette\Forms\Form'));
$error = new Error('Form with name "' . $formName . '" probably does not exist.');
return new Assign(
new Variable('form'),
new ArrayDimFetch(
new Array_([
new ArrayItem(new New_(new Name('Nette\Forms\Form'))),
new ArrayItem($error->toNode()->expr),
]),
new LNumber(0)
)
);
}
$this->actualForm = $this->forms[$formName] ?? null;
return new Assign(new Variable('form'), new StaticCall(new Name(FormHelper::class), 'getForm', [
new Arg(new ClassConstFetch(new Name($formClassName), 'class')),
]));
} elseif ($node instanceof StaticCall) {
if ($this->nameResolver->resolve($node->class) === 'Nette\Bridges\FormsLatte\Runtime') {
if ($this->nameResolver->resolve($node->name) === 'renderFormEnd') {
$node->args[0] = new Arg(new Variable('form'));
$this->actualForm = null;
return $node;
}
/**
* Replace:
* <code>
* \Nette\Bridges\FormsLatte\Runtime::item('foobar')
* </code>
*
* With:
* <code>
* $form['foobar']
* <code>
*
* if foobar exists in actual form
*/
if ($this->nameResolver->resolve($node->name) === 'item') {
if ($this->actualForm === null) {
return null;
}
$itemArgument = $node->getArgs()[0] ?? null;
if ($itemArgument === null) {
return null;
}
return $this->createFormControlFetch($itemArgument->value, $node->getAttributes(), $node);
}
}
} elseif ($node instanceof MethodCall) {
// nette/forms 3.3 compiles {input}, {label} and {formContainer} to
// $this->global->forms->get(...) and ends forms with renderFormEnd()
if ($this->isFormsRuntimeMethod($node, 'renderFormEnd')) {
$this->actualForm = null;
return null;
}
if ($this->actualForm === null || !$this->isFormsRuntimeGet($node)) {
return null;
}
$itemArgument = $node->getArgs()[0] ?? null;
if ($itemArgument === null) {
return null;
}
if ($this->isFormsRuntimeGetContainer($node)) {
return $this->createFormContainerFetch($itemArgument->value, $node->getAttributes(), $node);
}
return $this->createFormControlFetch($itemArgument->value, $node->getAttributes(), $node);
} elseif ($node instanceof ArrayDimFetch) {
if ($this->actualForm === null) {
return null;
}
if (!$node->var instanceof FuncCall) {
return null;
}
if ($this->nameResolver->resolve($node->var) !== 'end') {
return null;
}
if (!$node->var->args[0] instanceof Arg) {
return null;
}
if (!$this->isFormsStack($node->var->args[0]->value)) {
return null;
}
$formControl = null;
if ($node->dim instanceof String_ || $node->dim instanceof LNumber) {
$controlName = (string)$node->dim->value;
// TODO remove when container are supported
$controlNameParts = explode('-', $controlName);
$controlName = end($controlNameParts);
$formControl = $this->actualForm->getControl($controlName);
if ($formControl === null) {
$this->errorControlNodes[] = [
'node' => $this->findParentStmt($node),
'control' => $controlName,
];
return null;
}
$formControlType = $formControl->getType();
if ((new ObjectType('Nette\Forms\Controls\CheckboxList'))->isSuperTypeOf($formControlType)->yes() || (new ObjectType('Nette\Forms\Controls\RadioList'))->isSuperTypeOf($formControlType)->yes()) {
$this->possibleAlwaysTrueLabels[] = $this->findParentStmt($node);
}
} elseif ($node->dim instanceof Variable) {
// dynamic control
} else {
return null;
}
$node->var = new Variable('form');
if ($formControl !== null) {
$node->setAttribute('formControl', $formControl);
}
return $node;
}
return null;
}
/**
* @return Node|Node[]|null
*/
public function leaveNode(Node $node)
{
foreach ($this->errorControlNodes as $errorControlNode) {
if ($errorControlNode['node'] === spl_object_hash($node)) {
$error = new Error('Form control with name "' . $errorControlNode['control'] . '" probably does not exist.');
$errorNode = $error->toNode();
$errorNode->setAttributes($node->getAttributes());
return $errorNode;
}
}
/**
* Replace:
* <code>
* if ($ʟ_label = $form["foo"]->getLabel()) {
* echo $ʟ_label;
* }
* </code>
*
* With:
* <code>
* $ʟ_label = $form["foo"]->getLabel();
* echo $ʟ_label;
* </code>
*
* for RadioList and CheckboxList methods getLabel, getLabelPart, getControlPart
*/
if ($node instanceof If_) {
foreach ($this->possibleAlwaysTrueLabels as $possibleAlwaysTrueLabel) {
if ($possibleAlwaysTrueLabel === spl_object_hash($node)) {
if ($node->cond instanceof Assign) {
if (in_array($this->nameResolver->resolve($node->cond->var), ['ʟ_label', '_label'], true) &&
(
$node->cond->expr instanceof MethodCall && in_array($this->nameResolver->resolve($node->cond->expr), ['getLabel', 'getLabelPart', 'getControlPart'], true) ||
$node->cond->expr instanceof ArrayDimFetch && $node->cond->expr->var instanceof Array_ && isset($node->cond->expr->var->items[0]) && $node->cond->expr->var->items[0]->value instanceof MethodCall && in_array($this->nameResolver->resolve($node->cond->expr->var->items[0]->value), ['getLabel', 'getLabelPart', 'getControlPart'], true)
)
) {
$expression = new Expression($node->cond);
$expression->setAttributes($node->getAttributes());
return array_merge([$expression], $node->stmts);
}
}
}
}
}
/**
* Replace:
* <code>
* echo \Nette\Bridges\FormsLatte\Runtime::item($name, $this->global)->getControl();
* </code>
*
* With:
* <code>
* /** @var Nette\Forms\Controls\BaseControl $ʟ_input
* $ʟ_input = \Nette\Bridges\FormsLatte\Runtime::item($name, $this->global);
* echo $ʟ_input->getControl();
* </code>
*/
if ($node instanceof Echo_ && ($node->exprs[0] ?? null) instanceof MethodCall) {
$varName = 'ʟ_input';
/** @var MethodCall $methodCallExpr */
$methodCallExpr = $node->exprs[0];
$methodCallVar = $methodCallExpr->var;
$methodCalls = [$methodCallExpr];
while ($methodCallVar instanceof MethodCall) {
if ($this->isFormsRuntimeGet($methodCallVar)) {
break;
}
$methodCalls[] = $methodCallVar;
$methodCallVar = $methodCallVar->var;
}
if (($methodCallVar instanceof StaticCall && $this->nameResolver->resolve($methodCallVar->class) === 'Nette\Bridges\FormsLatte\Runtime' && $this->nameResolver->resolve($methodCallVar->name) === 'item') ||
($methodCallVar instanceof MethodCall && $this->isFormsRuntimeGet($methodCallVar))
) {
$newMethodCallVar = new Variable($varName);
$newMethodCall = null;
foreach (array_reverse($methodCalls) as $methodCall) {
$newMethodCall = $newMethodCallVar = new MethodCall($newMethodCallVar, $methodCall->name, $methodCall->args);
}
return [
new Expression(new Assign(new Variable($varName), $methodCallVar), ['comments' => [new Doc('/** @var Nette\Forms\Controls\BaseControl $' . $varName . ' */')]]),
new Echo_([$newMethodCall]),
];
}
}
/**
* Replace:
* <code>
* echo $ʟ_label = \Nette\Bridges\FormsLatte\Runtime::item($name, $this->global)->getLabel();
* </code>
*
* With:
* <code>
* /** @var Nette\Forms\Controls\BaseControl $ʟ_label
* $ʟ_label = \Nette\Bridges\FormsLatte\Runtime::item($name, $this->global);
* echo $ʟ_label->getLabel();
* </code>
*/
if ($node instanceof Echo_ &&
($node->exprs[0] ?? null) instanceof Assign &&
$node->exprs[0]->expr instanceof MethodCall &&
$node->exprs[0]->var instanceof Variable
) {
$varName = $this->nameResolver->resolve($node->exprs[0]->var->name) ?? '$ʟ_tmp';
/** @var MethodCall $methodCallExpr */
$methodCallExpr = $node->exprs[0]->expr;
$methodCallVar = $methodCallExpr->var;
$methodCalls = [$methodCallExpr];
while ($methodCallVar instanceof MethodCall) {
if ($this->isFormsRuntimeGet($methodCallVar)) {
break;
}
$methodCalls[] = $methodCallVar;
$methodCallVar = $methodCallVar->var;
}
if (($methodCallVar instanceof StaticCall && $this->nameResolver->resolve($methodCallVar->class) === 'Nette\Bridges\FormsLatte\Runtime' && $this->nameResolver->resolve($methodCallVar->name) === 'item') ||
($methodCallVar instanceof MethodCall && $this->isFormsRuntimeGet($methodCallVar))
) {
$newMethodCallVar = new Variable($varName);
$newMethodCall = null;
foreach (array_reverse($methodCalls) as $methodCall) {
$newMethodCall = $newMethodCallVar = new MethodCall($newMethodCallVar, $methodCall->name, $methodCall->args);
}
return [
new Expression(new Assign(new Variable($varName), $methodCallVar), ['comments' => [new Doc('/** @var Nette\Forms\Controls\BaseControl $' . $varName . ' */')]]),
new Echo_([$newMethodCall]),
];
}
}
/**
* Replace:
* <code>
* end($this->global->formsStack)
* </code>
*
* With
* <code>
* $form
* </code>
*/
if ($node instanceof FuncCall && $this->nameResolver->resolve($node) === 'end') {
$arg = $node->getArgs()[0] ?? null;
if ($arg instanceof Arg && $this->isFormsStack($arg->value)) {
return new Variable('form');
}
}
/**
* Replace:
* <code>
* echo $this->global->forms->begin($form = $this->global->uiControl['firstForm'], global: $this->global);
* </code>
*
* With:
* <code>
* $form = ...;
* $this->global->forms->begin($form, global: $this->global);
* </code>
*/
if ($node instanceof Expression && $node->expr instanceof MethodCall && $this->isFormsRuntimeMethod($node->expr, 'begin')) {
$formArgument = $node->expr->getArgs()[0] ?? null;
if ($formArgument !== null && $formArgument->value instanceof Assign &&
$formArgument->value->var instanceof Variable && $formArgument->value->var->name === 'form'
) {
$assign = new Expression($formArgument->value);
$assign->setAttributes($node->getAttributes());
$formArgument->value = new Variable('form');
return [$assign, $node];
}
}
return null;
}
private function findParentStmt(Node $node): string
{
$rootParentNode = $node;
while (true) {
/** @var ?Node $parentNode */
$parentNode = $rootParentNode->getAttribute('parent');
if ($parentNode === null) {
throw new ShouldNotHappenException('Could not find parent statement.');
}
$rootParentNode = $parentNode;
if ($parentNode instanceof Stmt) {
break;
}
}
return spl_object_hash($rootParentNode);
}
/**
* @param Node[] $nodes
* @return Node[]
*/
public function afterTraverse(array $nodes): array
{
$templateClass = false;
foreach ($nodes as $node) {
if ($node instanceof StmtClass_) {
if ($templateClass === false) {
// skip Template class
$templateClass = true;
continue;
}
// use Template->global class
$arrayShapeItems = [];
foreach ($this->formClassNames as $formName => $form) {
$arrayShapeItems[] = new ArrayShapeItemNode(new ConstExprStringNode($formName, ConstExprStringNode::SINGLE_QUOTED), false, (new ConstantStringType($form))->toPhpDocNode());
}
$arrayShape = ArrayShapeNode::createSealed($arrayShapeItems);
$node->stmts[] = new Property(StmtClass_::MODIFIER_PUBLIC, [
new PropertyProperty('formNamesToFormClasses'),
], [
'comments' => [new Doc('/** @var ' . $arrayShape->__toString() . ' */')],
], new Name('array'));
break;
}
}
$controlAssign = new Expression(new Assign(new Variable('control'), new StaticCall(
new Name('parent'),
new Identifier('offsetGet'),
[
new Arg(new Variable('name')),
]
)));
$controlAssign->setDocComment(new Doc('/** @var \Nette\Forms\Controls\BaseControl $control */'));
$baseOffsetGetMethod = (new Method('offsetGet'))
->addParam(new Param('name'))
->addStmts([
$controlAssign,
new Return_(new Variable('control')),
])
->makePublic()
->setReturnType('Nette\ComponentModel\IComponent');
// create Container classes
foreach ($this->forms as $formName => $form) {
$formClassName = $this->formClassNames[$formName] ?? null;
if ($formClassName === null) {
continue;
}
foreach ($form->getControls() as $formControl) {
if (!$formControl instanceof Container) {
continue;
}
$nodes[] = $this->createClassNode($formClassName, $formControl, $baseOffsetGetMethod);
}
}
// create Form classes
foreach ($this->forms as $formName => $form) {
$className = $this->formClassNames[$formName] ?? null;
if ($className === null) {
continue;
}
$nodes[] = $this->createClassNode($className, $form, $baseOffsetGetMethod);
}
return $nodes;
}
/**
* @param Form|Container $controlHolder
*/
private function createClassNode(string $parentClassName, ControlHolderInterface $controlHolder, Method $baseOffsetGetMethod): Node
{
$offsetGetComment = $this->createOffsetGetConditionalReturnTypeComment($parentClassName, $controlHolder->getControls());
$offsetGetMethod = clone $baseOffsetGetMethod;
$offsetGetMethod->setDocComment('/** @param string $name' . "\n" . $offsetGetComment . ' */');
$methods = [
$offsetGetMethod,
];
$className = $parentClassName;
if ($controlHolder instanceof Container) {
$className .= '_' . $controlHolder->getName();
}
if ($controlHolder instanceof Form) {
$getGroupMethod = (new Method('getGroup'))
->addParam(new Param('name'))
->addStmts([
new Return_(new StaticCall(
new Name('parent'),
new Identifier('getGroup'),
[
new Arg(new Variable('name')),
]
)),
])
->makePublic()
->setReturnType('?Nette\Forms\ControlGroup');
$getGroupComment = $this->createGetGroupConditionalReturnTypeComment($controlHolder->getGroups());
$getGroupMethod->setDocComment('/** @param int|string $name' . "\n" . $getGroupComment . ' */');
$methods[] = $getGroupMethod;
}
$builderClass = (new Class_($this->fixClassName($className)))->extend($controlHolder->getType()->describe(VerbosityLevel::typeOnly()))
->addStmts($methods);
return $builderClass->getNode();
}
/**
* @param ControlInterface[] $controls
*/
private function createOffsetGetConditionalReturnTypeComment(string $parentName, array $controls): string
{
$comment = '@return ' . self::COMPONENT_TYPE_PLACEHOLDER;
foreach ($controls as $control) {
if ($control instanceof Container) {
$controlType = $parentName . '_' . $control->getName();
} else {
$controlType = $control->getTypeAsString();
}
$comment = str_replace(self::COMPONENT_TYPE_PLACEHOLDER, '($name is \'' . $control->getName() . '\' ? ' . $this->fixClassName($controlType) . ' : ' . self::COMPONENT_TYPE_PLACEHOLDER . ')', $comment);
}
return str_replace(self::COMPONENT_TYPE_PLACEHOLDER, self::COMPONENT_TYPE, $comment);
}
/**
* @param Group[] $groups
*/
private function createGetGroupConditionalReturnTypeComment(array $groups): string
{
$comment = '@return ' . self::GROUP_TYPE_PLACEHOLDER;
foreach ($groups as $group) {
$comment = str_replace(self::GROUP_TYPE_PLACEHOLDER, '($name is \'' . $group->getName() . '\' ? ' . self::GROUP_TYPE . ' : ' . self::GROUP_TYPE_PLACEHOLDER . ')', $comment);
}
return str_replace(self::GROUP_TYPE_PLACEHOLDER, 'null', $comment);
}
private function isUiControl(Expr $expr): bool
{
if (!$expr instanceof PropertyFetch) {
return false;
}
if (!$expr->name instanceof Identifier) {
return false;
}
if ($this->nameResolver->resolve($expr->name) !== 'uiControl') {
return false;
}
if (!$expr->var instanceof PropertyFetch) {
return false;
}
if (!$expr->var->name instanceof Identifier) {
return false;
}
if ($this->nameResolver->resolve($expr->var->name) !== 'global') {
return false;
}
return true;
}
private function isFormsRuntimeGet(MethodCall $node): bool
{
return $this->isFormsRuntimeMethod($node, 'get');
}
private function isFormsRuntimeGetContainer(MethodCall $node): bool
{
$typeArgument = $node->getArgs()[1] ?? null;
if ($typeArgument === null || !$typeArgument->value instanceof ClassConstFetch) {
return false;
}
if ($this->nameResolver->resolve($typeArgument->value->name) !== 'class') {
return false;
}
return $this->nameResolver->resolve($typeArgument->value->class) === 'Nette\Forms\Container';
}
private function isFormsRuntimeMethod(MethodCall $node, string $method): bool
{
if (!$node->name instanceof Identifier || $node->name->toString() !== $method) {
return false;
}
$forms = $node->var;
if (!$forms instanceof PropertyFetch || !$forms->name instanceof Identifier || $forms->name->toString() !== 'forms') {
return false;
}
$global = $forms->var;
if (!$global instanceof PropertyFetch || !$global->name instanceof Identifier || $global->name->toString() !== 'global') {
return false;
}
return $global->var instanceof Variable && $global->var->name === 'this';
}
/**
* Replaces forms->get(<control>) and Runtime::item(<control>) with $form[<control>].
*
* @param array<string, mixed> $attributes
*/
private function createFormControlFetch(Expr $itemArgumentValue, array $attributes, Node $node): ?ArrayDimFetch
{
// dynamic item can also be a control object, keep the get()/item() call
if ($itemArgumentValue instanceof Variable) {
return null;
}
$formControl = null;
if ($itemArgumentValue instanceof String_ || $itemArgumentValue instanceof LNumber) {
$controlName = (string)$itemArgumentValue->value;
// TODO remove when containers are supported
$controlNameParts = explode('-', $controlName);
$controlName = end($controlNameParts);
$formControl = $this->actualForm !== null ? $this->actualForm->getControl($controlName) : null;
if ($formControl === null) {
$this->errorControlNodes[] = [
'node' => $this->findParentStmt($node),
'control' => $controlName,
];
return null;
}
}
if ($formControl !== null) {
$attributes['formControl'] = $formControl;
}
return new ArrayDimFetch(
new Variable('form'),
$itemArgumentValue,
$attributes
);
}
/**
* Replaces forms->get(<container>, Nette\Forms\Container::class) with $form[<container>]
* only when the generated form class knows the concrete container type.
*
* @param array<string, mixed> $attributes
*/
private function createFormContainerFetch(Expr $itemArgumentValue, array $attributes, Node $node): ?ArrayDimFetch
{
if ($itemArgumentValue instanceof String_ || $itemArgumentValue instanceof LNumber) {
$controlName = (string)$itemArgumentValue->value;
} elseif ($itemArgumentValue instanceof PropertyFetch) {
$varName = $this->nameResolver->resolve($itemArgumentValue->var);
$propertyName = $this->nameResolver->resolve($itemArgumentValue->name);
if ($varName === null || $propertyName === null) {
return null;
}
$controlName = '$' . $varName . '->' . $propertyName;
} else {
// dynamic item can also be a container object
return null;
}
// TODO remove when containers are supported
if ($itemArgumentValue instanceof PropertyFetch) {
$lookupName = $controlName;
} else {
$controlNameParts = explode('-', $controlName);
$lookupName = end($controlNameParts);
}
$formControl = $this->actualForm !== null ? $this->actualForm->getControl($lookupName) : null;
if ($formControl === null) {
$this->errorControlNodes[] = [
'node' => $this->findParentStmt($node),
'control' => $lookupName,
];
return null;
}
if (!$formControl instanceof Container || $lookupName !== $controlName) {
// keep get(..., Container::class), it is already typed as Container
return null;
}
$attributes['formControl'] = $formControl;
return new ArrayDimFetch(
new Variable('form'),
$itemArgumentValue,
$attributes
);
}
private function isFormsStack(Expr $expr): bool
{
if (!$expr instanceof PropertyFetch) {
return false;
}
if (!$expr->name instanceof Identifier) {
return false;
}
if ($this->nameResolver->resolve($expr->name) !== 'formsStack') {
return false;
}
if (!$expr->var instanceof PropertyFetch) {
return false;
}
if (!$expr->var->name instanceof Identifier) {
return false;
}
if ($this->nameResolver->resolve($expr->var->name) !== 'global') {
return false;
}
return true;
}
private function fixClassName(string $className): string
{
return str_replace(['$', '->'], ['_dollar_', '_arrow_'], $className);
}
}