Tired of template undefined field warnings in PhpStorm?

Code inspection is an awesome feature of PhpStorm. Remember the #gotofail SSL Security Bug? Wouldn’t happen to you with PhpStorm because it warns about unreachable statements. And a lot more.

If however, you get too many warnings, you stop paying attention to them. Especially if you know they’re bogus. One of them is the undefined field warning for template variable assignments in Nette presenter.

Seen this a million times?

Referenced field is not found in subject class.
Note: Check is not performed on objects of type “stdClass” or derived.

Well, here’s what you do. The trick is to make PhpStorm think the template is a stdClass instance.

  1. /**
  2.  * @property-read stdClass $template
  3.  */
  4. abstract class BasePresenter extends Presenter {}
  5.  

Problem solved. But wait, there are cases when you still want your IDE to know it’s a FileTemplate (or what ever you use). The solution is to override the PHPDoc hint locally:

  1. /** @var FileTemplate $template */
  2. $template = $this->template;
  3. $template->setFile($fileName);
  4. $template->setParameters($variables);
  5.  
  6. return $template->__toString();
  7.  

After the first line, you get method hinting and no warnings for FileTemplate methods. Sweet.

Tags:

4 Responses to “Tired of template undefined field warnings in PhpStorm?”

  1. Hello, I personally prefer to specify both types.

    /** @property-read \Nette\Templating\FileTemplate|\stdClass $template */

    With this, undefined properties will not be highlighted but you still get the FileTemplate autocompletion.

  2. Thanks for this tip!

  3. For Nette 2.2 version

    /**
    * @property-read \Nette\Bridges\ApplicationLatte\Template|\stdClass $template
    */

Leave a Reply