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

Attributes cant have 0 as parameter #140

Closed 19bischof closed 1 year ago

19bischof commented 1 year ago

Version: ?.?.?

Bug Description

When adding an Attribute with the single parameter 0 like so $property->addAttribute(MyAttribute::class,[0]) it would result in the parameter not being printed. That happens because in the Printer.php the following code checks whether the params evaluate to true or false to then print the parenthesis and the params

protected function printAttributes(array $attrs, bool $inline = false): string
    {
        if (!$attrs) {
            return '';
        }
        $this->dumper->indentation = $this->indentation;
        $items = [];
        foreach ($attrs as $attr) {
            $args = $this->dumper->format('...?:', $attr->getArguments());
            $args = Helpers::simplifyTaggedNames($args, $this->namespace);
            $items[] = $this->printType($attr->getName(), nullable: false) . ($args ? "($args)" : ''); //this one right here (in my case $args would be "0" and therefore evaluates to false
            $inline = $inline && !str_contains($args, "\n");
        }

        return $inline
            ? '#[' . implode(', ', $items) . '] '
            : '#[' . implode("]\n#[", $items) . "]\n";
    }

Expected Behavior

... That when you give as parameters an array with a 0, that it also prints a 0 as a parameter

Possible Solution

... instead of checking whether the $args string evaluates to true, check if the string is empty like ($args !== '' ? "($args)" : '')

dg commented 1 year ago

Can you please send a PR with a simple test?