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

Get different line number for attrGroups and its node

Open samsonasik opened this issue 1 year ago • 4 comments

currently, I can't found a way to verify the same line and different line number of code:

#[AllowDynamicProperties]
class User
{
}

vs

#[AllowDynamicProperties]class User
{
}

the getStartline() is always equal, between attrGroups vs node, so when downgrading, it can't be verified if it needs to be reprint or not, as in php 7, it will require get printed attrGroups and marked as comment attribute.

any way to do it?

samsonasik avatar Nov 23 '24 18:11 samsonasik

A good heuristic would be to check the line of the name. If you want to be pedantic, get the token end position of the last attrgroup and then check whether it's followed by a newline.

nikic avatar Nov 24 '24 17:11 nikic

It seems I can do with:

if (isset($oldTokens[$attrGroup->getEndTokenPos() + 1]) && ! str_contains((string) $oldTokens[$attrGroup->getEndTokenPos() + 1], "\n")) {
    $print = $this->betterStandardPrinter->print($attrGroup);
    $attributesAsComments[] = new Comment($print);
}

then remove attribute, and setAttribute('comment', $attributesAsComments), just wondering if there is a better way.

samsonasik avatar Nov 24 '24 20:11 samsonasik

Looks reasonable to me

nikic avatar Nov 24 '24 20:11 nikic

I found that add new line to next token seems works:

if (isset($oldTokens[$attrGroup->getEndTokenPos() + 1]) && ! str_contains((string) $oldTokens[$attrGroup->getEndTokenPos() + 1], "\n")) {
    // add new line
   $oldTokens[$attrGroup->getEndTokenPos() + 1]->text = "\n" . $oldTokens[$attrGroup->getEndTokenPos() + 1]->text;
}

samsonasik avatar Nov 25 '24 08:11 samsonasik