nette / php-generator

🐘 Generates neat PHP code for you. Supports new PHP 8.3 features.

Home Page:https://doc.nette.org/php-generator

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Methods with one parameter are printed as multiline if promoted or with attribute

jonsa opened this issue · comments

Version: 4.0.6

Bug Description

A method with a single parameter that is either promoted or has an attribute will have it's signature on multiple lines.

Maybe this is a feature request but the output "looks" wrong to me ☺️. Some might also want the current behaviour, therefor the added configuration flag in the solution suggestion.

Steps To Reproduce

use Nette\PhpGenerator\GlobalFunction;
use Nette\PhpGenerator\PsrPrinter;

$function = new GlobalFunction('foo');
$parameter = $function->addParameter('bar');
$parameter->addAttribute('Baz');

echo (new PsrPrinter())->printFunction($function);

Output

function foo(
    #[Baz] $bar,
) {
}

Expected Behavior

Output to be

function foo(#[Baz] $bar)
{
}

Possible Solution

Change the Printer::printParameters() method to check if it's a single parameter and take it into account when checking promoted and attributed.

class Printer
{
    // ...
    public bool $singleParameterOnOneLine = false; // <-- Added

    protected function printParameters(Closure|GlobalFunction|Method $function, int $column = 0): string
    {
        $params = [];
        $list = $function->getParameters();
        $multiline = false;
        $single = $this->singleParameterOnOneLine && count($list) === 1; // <-- Added

        foreach ($list as $param) {
            // ...

            $multiline = $multiline || (!$single && ($promoted || $attrs)); // <-- Changed
        }

        // ...
    }

    // ...
}

Please send pull request with a test