-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddExceptionsRender.php
More file actions
111 lines (90 loc) · 3.02 KB
/
AddExceptionsRender.php
File metadata and controls
111 lines (90 loc) · 3.02 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
<?php
namespace RonasIT\Larabuilder\Visitors\AppBootstrapVisitors;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Nop;
use RonasIT\Larabuilder\Enums\StatementAttributeEnum;
use RonasIT\Larabuilder\Nodes\PreformattedCode;
class AddExceptionsRender extends AbstractAppBootstrapVisitor
{
protected Expression $renderStatement;
public function __construct(
protected string $exceptionClass,
protected string $renderBody,
protected bool $includeRequestArg,
) {
$this->renderStatement = $this->buildRenderCall();
parent::__construct(
parentMethod: 'withExceptions',
targetMethod: 'render',
closureParams: [
new Param(
var: new Variable('exceptions'),
type: new Name('Exceptions'),
),
],
);
}
protected function insertNode(MethodCall $node): MethodCall
{
$currentStatements = $node->args[0]->value->stmts;
if (count($currentStatements) === 1 && $currentStatements[0] instanceof Nop) {
$node->args[0]->value->stmts = [$this->renderStatement];
return $node;
}
$lastExistingStatement = end($currentStatements);
$this->renderStatement->setAttribute(StatementAttributeEnum::Previous->value, $lastExistingStatement);
$node->args[0]->value->stmts[] = $this->renderStatement;
return $node;
}
protected function buildRenderCall(): Expression
{
return new Expression(
new MethodCall(
new Variable('exceptions'),
new Identifier('render'),
[
new Arg($this->buildClosure()),
],
),
);
}
protected function buildClosure(): Closure
{
$params = [
new Param(
var: new Variable('exception'),
type: new Name(class_basename($this->exceptionClass)),
),
];
if ($this->includeRequestArg) {
$params[] = new Param(
var: new Variable('request'),
type: new Name('Request'),
);
}
return new Closure([
'params' => $params,
'stmts' => [new PreformattedCode($this->renderBody)],
]);
}
protected function matchesCustomCriteria(Expression $stmt): bool
{
$paramType = $stmt->expr->args[0]?->value?->params[0]?->type ?? null;
if (!($paramType instanceof Name)) {
return false;
}
$typeName = $paramType->toString();
return $typeName === $this->exceptionClass || $typeName === class_basename($this->exceptionClass);
}
protected function getInsertableNode(): Expression
{
return $this->renderStatement;
}
}