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

Invalid typehints for nullable properties with union type #72

Closed petr-buchyn closed 3 years ago

petr-buchyn commented 3 years ago

Version: 3.5.1

Bug Description

For now for nullable properties this library generates typehint with ?, but this conflicts with PHP8 Union Types. Generated typehint for union types now looks like ?OneType|OtherType, which is not valid PHP syntax. Could you fix this for PHP8 please?

Possible Solution

Check PHP version and if it's larger than 8.0 - replace ? for |nullin typehint.

dg commented 3 years ago

Show please your code

petr-buchyn commented 3 years ago

Hi @dg !

Sample code to reproduce:


$class = new ClassType('MyClass');
$class
    ->addProperty('foo')
    ->setType('int|string|SomeClass')
    ->setNullable(true);

$printer = new PsrPrinter();
$printer->printClass($class);
petr-buchyn commented 3 years ago

Thanks, @dg ! Not that it is an issue for me, but you also should check, whether the |null is already contained in union type - otherwise there may be a fatal error.

Anyway, thank you very much!

dg commented 3 years ago

I think I'll leave it. So that no one sets setNullable together with setType('...|null')