Make phpstan work with ctp files

We are using phpstan to detect and fix some common errors. This tool works fine with plain PHP files or classes, but not with ctp files. This is our phpstan.neon config file:

parameters:
    fileExtensions:
      - php
      - ctp

But if we analyze a ctp file, we get errors like this:

$ phpstan analyze --level 0 src/Template/xxx/info.ctp
Note: Using configuration file xxx/phpstan.neon.
 1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ -------------------------------
  Line
 ------ -------------------------------
  7      Undefined variable: $this
  7      Using $this outside a class.
  42     Undefined variable: $authUser
  47     Undefined variable: $authUser
  52     Undefined variable: $authUser
  57     Undefined variable: $authUser
 ------ -------------------------------

 [ERROR] Found 6 errors

Does anyone know a configuration to make this work?

Looks like phpstan supports docblocks, so use something like this at the top of your ctp files:

/**
 * @var View $this
 * @var string $authUser
 */

It’s a lot of work to add them all, but you also get the added bonus of autocomplete when editing the files, if your editor supports that.

1 Like

After some more research, it looks that phpstan doesn’t work well with that kind of annotations: https://github.com/phpstan/phpstan/issues/351. Anayway, thanks for the response; it is useful for editors.

That’s a shame. Worse, it looks like the author does not see any value in adding that support.

PHPStan works quite well for us, and for CakePHP core development. You can use https://github.com/dereuromark/cakephp-ide-helper to make the changes automatically for you.

Hi @dakota, do you also validate ctp files? The problem is with that kind of files and the variable $this.

I wouldn’t suggest trying to use phpstan for .ctp files. The template files are basically php code fragments which are included inside View class. So by themselves they don’t have enough context available for phpstan to do it’s job. You’ll have to go about adding annotations like /** @var FooType $bar */ throughout the template files.

Yes, I know this limitation of phpstan… Does anyone use any static analyzer for ctp files that respect that kind of annotations? I am reviewing the alternatives mentioned here https://www.reddit.com/r/PHP/comments/5uy9fw/php_static_analysis_tool_discover_bugs_in_your/ but I would like to know your opinions.

phpstan supports annotations just fine.