All Projects → object-calisthenics → Phpcs Calisthenics Rules

object-calisthenics / Phpcs Calisthenics Rules

Licence: mit
Object Calisthenics rules for PHP_CodeSniffer

Projects that are alternatives of or similar to Phpcs Calisthenics Rules

php-codesniffer-sniffs
Custom sniffs for PHP_CodeSniffer
Stars: ✭ 16 (-97.36%)
Mutual labels:  static-analysis, php-codesniffer
phpcs-psr4-sniff
[READ-ONLY] PHP_CodeSniffer sniff that checks class name matches PSR-4 project structure.
Stars: ✭ 23 (-96.2%)
Mutual labels:  static-analysis, php-codesniffer
Phpqa
Docker image that provides static analysis tools for PHP
Stars: ✭ 853 (+40.99%)
Mutual labels:  static-analysis, php-codesniffer
codeclimate-phpcodesniffer
Code Climate Engine for PHP Code Sniffer
Stars: ✭ 27 (-95.54%)
Mutual labels:  static-analysis, php-codesniffer
Security Code Scan
Vulnerability Patterns Detector for C# and VB.NET
Stars: ✭ 550 (-9.09%)
Mutual labels:  static-analysis
Cmake Examples
Useful CMake Examples
Stars: ✭ 7,220 (+1093.39%)
Mutual labels:  static-analysis
Phpat
PHP Architecture Tester - Easy to use architectural testing tool for PHP ✔️
Stars: ✭ 489 (-19.17%)
Mutual labels:  static-analysis
Sark
IDAPython Made Easy
Stars: ✭ 477 (-21.16%)
Mutual labels:  static-analysis
Pyre Check
Performant type-checking for python.
Stars: ✭ 5,716 (+844.79%)
Mutual labels:  static-analysis
Phan
Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.
Stars: ✭ 5,194 (+758.51%)
Mutual labels:  static-analysis
Pep8speaks
A GitHub app to automatically review Python code style over Pull Requests
Stars: ✭ 546 (-9.75%)
Mutual labels:  static-analysis
Security Tools
Collection of small security tools, mostly in Bash and Python. CTFs, Bug Bounty and other stuff.
Stars: ✭ 509 (-15.87%)
Mutual labels:  static-analysis
Jsprime
a javascript static security analysis tool
Stars: ✭ 556 (-8.1%)
Mutual labels:  static-analysis
Phasar
A LLVM-based static analysis framework.
Stars: ✭ 503 (-16.86%)
Mutual labels:  static-analysis
Dokieli
💡 dokieli is a clientside editor for decentralised article publishing, annotations and social interactions
Stars: ✭ 582 (-3.8%)
Mutual labels:  solid
Elsa
Emacs Lisp Static Analyzer
Stars: ✭ 485 (-19.83%)
Mutual labels:  static-analysis
Lazy importer
library for importing functions from dlls in a hidden, reverse engineer unfriendly way
Stars: ✭ 544 (-10.08%)
Mutual labels:  static-analysis
Hadolint
Dockerfile linter, validate inline bash, written in Haskell
Stars: ✭ 6,284 (+938.68%)
Mutual labels:  static-analysis
Svf
Static Value-Flow Analysis Framework for Source Code
Stars: ✭ 540 (-10.74%)
Mutual labels:  static-analysis
Jedi
Awesome autocompletion, static analysis and refactoring library for python
Stars: ✭ 5,037 (+732.56%)
Mutual labels:  static-analysis

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/coding-standard package. Use it instead.




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

1. Only X Level of Indentation per Method

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

2. Do Not Use "else" Keyword

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: ~

5. Use Only One Object Operator (->) per Statement

$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"]

6. Do not Abbreviate

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"]

7. Keep Your Classes Small

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

9. Do not Use Getters and Setters

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].