使用PHPSTAN配置VIM ALE插件

I am using ALE for my PHP developing. There is possibility to use phpstan as one of linters, but no matter what I do there is notification that phpstan cannot load class / method definitions:

Function foo not found while trying to analyse it - autoloading is probably not configured properly.

Default configuration of ALE unfortunately does not help, because it expects phpstan to be in $PATH, and even if it is there it still complains about missing autoloading.

This solution is git and composer specific.

I have not found good solution without either any vcs or composer.

So first of all we assume that there is composer being used in project, so there is autoload.php file generated. If you are not using this feature you probably should, because it maps classes to files and makes autoloading simple.

Unfortunately using global phpstan binary is futile. This is because of phpstan looks in current directory for autoload or neon config file that tells it where to look for class definitions. So if you don't want to be forced to open each file in project from root project's directory, then there should be another solution.

Using phpstan binary installed by composer in your project (in vendor/bin/phpstan) solves this problem. Local binary is using the same autoload.php and correctly finds each class definition. So we need to tell ale where phpstan binary is.

Inserting in vimrc file (or better in .vim/ftplugin/php.vim) following line:

let g:ale_php_phpstan_executable = system('if ! type git &> /dev/null; then echo phpstan; else PSE=`git rev-parse --show-toplevel 2> /dev/null`/vendor/bin/phpstan; if [ -x "$PSE" ]; then echo -n $PSE; else echo phpstan; fi; fi')

It tells ALE path to phpstan executable, which is determined by running shell comand.

if ! type git part checks if there is git command in system. If not, then default phpstan text is being returned to variable.

git rev-parse --show-toplevel is trying to find out whether we are in git repository and what is it's top level directory. When found correctly, it determines path to phpstan by adding /vendor/bin/phpstan to top level directory. This is where locally installed phpstan should reside. If there is no such file or it is not executable, then default phpstan variable value is being returned.