Introducing Object Calisthenics Rules for PHPStan

Written by Tomáš Votruba / Original link on Sep. 7, 2020

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
    - 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
        class: Symplify\CodingStandard\ObjectCalisthenics\Rules\NoChainMethodCallRule
        tags: [phpstan.rules.rule]

Rule 6: No Names Shorter than 3 Chars

# phpstan.neon
        class: Symplify\CodingStandard\ObjectCalisthenics\Rules\NoShortNameRule
        tags: [phpstan.rules.rule]
            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!


« Xdebug Update: August 2020 - Refactoring PHP: 4 actionable tips »