How to set a type for a variable

I develop Yii2 plugin (PHP) and want to set variables' types for special cases.

For example 
$obj = Yii::createObject(MyClassname::class);

classObject returns Object according to PhpDoc, but in reality return type will be MyClassname.

How could I make Intellij to know that type of $obj is a MyClassname? 

0
6 comments
Official comment

Actually, you don't have to develop a plugin for that. Just create .phpstorm.meta.php file in the root of a project with the following content:

<?php

namespace PHPSTORM_META {
$STATIC_METHOD_TYPES = [
\Yii::createObject() => [
],
];
}

Restart PhpStorm and it should work.

Thanks for info. I will investigate it, looks like it will be very usefull for autocomplete composer package that is on roadmap.


But plugin already exists and we actively develop it. It was just one example and I would like to make it universally from plugin.  It could be sufficient to get a direction, for example classes in the IntelliJ to dig myself.

0

I still believe it's easier to provide this file inside your plugin instead of implementing the same logic using our Java API since our implementation is very optimized and stable. See https://github.com/artspb/phpstorm-library-plugin about the way you can provide PHP files inside a plugin.

If you have any other example that doesn't fit in the scheme feel free to comment.

0

Great, it works. But unfortunatly it does not cover all needed functonality.

For example this does not work (and this is most popular DI call):

$browser = \Yii::createObject([
'class' => Browser::class,
'baseUrl' => "http://google.com",
]);

Is there any chanse to make it work, e.g. IntellijJ/PHPStorm would know the type of $browser without PhpDoc?

0

Sure, you have to implement com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider3 (or what will be the highest version soon).

This is exactly how .phpstorm.meta.php done. It just does not have a way to configure such a mapping pattern that you need. Better to have it in a Laravel plugin.

0

Please sign in to leave a comment.