Git Product home page Git Product logo

phpcs-calisthenics-rules's Introduction

Object Calisthenics rules for PHP_CodeSniffer

DEPRECATED: PHP_CodeSniffer is great for handling spaces and char positions. Yet these rules are about code architecture and structure. In 2020, there is tool that suits this perfectly - PHPStan.

Saying that, object calisthenics were implemented as PHPStan rules in a symplify/phpstan-rules package. Use it instead ๐Ÿ‘‡

includes:
    - vendor/symplify/phpstan-rules/packages/object-calisthenics/config/object-calisthenics-rules.neon
    - vendor/symplify/phpstan-rules/packages/object-calisthenics/config/object-calisthenics-services.neon



Downloads

Object Calisthenics are set of rules in object-oriented code, that focuses of maintainability, readability, testability and comprehensibility. We're pragmatic first - they are easy to use all together or one by one.

Why Should You Use This in Your Project?

Read post by William Durand or check presentation by Guilherme Blanco.

Install

composer require object-calisthenics/phpcs-calisthenics-rules --dev

Usage

If you know what you want, jump right to the specific rule:

How to quickly check 1 rule?

In PHP_CodeSniffer

vendor/bin/phpcs src tests -sp \
--standard=vendor/object-calisthenics/phpcs-calisthenics-rules/src/ObjectCalisthenics/ruleset.xml \
--sniffs=ObjectCalisthenics.Classes.ForbiddenPublicProperty

In EasyCodingStandard

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\Classes\ForbiddenPublicPropertySniff: ~

then

vendor/bin/ecs check src

Implemented Rule Sniffs

โŒ

foreach ($sniffGroups as $sniffGroup) {
    foreach ($sniffGroup as $sniffKey => $sniffClass) {
        if (! $sniffClass instanceof Sniff) {
            throw new InvalidClassTypeException;
        }
    }
}

๐Ÿ‘

foreach ($sniffGroups as $sniffGroup) {
    $this->ensureIsAllInstanceOf($sniffGroup, Sniff::class);
}

// ...
private function ensureIsAllInstanceOf(array $objects, string $type)
{
    // ...
}

Use Only This Rule?

In PHP_CodeSniffer:

vendor/bin/phpcs ... --sniffs=ObjectCalisthenics.Metrics.MaxNestingLevel

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\Metrics\MaxNestingLevelSniff: ~

๐Ÿ”ง Configurable

In PHP_CodeSniffer:

<?xml version="1.0"?>
<ruleset name="my-project">
    <rule ref="ObjectCalisthenics.Metrics.MaxNestingLevel">
        <properties>
            <property name="maxNestingLevel" value="2"/>
        </properties>
    </rule>
</ruleset>

In ECS:

services:
    ObjectCalisthenics\Sniffs\Metrics\MaxNestingLevelSniff:
        maxNestingLevel: 2

โŒ

if ($status === self::DONE) {
    $this->finish();
} else {
    $this->advance();
}

๐Ÿ‘

if ($status === self::DONE) {
    $this->finish();
    return;
}

$this->advance();

Use Only This Rule?

In PHP_CodeSniffer:

vendor/bin/phpcs ... --sniffs=ObjectCalisthenics.ControlStructures.NoElse

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\ControlStructures\NoElseSniff: ~

โŒ

$this->container->getBuilder()->addDefinition(SniffRunner::class);

๐Ÿ‘

$containerBuilder = $this->getContainerBuilder();
$containerBuilder->addDefinition(SniffRunner::class);

Use Only This Rule?

In PHP_CodeSniffer:

vendor/bin/phpcs ... --sniffs=ObjectCalisthenics.CodeAnalysis.OneObjectOperatorPerLine

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\CodeAnalysis\OneObjectOperatorPerLineSniff: ~

๐Ÿ”ง Configurable

In PHP_CodeSniffer:

<?xml version="1.0"?>
<ruleset name="my-project">
    <rule ref="ObjectCalisthenics.CodeAnalysis.OneObjectOperatorPerLine">
        <properties>
            <property name="variablesHoldingAFluentInterface" type="array" value="$queryBuilder,$containerBuilder"/>
            <property name="methodsStartingAFluentInterface" type="array" value="createQueryBuilder"/>
            <property name="methodsEndingAFluentInterface" type="array" value="execute,getQuery"/>
        </properties>
    </rule>
</ruleset>

In ECS:

services:
    ObjectCalisthenics\Sniffs\CodeAnalysis\OneObjectOperatorPerLineSniff:
        variablesHoldingAFluentInterface: ["$queryBuilder", "$containerBuilder"]
        methodsStartingAFluentInterface: ["createQueryBuilder"]
        methodsEndingAFluentInterface: ["execute", "getQuery"]

This is related to class, trait, interface, constant, function and variable names.

โŒ

class EM
{
    // ...
}

๐Ÿ‘

class EntityMailer
{
    // ...
}

Use Only This Rule?

In PHP_CodeSniffer:

vendor/bin/phpcs ... --sniffs=ObjectCalisthenics.NamingConventions.ElementNameMinimalLength

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff: ~

๐Ÿ”ง Configurable

In PHP_CodeSniffer:

<?xml version="1.0"?>
<ruleset name="my-project">
    <rule ref="ObjectCalisthenics.NamingConventions.ElementNameMinimalLength">
        <properties>
            <property name="minLength" value="3"/>
            <property name="allowedShortNames" type="array" value="i,id,to,up"/>
        </properties>
    </rule>
</ruleset>

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff:
        minLength: 3
        allowedShortNames: ["i", "id", "to", "up"]

โŒ

class SimpleStartupController
{
    // 300 lines of code
}

๐Ÿ‘

class SimpleStartupController
{
    // 50 lines of code
}

โŒ

class SomeClass
{
    public function simpleLogic()
    {
        // 30 lines of code
    }
}

๐Ÿ‘

class SomeClass
{
    public function simpleLogic()
    {
        // 10 lines of code
    }
}

โŒ

class SomeClass
{
    // 20 properties
}

๐Ÿ‘

class SomeClass
{
    // 5 properties
}

โŒ

class SomeClass
{
    // 20 methods
}

๐Ÿ‘

class SomeClass
{
    // 5 methods
}

Use Only This Rule?

In PHP_CodeSniffer:

vendor/bin/phpcs ... --sniffs=ObjectCalisthenics.Files.ClassTraitAndInterfaceLength,ObjectCalisthenics.Files.FunctionLength,ObjectCalisthenics.Metrics.MethodPerClassLimit,ObjectCalisthenics.Metrics.PropertyPerClassLimit

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\Files\ClassTraitAndInterfaceLengthSniff: ~
    ObjectCalisthenics\Sniffs\Files\FunctionLengthSniff: ~
    ObjectCalisthenics\Sniffs\Metrics\MethodPerClassLimitSniff: ~
    ObjectCalisthenics\Sniffs\Metrics\PropertyPerClassLimitSniff: ~

๐Ÿ”ง Configurable

In PHP_CodeSniffer:

<?xml version="1.0"?>
<ruleset name="my-project">
    <rule ref="ObjectCalisthenics.Files.ClassTraitAndInterfaceLength">
        <properties>
            <property name="maxLength" value="200"/>
        </properties>
    </rule>
    <rule ref="ObjectCalisthenics.Files.FunctionLength">
        <properties>
            <property name="maxLength" value="20"/>
        </properties>
    </rule>
    <rule ref="ObjectCalisthenics.Metrics.PropertyPerClassLimit">
        <properties>
            <property name="maxCount" value="10"/>
        </properties>
    </rule>
    <rule ref="ObjectCalisthenics.Metrics.MethodPerClassLimit">
        <properties>
            <property name="maxCount" value="10"/>
        </properties>
    </rule>
</ruleset>

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\Files\ClassTraitAndInterfaceLengthSniff:
        maxLength: 200
    ObjectCalisthenics\Sniffs\Files\FunctionLengthSniff:
        maxLength: 20
    ObjectCalisthenics\Sniffs\Metrics\PropertyPerClassLimitSniff:
        maxCount: 10
    ObjectCalisthenics\Sniffs\Metrics\MethodPerClassLimitSniff:
        maxCount: 10

This rules is partially related to Domain Driven Design.

  • Classes should not contain public properties.
  • Method should represent behavior, not set values.

โŒ

class ImmutableBankAccount
{
    public $currency = 'USD';
    private $amount;

    public function setAmount(int $amount)
    {
        $this->amount = $amount;
    }
}

๐Ÿ‘

class ImmutableBankAccount
{
    private $currency = 'USD';
    private $amount;

    public function withdrawAmount(int $withdrawnAmount)
    {
        $this->amount -= $withdrawnAmount;
    }
}

Use Only This Rule?

In PHP_CodeSniffer:

vendor/bin/phpcs ... --sniffs=ObjectCalisthenics.Classes.ForbiddenPublicProperty,ObjectCalisthenics.NamingConventions.NoSetter

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\Classes\ForbiddenPublicPropertySniff: ~
    ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff: ~

๐Ÿ”ง Configurable

In PHP_CodeSniffer:

<?xml version="1.0"?>
<ruleset name="my-project">
    <rule ref="ObjectCalisthenics.NamingConventions.NoSetter">
        <properties>
            <property name="allowedClasses" type="array" value="*\DataObject"/>
        </properties>
    </rule>
</ruleset>

In ECS:

# ecs.yaml
services:
    ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff:
        allowedClasses: 
            - '*\DataObject'

Not Implemented Rules - Too Strict, Vague or Annoying

While using in practice, we found these rule to be too strict, vague or even annoying, rather than helping to write cleaner and more pragmatic code. They're also closely related with Domain Driven Design.

3. Wrap Primitive Types and Strings - Since PHP 7, you can use define(strict_types=1) and scalar type hints. For other cases, e.g. email, you can deal with that in your Domain via Value Objects.

4. Use First Class Collections - This rule makes sense, yet is too strict to be useful in practice. Even our code didn't pass it at all.

8. Do Not Use Classes With More Than Two Instance Variables - This depends on individual domain of each project. It doesn't make sense to make a rule for that.


3 Rules for Contributing

  • 1 feature per PR

  • every new feature must be covered by tests

  • all tests and style checks must pass

    composer complete-check

We will be happy to merge your feature then.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.