Add ability to define trait import PHPDoc
InvisibleSmiley opened this issue · comments
In order to use generic traits with current versions of PHPStan, PHPDoc with @use must be added to trait imports (use).
AFAICS this generator is currently unable to define PHPDoc comments for trait imports.
FTR the feature was added to PHPStan here:
phpstan/phpstan-src@8766923
Can you describe it better?
Example code:
<?php
$namespace = new \Nette\PhpGenerator\PhpNamespace('Foo');
$class = $namespace->addClass('Bar')->addTrait('SomeTrait');
$file = new \Nette\PhpGenerator\PhpFile();
$file->addNamespace($namespace);
echo (new \Nette\PhpGenerator\Printer())->printFile($file);
Result:
<?php
namespace Foo;
class Bar
{
use \SomeTrait;
}
Desired result:
<?php
namespace Foo;
class Bar
{
/** @use \SomeTrait<\Carbon\CarbonImmutable> */
use \SomeTrait;
}
Trait for use case:
<?php
/** @template T of \DateTimeInterface */
trait SomeTrait
{
/** @return T */
public function createDate(): \DateTimeInterface
{
return \Carbon\CarbonImmutable::now();
}
}
The ideal would be something like
$namespace->addClass('Bar')
->addTrait('SomeTrait')
->addComment('@use \SomeTrait<\Carbon\CarbonImmutable>');
but addTrait()
returns static
and to change that would be a big BC break…
Maybe add a new method useTrait()
...
I'd rather say adapt addTrait to accept either a string (behavior like now) or a class that wraps the name and PHPDoc, like so:
$trait = new PhpTrait('SomeTrait')->addComment('@use \SomeTrait<\Carbon\CarbonImmutable>');
$namespace->addClass('Bar')->addTrait($someTrait);
It's working now. I added the true
parameter and then it returns the TraitUse
object:
$namespace->addClass('Bar')
->addTrait('SomeTrait', true)
->addComment('@use \SomeTrait<\Carbon\CarbonImmutable>');