Skip to content

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

Closed
@jonsa

Description

@jonsa

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
        }

        // ...
    }

    // ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions