Repository navigation
Expand file tree
/
Copy pathProxiedClassModifier.php
More file actions
365 lines (318 loc) · 10.2 KB
/
Copy pathProxiedClassModifier.php
File metadata and controls
365 lines (318 loc) · 10.2 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
<?php
/** @noinspection PhpPropertyOnlyWrittenInspection */
namespace Okapi\Aop\Core\Transform;
use DI\Attribute\Inject;
use Microsoft\PhpParser\Node;
use Microsoft\PhpParser\Token;
use Microsoft\PhpParser\TokenKind;
use Okapi\Aop\Core\Cache\CachePaths;
use Okapi\CodeTransformer\Core\DI;
use Okapi\CodeTransformer\Core\StreamFilter\Metadata;
use Okapi\CodeTransformer\Transformer\Code;
/**
* # Proxied Class Modifier
*
* This class is responsible for modifying the proxied class.
*/
class ProxiedClassModifier
{
// region DI
#[Inject]
private CachePaths $cachePaths;
// endregion
/**
* The code class.
*
* @var Code
*/
private Code $code;
/**
* The source file node.
*
* @var Node\SourceFileNode
*/
private Node\SourceFileNode $sourceFileNode;
/**
* The proxied class name.
*
* @var string
*/
private string $proxiedClassName;
/**
* Callbacks to process tokens.
*
* @var callable<Token>[]
*/
private array $tokenCallbacks = [];
/**
* Callbacks to process nodes.
*
* @var callable<Node>[]
*/
private array $nodeCallbacks = [];
/**
* @var (Node|Token)[]
*/
private array $alreadyProcessed = [];
/**
* ProxiedClassModifier constructor.
*
* @param Metadata $metadata
*/
public function __construct(
private readonly Metadata $metadata,
) {
$cachePaths = DI::get(CachePaths::class);
$this->code = $this->metadata->code;
$this->sourceFileNode = $this->code->getSourceFileNode();
$this->proxiedClassName = $this->code->getClassName() . $cachePaths::PROXIED_SUFFIX;
}
/** @noinspection PhpUnused Is used at runtime for proxied classes */
public static function resolveStaticClass(string $staticClass): string
{
return str_replace(
CachePaths::PROXIED_SUFFIX,
'',
$staticClass,
);
}
/**
* Modify the proxied class.
*
* @return void
*/
public function modify(): void
{
$this->convertToProxy();
$this->unFinalMethods();
$this->unReadOnlyClasses();
$this->changeVisibility();
$this->replaceSelfType();
$this->replaceMagicConstants();
$sourceFileNode = $this->metadata->code->getSourceFileNode();
// Iterate over the nodes
foreach ($sourceFileNode->getDescendantNodes() as $node) {
foreach ($this->nodeCallbacks as $callback) {
$callback($node);
}
}
// Iterate over the tokens
foreach ($sourceFileNode->getDescendantTokens() as $token) {
foreach ($this->tokenCallbacks as $callback) {
$callback($token);
}
}
}
private function edit(
Node|Token $nodeOrToken,
string $replacement,
): void {
if (in_array($nodeOrToken, $this->alreadyProcessed, true)) {
return;
}
$this->code->edit(
$nodeOrToken,
$replacement,
);
$this->alreadyProcessed[] = $nodeOrToken;
}
/**
* Convert the proxied class to a class that extends the proxied class.
*
* @return void
*/
private function convertToProxy(): void
{
// Find the class declaration
$node = $this->sourceFileNode->getFirstDescendantNode(Node\Statement\ClassDeclaration::class);
assert($node instanceof Node\Statement\ClassDeclaration);
// Replace the class name
$this->edit(
$node->name,
$this->proxiedClassName,
);
// Append the child class
$childClassPath = $this->cachePaths->getWovenCachePath($this->metadata->uri);
// language=PHP
$codeToAppend = "\ninclude_once '$childClassPath';";
$this->code->append($codeToAppend);
}
/**
* Remove the final keyword from the methods.
*
* @return void
*/
private function unFinalMethods(): void
{
$this->tokenCallbacks[] = function (Token $token) {
if ($token->kind === TokenKind::FinalKeyword) {
$this->edit($token, '');
}
};
}
private function unReadOnlyClasses(): void
{
$this->tokenCallbacks[] = function (Token $token) {
if ($token->kind === TokenKind::ReadonlyKeyword) {
$this->edit($token, '');
}
};
}
/**
* Change the visibility of the class members.
*
* @return void
*/
private function changeVisibility(): void
{
// A descendant may be loaded after this class. Keep every private property
// in its declaring scope, even when no same-name property is known yet.
foreach ($this->sourceFileNode->getDescendantNodes() as $node) {
$modifiers = match (true) {
$node instanceof Node\PropertyDeclaration => $node->modifiers ?? [],
$node instanceof Node\Parameter => array_filter([
$node->visibilityToken,
...($node->modifiers ?? []),
]),
default => [],
};
foreach ($modifiers as $modifier) {
if ($modifier->kind === TokenKind::PrivateKeyword) {
$this->alreadyProcessed[] = $modifier;
}
}
}
$this->tokenCallbacks[] = function (Token $token) {
if ($token->kind === TokenKind::PrivateKeyword
|| $token->kind === TokenKind::ProtectedKeyword
) {
$this->edit(
$token,
'public',
);
}
};
}
// region Self Types
/**
* Replace self type with the original class name.
*
* @return void
*/
private function replaceSelfType(): void
{
$this->nodeCallbacks[] = function (Node $node) {
// Replace return object types with the proxied class name
if ($node instanceof Node\MethodDeclaration
&& $node->returnTypeList instanceof Node\DelimitedList\QualifiedNameList
) {
foreach ($node->returnTypeList->children as $returnType) {
if ($returnType instanceof Node\QualifiedName) {
$this->replaceReturnSelfType($returnType);
}
}
}
// Replace self object creations with the proxied class name
if ($node instanceof Node\Expression\ObjectCreationExpression) {
if ($node->classTypeDesignator->getText() === 'self') {
$this->replaceObjectCreationSelfType($node);
}
}
};
}
/**
* Replace the return self type with the proxied class name.
*
* @param Node\QualifiedName $qualifiedName
*
* @return void
*/
private function replaceReturnSelfType(
Node\QualifiedName $qualifiedName,
): void {
// Self
if ($qualifiedName->getText() === 'self') {
$this->edit(
$qualifiedName,
$this->proxiedClassName,
);
}
}
/**
* Replace the object creation self type with the proxied class name.
*
* @param Node\Expression\ObjectCreationExpression $objectCreationExpression
*
* @return void
*/
private function replaceObjectCreationSelfType(
Node\Expression\ObjectCreationExpression $objectCreationExpression,
): void {
$this->edit(
$objectCreationExpression->classTypeDesignator,
'\\' . $this->code->getNamespacedClass(),
);
}
// endregion
/**
* Replace magic constants like {@see __DIR__} to their actual path.
*
* @return void
*
* @see https://www.php.net/manual/language.constants.magic.php
*/
private function replaceMagicConstants(): void
{
$this->nodeCallbacks[] = function (Node $node) {
if ($node instanceof Node\QualifiedName) {
$text = $node->getText();
switch ($text) {
case '__DIR__':
$originalParentDir = dirname($this->getOriginalFileDir());
$this->edit($node, "'$originalParentDir'");
break;
case '__FILE__':
$originalFileDir = $this->getOriginalFileDir();
$this->edit($node, "'$originalFileDir'");
break;
case '__CLASS__':
$originalNamespacedClassName = $this->code->getNamespacedClass();
$this->edit($node, "'$originalNamespacedClassName'");
break;
case '__METHOD__':
$methodNode = $node->getFirstAncestor(Node\MethodDeclaration::class);
if (!$methodNode) {
break;
}
assert($methodNode instanceof Node\MethodDeclaration);
$originalNamespacedClassName = $this->code->getNamespacedClass();
$originalMethodName = $methodNode->getName();
$this->edit(
$node,
"'$originalNamespacedClassName::$originalMethodName'",
);
break;
case 'self':
$originalClassName = $this->code->getClassName();
$this->edit(
$node,
$originalClassName,
);
break;
}
}
if ($node instanceof Node\Expression\ScopedPropertyAccessExpression) {
if ($node->getText() === 'static::class') {
$this->edit(
$node,
'\\' . self::class . '::resolveStaticClass(static::class)',
);
}
}
};
}
private function getOriginalFileDir(): string
{
return $this->metadata->uri;
}
}