ClassType->getNamespace() should not be deprecated
riki137 opened this issue · comments
I can't find a substitution for this piece of code without using the getNamespace()
method:
$class = ClassType::from($myClass, true);
$namespace = $class->getNamespace();
$namespace->addUse(DateTimeInterface::class);
Alternative method should at least be mentioned in documention.
To create a new class, I create the PhpNamespace
first.
$namespace = new PhpNamespace('Testing');
$namespace->addUse(\DateTimeInterface::class);
$class = $namespace->addClass('Test');
To create from existing, you can import the PhpFile
.
$file = PhpFile::fromCode(file_get_contents('src/'.str_replace('\\', '/', $myClass).'.php));
$namespace = $file->getNamespaces()[0];
$class = $namespace->getClasses()[0];
$namespace->addUse(DateTimeInterface::class);
@GromNaN No, i want to use ClassType::from, not PhpFile::fromCode, and also I'd like to avoid [0] when I can be sure that one class will always have one or no namespace.
What do you do with the $class
or $namespace
variables after adding the use
? Do you save the file again?
Ok, let's forget about getting rid of ClassType::from. (but it makes me cry)
If i use $namespace = $file->getNamespaces()[0];
i don't really have a guarantee that the namespace is the namespace of the class, and that the class is the class i want (in case there would be multiple classes and namespaces in the file). I really wouldn't like to manually check this every time i use it.
Also, using [0] indexes makes for a code that is way harder to statically analyze.
I'd have to add some type checks and that would make my code harder to read.
I really don't see the benefit of removing this method. It makes things so much harder for my use case.
Seconded, I can't see how I would achieve what I do in the following code easily. It would require way more complexity, passing around the namespace with the ClassType
object perhaps?