Introducing Object Calisthenics Rules for PHPStan

For the last 2 years, I've maintained Object Calisthenics Rules for PHP_CodeSniffer. In 2019 and 2020, there was a huge boom of custom PHPStan rulesets that make everyday development easier and stronger at the same time.

Have you been waiting to put these rules into your phpstan.neon?

Today you can!

Object Calisthenics is about SOLID rules and code architecture more than spaces and bracket positions, maybe PHPStan and AST are better to handle it?


What is Object Calis...?

Oh wait, it's the first time you hear Object Calisthenics?

Don't worry. It's not a physical sport that is required to become a better developer. You read about all 9 rules or listen to 12-min audio in Object Calisthenics post by William Durand or check colorful slides by Guilherme Blanco, the former maintainer PHP_CodeSniffer set package.

Some of the rules are rather theoretical to entertain the mind, but some can be measured. And what can be measured, can be automated. What rules can you check in your CI?

Introducing PHPStan Rules

You can add all of the rules above as a PHPStan ruleset. I've ported these rules to symplify/coding-standard in the last 2 days.

composer require symplify/coding-standard --dev

And update phpstan.neon:

# phsptan.neon
includes:
    - vendor/symplify/coding-standard/packages/object-calisthenics/config/object-calisthenics-rules.neon

As you can see, their rules are pretty strict, and in practice, that might be impossible to put on a real project. It's better to start slowly with low hanging fruit rules. Like these 2:

Rule 5: No Chain Method Call

# phpstan.neon
services:
    -
        class: Symplify\CodingStandard\ObjectCalisthenics\Rules\NoChainMethodCallRule
        tags: [phpstan.rules.rule]

Rule 6: No Names Shorter than 3 Chars

# phpstan.neon
services:
    -
        class: Symplify\CodingStandard\ObjectCalisthenics\Rules\NoShortNameRule
        tags: [phpstan.rules.rule]
        arguments:
            minNameLenght: 3
            allowedShortNames: ['id', 'to', 'up']

And you're ready to go!

How to Switch from PHP_CodeSniffer to PHPStan rules?

Most likely, you're not using all the rules at once, so we look at migrating particular rules.

Good luck and have fun.


Happy coding!