简体   繁体   中英

How to provide auto-complete hints for IDEs for dynamic functions?

My specific case revolves around fakerphp/faker , but I imagine the case can be made for other libraries.

If one creates a library with a "provider" for Faker, one basically creates a class with certain methods that return the generated fake data:

namespace Faker\Provider;

class Book extends \Faker\Provider\Base
{
  public function title($nbWords = 5): string
  {
    $sentence = $this->generator->sentence($nbWords);
    return substr($sentence, 0, strlen($sentence) - 1);
  }

  public function ISBN(): string
  {
    return $this->generator->ean13();
  }
}

To add this provider to Faker, one calls $faker->addProvider(new \Faker\Provider\Book($faker)); .

Now comes the issue.

When actually using this new provider methods, one goes through the Faker object, which works as a proxy to the real object by using the magic of __call() .

So when calling $faker->ISBN() , PhpStorm would have no idea that the method ISBN() exists and it returns a string.

Is there a way, via annotations or stubs or whatever, to provide this autocompletions (and maybe even static-analysis hints) when creating a library like this?

You can add a corresponding @var PHPDoc comment above the $faker-> call that would instruct IDE accordingly. Here's an example:

    protected function setUp()
    {
        $faker = new Generator();
        $faker->addProvider(new \Faker\Provider\Book($faker));
        /** @var \Faker\Provider\Book $faker */
        $faker->ISBN();
    }

And here you can see IDE recognizing it correctly: 在此处输入图像描述

Sadly I can't figure out a way to address this in a more elegant way right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM