|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This program is free software. It comes without any warranty, to |
|
4
|
|
|
* the extent permitted by applicable law. You can redistribute it |
|
5
|
|
|
* and/or modify it under the terms of the Do What The Fuck You Want |
|
6
|
|
|
* To Public License, Version 2, as published by Sam Hocevar. See |
|
7
|
|
|
* http://www.wtfpl.net/ for more details. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
declare(strict_types = 1); |
|
11
|
|
|
|
|
12
|
|
|
namespace hanneskod\classtools\Transformer; |
|
13
|
|
|
|
|
14
|
|
|
use PhpParser\NodeTraverser; |
|
15
|
|
|
use PhpParser\NodeVisitor; |
|
16
|
|
|
use PhpParser\Error as PhpParserException; |
|
17
|
|
|
use hanneskod\classtools\Exception\RuntimeException; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Translate and print parsed code snippets |
|
21
|
|
|
* |
|
22
|
|
|
* @author Hannes Forsgård <[email protected]> |
|
23
|
|
|
*/ |
|
24
|
|
|
class Writer |
|
25
|
|
|
{ |
|
26
|
|
|
/** |
|
27
|
|
|
* @var NodeTraverser Traverser used for altering parsed code |
|
28
|
|
|
*/ |
|
29
|
|
|
private $traverser; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @var BracketingPrinter Printer used for printing traversed code |
|
33
|
|
|
*/ |
|
34
|
|
|
private $printer; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Optionally inject dependencies |
|
38
|
|
|
* |
|
39
|
|
|
* Since Reader always makes definitions namespaced a PhpParser printer that |
|
40
|
|
|
* wraps the code in brackeded namespace statements must be used. The current |
|
41
|
|
|
* implementation of this is BracketingPrinter. |
|
42
|
|
|
*/ |
|
43
|
|
|
public function __construct(NodeTraverser $traverser = null, BracketingPrinter $printer = null) |
|
44
|
|
|
{ |
|
45
|
|
|
$this->traverser = $traverser ?: new NodeTraverser; |
|
46
|
|
|
$this->printer = $printer ?: new BracketingPrinter; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Apply translation to alter code |
|
51
|
|
|
*/ |
|
52
|
|
|
public function apply(NodeVisitor $translation): self |
|
53
|
|
|
{ |
|
54
|
|
|
$this->traverser->addVisitor($translation); |
|
55
|
|
|
return $this; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Generate new code snippet |
|
60
|
|
|
* |
|
61
|
|
|
* @throws RuntimeException If code generation failes |
|
62
|
|
|
*/ |
|
63
|
|
|
public function write(array $statements): string |
|
64
|
|
|
{ |
|
65
|
|
|
try { |
|
66
|
|
|
return $this->printer->prettyPrint( |
|
67
|
|
|
$this->traverser->traverse( |
|
68
|
|
|
$statements |
|
69
|
|
|
) |
|
70
|
|
|
); |
|
71
|
|
|
} catch (PhpParserException $e) { |
|
72
|
|
|
throw new RuntimeException("Error generating code: {$e->getMessage()}", 0, $e); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|