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

Add traits and don't import their methods #89

Closed mikepsinn closed 3 years ago

mikepsinn commented 3 years ago

Previously the factory wasn't importing used traits from existing classes

dg commented 3 years ago

Actually, this is a much more complicated task. PHP doesn't have sufficient API to detect if a method is defined in the trait (getMethodDeclaringMethod() just tries to guess) and how is resolved, like:

class Aliased_Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as talk;
    }
}

I'll add switch whether to import traits or not, and leave it up to the user, because it's hard to do it perfectly.

mikepsinn commented 3 years ago

@dg Yeah, it's a tough one. The only flaw I observed in my code is that it still imports static properties from the traits. I couldn't really figure out a way around that, yet. But the static properties are easy to delete and at least it doesn't import a million trait functions.

Thanks for adding that option for me and for your amazing work and generosity on this project! :D

dg commented 3 years ago

That's odd, I tried adding a test to it and the static variables seem to work correctly:

https://github.com/nette/php-generator/blob/master/tests/PhpGenerator/expected/ClassType.from.trait-use.expect#L6