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

Proposal: Adding previously created objects to existing ones #35

Closed MCStreetguy closed 6 years ago

MCStreetguy commented 6 years ago

Hey there, I currently use this awesome library to regenerate existing classes with some modifications. For this reason I'm often forced to to something like this:

$target = ClassType::from($targetClass);

$methods = $target->getMethods();
$newMethods = [];

foreach ($methods as $method) {
    # do some work
    $newMethods[] = $someNewMethod;
}

$target->setMethods(array_merge($methods, $newMethods));

It would be really nice if it would be possible to directly add existing Method or Property instances to an ClassType instance, instead of using this workaround. Currently it's only possible to create new methods or properties through their respective add...() methods as far as I know. I imagine something like this:

$target = ClassType::from($targetClass);

foreach ($target->getMethods() as $method) {
    # do some work
    $target->addExistingMethod($someNewMethod);
}

Even worse is the process of adding ClassType objects to a PhpFile. For that purpose I had to write a helper method looking like this:

public static function addClassFromTemplate(PhpNamespace &$target, ClassType $tpl): ClassType
{
    return $target->addClass($tpl->getName())
                ->setType($tpl->getType())
                ->setFinal($tpl->isFinal())
                ->setAbstract($tpl->isAbstract())
                ->setExtends($tpl->getExtends())
                ->setImplements($tpl->getImplements())
                ->setTraits($tpl->getTraits())
                ->setConstants($tpl->getConstants())
                ->setProperties($tpl->getProperties())
                ->setMethods($tpl->getMethods())
                ->setComment($tpl->getComment());
}

In this case, it would be even more helpful to add the class with a one-liner. Let me know what you think about my proposal.

Greetings, MCStreetguy