PrettyPrinterAbstract   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 289
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 7
Bugs 2 Features 4
Metric Value
wmc 30
c 7
b 2
f 4
lcom 1
cbo 3
dl 0
loc 289
rs 10

15 Methods

Rating   Name   Duplication   Size   Complexity  
A prettyPrintExpr() 0 3 1
A __construct() 0 6 1
A prettyPrint() 0 5 1
A prettyPrintFile() 0 19 4
A preprocessNodes() 0 9 4
A pStmts() 0 15 4
A p() 0 3 1
A pInfixOp() 0 7 1
A pPrefixOp() 0 4 1
A pPostfixOp() 0 4 1
B pPrec() 0 13 5
A pImplode() 0 8 2
A pCommaSeparated() 0 3 1
A pNoIndent() 0 3 1
A pComments() 0 9 2
1
<?php
2
3
namespace PhpParser;
4
5
use PhpParser\Node\Expr;
6
use PhpParser\Node\Stmt;
7
8
abstract class PrettyPrinterAbstract
9
{
10
    protected $precedenceMap = array(
11
        // [precedence, associativity] where for the latter -1 is %left, 0 is %nonassoc and 1 is %right
12
        'Expr_BinaryOp_Pow'            => array(  0,  1),
13
        'Expr_BitwiseNot'              => array( 10,  1),
14
        'Expr_PreInc'                  => array( 10,  1),
15
        'Expr_PreDec'                  => array( 10,  1),
16
        'Expr_PostInc'                 => array( 10, -1),
17
        'Expr_PostDec'                 => array( 10, -1),
18
        'Expr_UnaryPlus'               => array( 10,  1),
19
        'Expr_UnaryMinus'              => array( 10,  1),
20
        'Expr_Cast_Int'                => array( 10,  1),
21
        'Expr_Cast_Double'             => array( 10,  1),
22
        'Expr_Cast_String'             => array( 10,  1),
23
        'Expr_Cast_Array'              => array( 10,  1),
24
        'Expr_Cast_Object'             => array( 10,  1),
25
        'Expr_Cast_Bool'               => array( 10,  1),
26
        'Expr_Cast_Unset'              => array( 10,  1),
27
        'Expr_ErrorSuppress'           => array( 10,  1),
28
        'Expr_Instanceof'              => array( 20,  0),
29
        'Expr_BooleanNot'              => array( 30,  1),
30
        'Expr_BinaryOp_Mul'            => array( 40, -1),
31
        'Expr_BinaryOp_Div'            => array( 40, -1),
32
        'Expr_BinaryOp_Mod'            => array( 40, -1),
33
        'Expr_BinaryOp_Plus'           => array( 50, -1),
34
        'Expr_BinaryOp_Minus'          => array( 50, -1),
35
        'Expr_BinaryOp_Concat'         => array( 50, -1),
36
        'Expr_BinaryOp_ShiftLeft'      => array( 60, -1),
37
        'Expr_BinaryOp_ShiftRight'     => array( 60, -1),
38
        'Expr_BinaryOp_Smaller'        => array( 70,  0),
39
        'Expr_BinaryOp_SmallerOrEqual' => array( 70,  0),
40
        'Expr_BinaryOp_Greater'        => array( 70,  0),
41
        'Expr_BinaryOp_GreaterOrEqual' => array( 70,  0),
42
        'Expr_BinaryOp_Equal'          => array( 80,  0),
43
        'Expr_BinaryOp_NotEqual'       => array( 80,  0),
44
        'Expr_BinaryOp_Identical'      => array( 80,  0),
45
        'Expr_BinaryOp_NotIdentical'   => array( 80,  0),
46
        'Expr_BinaryOp_Spaceship'      => array( 80,  0),
47
        'Expr_BinaryOp_BitwiseAnd'     => array( 90, -1),
48
        'Expr_BinaryOp_BitwiseXor'     => array(100, -1),
49
        'Expr_BinaryOp_BitwiseOr'      => array(110, -1),
50
        'Expr_BinaryOp_BooleanAnd'     => array(120, -1),
51
        'Expr_BinaryOp_BooleanOr'      => array(130, -1),
52
        'Expr_BinaryOp_Coalesce'       => array(140,  1),
53
        'Expr_Ternary'                 => array(150, -1),
54
        // parser uses %left for assignments, but they really behave as %right
55
        'Expr_Assign'                  => array(160,  1),
56
        'Expr_AssignRef'               => array(160,  1),
57
        'Expr_AssignOp_Plus'           => array(160,  1),
58
        'Expr_AssignOp_Minus'          => array(160,  1),
59
        'Expr_AssignOp_Mul'            => array(160,  1),
60
        'Expr_AssignOp_Div'            => array(160,  1),
61
        'Expr_AssignOp_Concat'         => array(160,  1),
62
        'Expr_AssignOp_Mod'            => array(160,  1),
63
        'Expr_AssignOp_BitwiseAnd'     => array(160,  1),
64
        'Expr_AssignOp_BitwiseOr'      => array(160,  1),
65
        'Expr_AssignOp_BitwiseXor'     => array(160,  1),
66
        'Expr_AssignOp_ShiftLeft'      => array(160,  1),
67
        'Expr_AssignOp_ShiftRight'     => array(160,  1),
68
        'Expr_AssignOp_Pow'            => array(160,  1),
69
        'Expr_YieldFrom'               => array(165,  1),
70
        'Expr_Print'                   => array(168,  1),
71
        'Expr_BinaryOp_LogicalAnd'     => array(170, -1),
72
        'Expr_BinaryOp_LogicalXor'     => array(180, -1),
73
        'Expr_BinaryOp_LogicalOr'      => array(190, -1),
74
        'Expr_Include'                 => array(200, -1),
75
    );
76
77
    protected $noIndentToken;
78
    protected $canUseSemicolonNamespaces;
79
    protected $options;
80
81
    /**
82
     * Creates a pretty printer instance using the given options.
83
     *
84
     * Supported options:
85
     *  * bool $shortArraySyntax = false: Whether to use [] instead of array()
86
     *
87
     * @param array $options Dictionary of formatting options
88
     */
89
    public function __construct(array $options = []) {
90
        $this->noIndentToken = '_NO_INDENT_' . mt_rand();
91
92
        $defaultOptions = ['shortArraySyntax' => false];
93
        $this->options = $options + $defaultOptions;
94
    }
95
96
    /**
97
     * Pretty prints an array of statements.
98
     *
99
     * @param Node[] $stmts Array of statements
100
     *
101
     * @return string Pretty printed statements
102
     */
103
    public function prettyPrint(array $stmts) {
104
        $this->preprocessNodes($stmts);
105
106
        return ltrim(str_replace("\n" . $this->noIndentToken, "\n", $this->pStmts($stmts, false)));
107
    }
108
109
    /**
110
     * Pretty prints an expression.
111
     *
112
     * @param Expr $node Expression node
113
     *
114
     * @return string Pretty printed node
115
     */
116
    public function prettyPrintExpr(Expr $node) {
117
        return str_replace("\n" . $this->noIndentToken, "\n", $this->p($node));
118
    }
119
120
    /**
121
     * Pretty prints a file of statements (includes the opening <?php tag if it is required).
122
     *
123
     * @param Node[] $stmts Array of statements
124
     *
125
     * @return string Pretty printed statements
126
     */
127
    public function prettyPrintFile(array $stmts) {
128
        if (!$stmts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stmts of type PhpParser\Node[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
129
            return "<?php\n\n";
130
        }
131
132
        $p = $this->prettyPrint($stmts);
133
134
        if ($stmts[0] instanceof Stmt\InlineHTML) {
135
            $p = preg_replace('/^\?>\n?/', '', $p);
136
        } else {
137
            $p = "<?php\n\n" . $p;
138
        }
139
140
        if ($stmts[count($stmts) - 1] instanceof Stmt\InlineHTML) {
141
            $p = preg_replace('/<\?php$/', '', rtrim($p));
142
        }
143
144
        return $p;
145
    }
146
147
    /**
148
     * Preprocesses the top-level nodes to initialize pretty printer state.
149
     *
150
     * @param Node[] $nodes Array of nodes
151
     */
152
    protected function preprocessNodes(array $nodes) {
153
        /* We can use semicolon-namespaces unless there is a global namespace declaration */
154
        $this->canUseSemicolonNamespaces = true;
155
        foreach ($nodes as $node) {
156
            if ($node instanceof Stmt\Namespace_ && null === $node->name) {
157
                $this->canUseSemicolonNamespaces = false;
158
            }
159
        }
160
    }
161
162
    /**
163
     * Pretty prints an array of nodes (statements) and indents them optionally.
164
     *
165
     * @param Node[] $nodes  Array of nodes
166
     * @param bool   $indent Whether to indent the printed nodes
167
     *
168
     * @return string Pretty printed statements
169
     */
170
    protected function pStmts(array $nodes, $indent = true) {
171
        $result = '';
172
        foreach ($nodes as $node) {
173
            $result .= "\n"
174
                    . $this->pComments($node->getAttribute('comments', array()))
175
                    . $this->p($node)
176
                    . ($node instanceof Expr ? ';' : '');
177
        }
178
179
        if ($indent) {
180
            return preg_replace('~\n(?!$|' . $this->noIndentToken . ')~', "\n    ", $result);
181
        } else {
182
            return $result;
183
        }
184
    }
185
186
    /**
187
     * Pretty prints a node.
188
     *
189
     * @param Node $node Node to be pretty printed
190
     *
191
     * @return string Pretty printed node
192
     */
193
    protected function p(Node $node) {
194
        return $this->{'p' . $node->getType()}($node);
195
    }
196
197
    protected function pInfixOp($type, Node $leftNode, $operatorString, Node $rightNode) {
198
        list($precedence, $associativity) = $this->precedenceMap[$type];
199
200
        return $this->pPrec($leftNode, $precedence, $associativity, -1)
201
             . $operatorString
202
             . $this->pPrec($rightNode, $precedence, $associativity, 1);
203
    }
204
205
    protected function pPrefixOp($type, $operatorString, Node $node) {
206
        list($precedence, $associativity) = $this->precedenceMap[$type];
207
        return $operatorString . $this->pPrec($node, $precedence, $associativity, 1);
208
    }
209
210
    protected function pPostfixOp($type, Node $node, $operatorString) {
211
        list($precedence, $associativity) = $this->precedenceMap[$type];
212
        return $this->pPrec($node, $precedence, $associativity, -1) . $operatorString;
213
    }
214
215
    /**
216
     * Prints an expression node with the least amount of parentheses necessary to preserve the meaning.
217
     *
218
     * @param Node $node                Node to pretty print
219
     * @param int  $parentPrecedence    Precedence of the parent operator
220
     * @param int  $parentAssociativity Associativity of parent operator
221
     *                                  (-1 is left, 0 is nonassoc, 1 is right)
222
     * @param int  $childPosition       Position of the node relative to the operator
223
     *                                  (-1 is left, 1 is right)
224
     *
225
     * @return string The pretty printed node
226
     */
227
    protected function pPrec(Node $node, $parentPrecedence, $parentAssociativity, $childPosition) {
228
        $type = $node->getType();
229
        if (isset($this->precedenceMap[$type])) {
230
            $childPrecedence = $this->precedenceMap[$type][0];
231
            if ($childPrecedence > $parentPrecedence
232
                || ($parentPrecedence == $childPrecedence && $parentAssociativity != $childPosition)
233
            ) {
234
                return '(' . $this->{'p' . $type}($node) . ')';
235
            }
236
        }
237
238
        return $this->{'p' . $type}($node);
239
    }
240
241
    /**
242
     * Pretty prints an array of nodes and implodes the printed values.
243
     *
244
     * @param Node[] $nodes Array of Nodes to be printed
245
     * @param string $glue  Character to implode with
246
     *
247
     * @return string Imploded pretty printed nodes
248
     */
249
    protected function pImplode(array $nodes, $glue = '') {
250
        $pNodes = array();
251
        foreach ($nodes as $node) {
252
            $pNodes[] = $this->p($node);
253
        }
254
255
        return implode($glue, $pNodes);
256
    }
257
258
    /**
259
     * Pretty prints an array of nodes and implodes the printed values with commas.
260
     *
261
     * @param Node[] $nodes Array of Nodes to be printed
262
     *
263
     * @return string Comma separated pretty printed nodes
264
     */
265
    protected function pCommaSeparated(array $nodes) {
266
        return $this->pImplode($nodes, ', ');
267
    }
268
269
    /**
270
     * Signals the pretty printer that a string shall not be indented.
271
     *
272
     * @param string $string Not to be indented string
273
     *
274
     * @return string String marked with $this->noIndentToken's.
275
     */
276
    protected function pNoIndent($string) {
277
        return str_replace("\n", "\n" . $this->noIndentToken, $string);
278
    }
279
280
    /**
281
     * Prints reformatted text of the passed comments.
282
     *
283
     * @param Comment[] $comments List of comments
284
     *
285
     * @return string Reformatted text of comments
286
     */
287
    protected function pComments(array $comments) {
288
        $result = '';
289
290
        foreach ($comments as $comment) {
291
            $result .= $comment->getReformattedText() . "\n";
292
        }
293
294
        return $result;
295
    }
296
}
297