PHP-Parser icon indicating copy to clipboard operation
PHP-Parser copied to clipboard

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

Open YepYuYu opened this issue 2 years ago • 4 comments

$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'
];

YepYuYu avatar Apr 19 '23 07:04 YepYuYu

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.

WyriHaximus avatar May 02 '23 19:05 WyriHaximus

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.

YepYuYu avatar May 04 '23 10:05 YepYuYu

There is no option for this, but it should be easy to implement your own. Extend the standard pretty printer and override this method: https://github.com/nikic/PHP-Parser/blob/0ffddce52d816f72d0efc4d9b02e276d3309ef01/lib/PhpParser/PrettyPrinter/Standard.php#L582 Rather than pMaybeMultiline call pCommaSeparatedMultiline (possibly behind a check for an attribute, if you don't want to do this for all arrays).

nikic avatar May 04 '23 19:05 nikic

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

Rachad-Alabi-ADEKAMBI avatar Aug 13 '23 16:08 Rachad-Alabi-ADEKAMBI