nikic / PHP-Parser

A PHP parser written in PHP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How can I make each element of the array appear on a separate line?

YepYuYu opened this issue · comments

commented
$array = new Array_();

$array->items = [
    new ArrayItem(new String_('test'), new String_('test0')),
    new ArrayItem(new String_('test'), new String_('test1')),
    new ArrayItem(new String_('test'), new String_('test2')),
    new ArrayItem(new String_('test'), new String_('test3')),
    new ArrayItem(new String_('test'), new String_('test4')),
    new ArrayItem(new String_('test'), new String_('test5')),
    new ArrayItem(new String_('test'), new String_('test6')),
];

$ast = new Expression(new Assign(new Variable('testArray'), $array));
$prettyPrinter = new Standard(['shortArraySyntax' => true]);
echo $prettyPrinter->prettyPrint([$ast]);

The generated code is as follows:

$testArray = ['test0' => 'test', 'test1' => 'test', 'test2' => 'test', 'test3' => 'test', 'test4' => 'test', 'test5' => 'test', 'test6' => 'test'];

The code that I would like to obtain is as follows.

$testArray = [
    'test0' => 'test', 
    'test1' => 'test', 
    'test2' => 'test', 
    'test3' => 'test', 
    'test4' => 'test', 
    'test5' => 'test', 
    'test6' => 'test'
];

Not sure if this is possible, or even part of the scope for this package. But I've been running phpcs over the generated code for any code style and aesthetics of the code.

commented

Not sure if this is possible, or even part of the scope for this package. But I've been running phpcs over the generated code for any code style and aesthetics of the code.

However, phpcs is unable to fulfill many formatting requirements, such as the format requested in this issue, parameter line breaks, and so on.

There is no option for this, but it should be easy to implement your own. Extend the standard pretty printer and override this method:

protected function pExpr_Array(Expr\Array_ $node) {
Rather than pMaybeMultiline call pCommaSeparatedMultiline (possibly behind a check for an attribute, if you don't want to do this for all arrays).

why not do something like this :
echo <br>.$prettyPrinter->prettyPrint([$ast]); ?