PHPStan, Encrypter and Laravel Packages

I've just come across a rather annoying problem that is down to a relatively specific set of circumstances.

I use the static anaylsis tool PHPStan to check my PHP code. I use the Laravel specific wrapper, developed by nunomaduro, called Larastan which gives me a nice set of defaults.

I have a composer script setup which I use to run the required command;

"stan": [
    "php ./vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=2G"
],

This means I can run a simple command without having to remember all of the parameters. It also keeps running different scripts consistent.

composer run stan

Most of the time, the script works perfectly. It returns errors or success messages without any issues.

Adding encryption causes a problem

I started using Laravel's encryption in the codebase and PHPStan starting giving me an error;

Error: Internal error: No application encryption key has been specified.

It seems this a commonly reported problem and the resolution is to create an .env file with the APP_KEY value set. This is usually a first step when setting up a Laravel application, so the issue should be rarely seen.

However, the codebase is built around the Laravel package set up and this solution didn't help. However, I was able to solve the issue by setting the APP_KEY in the command line script. I generated a new key (php artisan key:generate) and updated the composer script;

"stan": [
    "APP_KEY=base64:xyz php ./vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=2G"
],

Because I had set up a composer script, the command I had to run didn't change and the PHPStan error was resolved.

Solving GrumPHP issues

I also implement GrumPHP. This automates testing when committing code. I have PHPStan enabled using the Grum tasks. Because this is not running through my composer script, I ended up with the same problem.

GrumPHP supports setting environment variables using the config file. I added the APP_KEY to my grumphp.yml file and the script now runs successfully;

grumphp:
    environment:
        variables:
           APP_KEY: base64:xyz