|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace RonasIT\Larabuilder\Visitors\MethodVisitors; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\ArrayItem; |
| 7 | +use PhpParser\Node\Expr\Array_; |
| 8 | +use PhpParser\Node\Stmt\ClassMethod; |
| 9 | +use PhpParser\Node\Stmt\Return_; |
| 10 | +use RonasIT\Larabuilder\Contracts\UpdateNodeContract; |
| 11 | +use RonasIT\Larabuilder\Enums\DefaultValue; |
| 12 | +use RonasIT\Larabuilder\Exceptions\UnexpectedReturnTypeException; |
| 13 | +use RonasIT\Larabuilder\Nodes\PreformattedExpression; |
| 14 | +use RonasIT\Larabuilder\Printer; |
| 15 | + |
| 16 | +class AddItemToReturnArray extends AbstractMethodVisitor implements UpdateNodeContract |
| 17 | +{ |
| 18 | + protected PreformattedExpression $valueExpr; |
| 19 | + protected ?PreformattedExpression $keyExpr; |
| 20 | + |
| 21 | + public function __construct( |
| 22 | + protected string $methodName, |
| 23 | + string $value, |
| 24 | + string|DefaultValue $key = DefaultValue::None, |
| 25 | + ) { |
| 26 | + parent::__construct($methodName); |
| 27 | + |
| 28 | + $this->valueExpr = new PreformattedExpression($value); |
| 29 | + $this->keyExpr = ($key === DefaultValue::None) ? null : new PreformattedExpression($key); |
| 30 | + } |
| 31 | + |
| 32 | + public function shouldUpdateNode(Node $node): bool |
| 33 | + { |
| 34 | + $isTarget = $node instanceof ClassMethod && $this->methodName === $node->name->name; |
| 35 | + |
| 36 | + if ($isTarget) { |
| 37 | + $this->hasTargetMethod = true; |
| 38 | + } |
| 39 | + |
| 40 | + return $isTarget; |
| 41 | + } |
| 42 | + |
| 43 | + public function updateNode(Node $node): void |
| 44 | + { |
| 45 | + $returnNode = array_find(array_reverse($node->stmts ?? []), fn ($stmt) => $stmt instanceof Return_); |
| 46 | + |
| 47 | + if (!$returnNode?->expr instanceof Array_) { |
| 48 | + throw new UnexpectedReturnTypeException($this->methodName, 'array', $node->returnType?->toString()); |
| 49 | + } |
| 50 | + |
| 51 | + if (empty($this->keyExpr)) { |
| 52 | + $returnNode->expr->items[] = new ArrayItem($this->valueExpr); |
| 53 | + |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + $printer = new Printer(); |
| 58 | + |
| 59 | + foreach ($returnNode->expr->items as $item) { |
| 60 | + if ($item instanceof ArrayItem |
| 61 | + && !empty($item->key) |
| 62 | + && $printer->prettyPrintExpr($item->key) === $this->keyExpr->value |
| 63 | + ) { |
| 64 | + $item->value = $this->valueExpr; |
| 65 | + |
| 66 | + return; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + $returnNode->expr->items[] = new ArrayItem($this->valueExpr, $this->keyExpr); |
| 71 | + } |
| 72 | +} |
0 commit comments