-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertCodeToMethod.php
More file actions
52 lines (41 loc) · 1.65 KB
/
Copy pathInsertCodeToMethod.php
File metadata and controls
52 lines (41 loc) · 1.65 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
<?php
namespace RonasIT\Larabuilder\Visitors\MethodVisitors;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Nop;
use RonasIT\Larabuilder\Contracts\UpdateNodeContract;
use RonasIT\Larabuilder\Enums\InsertPositionEnum;
use RonasIT\Larabuilder\Nodes\PreformattedCode;
use RonasIT\Larabuilder\Support\StatementDuplicateChecker;
class InsertCodeToMethod extends BaseMethodVisitor implements UpdateNodeContract
{
protected PreformattedCode $code;
protected StatementDuplicateChecker $statementDuplicateChecker;
public function __construct(
protected string $methodName,
string $code,
protected InsertPositionEnum $insertPosition,
) {
parent::__construct($methodName);
$this->code = new PreformattedCode($code);
$this->statementDuplicateChecker = new StatementDuplicateChecker();
}
public function shouldUpdateNode(Node $node): bool
{
$isTargetMethod = $node instanceof ClassMethod && $this->methodName === $node->name->name;
if ($isTargetMethod) {
$this->hasTargetMethod = true;
}
return !empty($this->code->value)
&& $isTargetMethod
&& !$this->statementDuplicateChecker->isDuplicated($node->stmts ?? [], $this->code->code);
}
public function updateNode(Node $node): void
{
$existingStmts = $node->stmts ?? [];
$separator = (!empty($existingStmts)) ? [new Nop()] : [];
$node->stmts = ($this->insertPosition === InsertPositionEnum::Start)
? [$this->code, ...$separator, ...$existingStmts]
: [...$existingStmts, ...$separator, $this->code];
}
}