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

Automatically import (`use`) classes to namespace #82

Closed ruudk closed 3 years ago

ruudk commented 3 years ago

I'm using this library to generate a lot of PHP classes.

For every returnType, propertyType, argumentType I have to remember to call $namespace->addUse().

It would be really nice if these types could be automatically imported.

For example like this:

$file = new PhpFile();

$ns = $file->addNamespace('My\\App', $autoImport = true);

$class = $ns->addClass('MyClass');

$constructor = $class->addMethod('__construct');

$constructor->addParameter('data')
    ->setType('\My\\App\\Entity\\User');

Would such a change be accepted? Or is there a better way to deal with this?

dg commented 3 years ago

The best solution would probably be to make a helper function that traverses the existing class and calls all addUse() itself. And then it will be up to user whether to use such a function or not.

dg commented 3 years ago
foreach ($file->getNamespaces() as $namespace) {
    foreach ($namespace->getClasses() as $class) {
        $types = [];
        foreach ($class->getMethods() as $method) {
            $types[] = $method->getReturnType(true);
            array_map(function ($param) use (&$types) { $types[] = $param->getType(true); }, $method->getParameters());
        }
        array_map(function ($param) use (&$types) { $types[] = $param->getType(true); }, $class->getProperties());
        foreach (array_filter($types) as $type) {
            foreach ($type->getTypes() as $subtype) {
                if ($subtype->isClass() && !$subtype->isClassKeyword()) {
                    $namespace->addUse((string) $subtype);
                }
            }
        }
    }
}
matronator commented 2 years ago

@dg Will this be implemented in the library, or it just a sample for users to implement themselves?

dg commented 2 years ago

@matronator the sample for users :)