Search code examples
genericsphpstormphpdoctype-hinting

PhpStorm completion, type hint generic


I would love to find a way (if that's even possible?) for PhpStorm to auto complete code generated by my Factory class without having to write a PHPDoc every time I pull a class from it.

Here is my code:

<?php
class Factory
{
    public function getManager(string $class)
    {
        // if in cache ... returns

        // not in cache > init
        $manager = new $class();
        $this->doStuff($manager);
        return $manager;
    }

    public function doStuff($manager) {}
}

$factory = new Factory();
/** @var DateTime $dtClass */
$dtClass = $factory->getManager(DateTime::class);
$dtClass->getTimestamp();

So in order to autocomplete & silence PhpStorm warnings I've to add that line after each getManager() calls with the corresponding class.

/** @var DateTime $dtClass */

I was wondering if a PHPDoc, a PhpStorm helper file or anything could help doing that?

    /**
     * @template T
     * @param string $class <T>
     * @return <T>
     */
    public function getManager(string $class)
    { 

Solution

  • Oh My god ! thank you so much @LazyOne 🎉

    I can't believe that only 10lines of code could save me so much time

    So here is a quick round up. Just create a folder .phpstorm.meta.php at the root of your project. Inside create a manager.meta.php Containing just:

    <?php
    
    namespace PHPSTORM_META {
        override(
            \Factory::getManager(0),
            map([
                '' => '@',
            ])
        );
    }
    

    Et voilà !