nette / php-generator

🐘 Generates neat PHP code for you. Supports new PHP 8.3 features.
https://doc.nette.org/php-generator
Other
2.11k stars 138 forks source link

printParameters is not taking into account the rest of the method to determine line length for wrapping #77

Closed Eydamos closed 3 years ago

Eydamos commented 3 years ago

Version: 3.5.2

Bug Description

The method printParameters in the Printer class checks if the length of the arguments is greater than (new Dumper)->wrapLength. But this only checks if the list of parameters exceeds the 120 character limit but ignores the string length of the rest of the method head like the visibility, method name, function keyword and the return type

Steps To Reproduce

Example code:

$file = new PhpFile();
$namespace = $file->addNamespace('Foo');
$class = $namespace->addClass('Bar');
$method = $class->addMethod('baz')
                ->setPublic()
                ->setReturnType('string');
$method->addParameter('lorem')
       ->setType('string');
$method->addParameter('ipsum')
       ->setType('string');
$method->addParameter('dolor')
       ->setType('string');
$method->addParameter('sit')
       ->setType('string');
$method->addParameter('amet')
       ->setType('string');
$method->addParameter('foo')
       ->setType('string');
$method->addParameter('bar')
       ->setType('string');

echo (new PsrPrinter())->printFile($file);

Will print the following:

<?php

namespace Foo;

class Bar
{
    public function baz(string $lorem, string $ipsum, string $dolor, string $sit, string $amet, string $foo, string $bar): string
    {
    }
}

The function baz now has a line length of 130 characters which is too long for PSR2 and PSR12

Expected Behavior

I expect, that the rest of the method head is also taken into account when checking the line length so the following output would be generated which is PSR2 and PSR12 valid:

<?php

namespace Foo;

class Bar
{
    public function baz(
        string $lorem,
        string $ipsum,
        string $dolor,
        string $sit,
        string $amet,
        string $foo,
        string $bar
    ): string {
    }
}
Eydamos commented 3 years ago

First of all thanks for a quick fix. Unfortunately this is still not working correctly. In line 288 of the Printer class you are taking into account the length of public function baz as well as the length of : string and the length of the parameters string $lorem, string $ipsum, string $dolor, string $sit, string $amet, string $foo, string $bar but you are forgetting two things here. First of all you need to add 2 characters for the parenthesis of the parameters as well as 4 spaces for the indention of the function. Later should probably be included in the parameter $column

dg commented 3 years ago

fixed