Git Product home page Git Product logo

phpcs-cognitive-complexity's Introduction

PHPCS Cognitive Complexity

Make it maintainable or else.

Tests Status Latest Stable Version PHP from Packagist PDS Skeleton

The project implements Cognitive Complexity metric by SonarSource as PHP_CodeSniffer standard.

Install

Composer

composer init --no-interaction
composer require rarst/phpcs-cognitive-complexity squizlabs/php_codesniffer dealerdirect/phpcodesniffer-composer-installer
vendor/bin/phpcs --standard=CognitiveComplexity /path/to/scan

Standalone

git clone https://github.com/Rarst/phpcs-cognitive-complexity
phpcs --standard=phpcs-cognitive-complexity/src/CognitiveComplexity /path/to/scan

Limitations

  • detection of boolean operator chains is not perfect, due to complexity of many possible cases.

Credits

Initial code forked from Symplify Coding Standard.

License

MIT

phpcs-cognitive-complexity's People

Contributors

epic-64 avatar garyjones avatar rarst avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

phpcs-cognitive-complexity's Issues

Case in switch should not increment nesting level

I don't know what this method's cognitive-complexity should be, but I know it shouldn't be 11

public function foo()
{
    $blah = array();
    for ($i = 0, $count = \count($this->things); $i < $count; $i++) {
        switch ($this->things[$i]['method']) {
            case 'foo':
            case 'bar':
                $blah[] = $i;
                break;
            case 'baz':
                \array_pop($blah);
                break;
            case 'ding':
            case 'dong':
                if ($this->something === false) {
                    break;
                }
                foreach ($blah as $i2) {
                    $this->things[$i2]['method'] = 'foo';
                }
                break;
        }
    }
}

9 maybe?
¯\_(ツ)_/¯

do while calculation

sniff calculates this to be 7
codeclimate.com calculates it to be 5 (I think)
I think it should be 6 ??

public function doWhile()
{
    if (true) {         // 1
        $val = true    // 2
            ? 'foo'
            : 'bar';
    }
    do {                   //  nesting inc
        if (true) {        // 2
            break;
        }
    } while (false);    // 1
}

do {} while(); should have the same complexity as a while() {}

If we agree the value should be 6, I can add and new test to my PR

Improve sniff implementation to be code style agnostic

Extracted from #1

Sniff code:

  • $method: you are presuming a code style. Best practice sniffs should be code style agnostic.
    While not very common, this will break on:
public function // some comment
   functionName() {}

Analyzer code:

  • $nextToken in isIncrementingToken() is not code style agnostic.

I am bad with parsers and have no idea how to approach it, so this might take a while. 😅

Create a new tag

Hi there,

Could you please create a new tag for the latest master version?

Feedback on initial setup

Hi @Rarst, as discussed on Slack, please find some initial feedback below:

Note: all current feedback is just and only based on a quick look at the codebase. I haven't run any tests with the repo (yet).

composer.json:

  • Why minimum PHP 7.2 ? Not needed for PHPCS (minimum PHP 5.4) and you're severely limiting the potential public which can use the sniff as people often don't want dev dependencies with a higher minimum PHP version as their own project (and Composer warns against doing that).
  • Please remove the autoload section. This is known to cause issues with PHPCS.
  • PHP_CodeSniffer should be a no-dev requirement, not a dev requirement. Otherwise users may still get an older PHPCS version if they also use other external standards which have a lower minimum PHPCS version.

.gitignore:

  • Please ignore your tests.

Readme:

  • Composer install: You may want to suggest for people to use require --dev as this sniff is normally not a production requirement for other packages.
  • Standalone install:
    • missing instructions on installing PHPCS
    • I'd recommend telling people to set the installed_paths and use the ruleset by name. There are numerous bugs known for when standards are not installed.

Ruleset:

  • You shouldn't need the <autoload> in the ruleset. PHPCS >= 3.1.0 should handle this fine as is. Though maybe not if the standard is not installed... hmm.... well, see my remark above in that case.
  • Don't set properties for your own sniff in the ruleset. Set them as the default property value for the sniff instead (which you already have done).
    And you don't need to include the sniff in the ruleset, all sniffs in the Sniffs directory of a standard will automatically be included.
  • Please add the XSD to the ruleset.
  • You should also set the namespace you are using in the ruleset as it doesn't follow the base pattern expected by PHPCS, so you're breaking the autoloader.
    Have a look at WPCS to see an example.

Sniff code:

  • See above my remark about the namespace. You can use this, but not without setting the namespace in the ruleset. You are currently breaking the build in autoloader from PHPCS.
  • Minor nitpick: you are using non-standard names for the parameters received for process() making the cognitive load for other sniff devs higher (breaks the principle of least astonishment).
  • $method: you are presuming a code style. Best practice sniffs should be code style agnostic.
    While not very common, this will break on:
    public function // some comment
        functionName() {}
  • The PHPCS addError() function already has sprintf() build in, so no need to do it yourself. Just pass the replacements as an array in the fourth parameter.
  • The errorcode should be descriptive and not contain characters which may break in XML. Using self::class is a bad idea as:
    1. It repeats the sniff name (useless).
    2. Is non-descriptive
    3. May break XML.
    4. Makes the sniff error code unnecessarily long.
      I'd suggest using a plain string like TooHigh.
      You could even consider setting two levels, like maxCognitiveComplexity and recommendedCognitiveComplexity, throw an error for the first, a warning for the second and have separate error code for each, like TooHigh and High

Analyzer code:

  • $booleanOperators - you are missing three operators. Please consider using the PHPCS native Tokens::$booleanOperators array instead.
  • $operatorChainBreaks - what about null coalesce ?
  • For performance reasons, set the token arrays with the token constants as keys and use isset() instead of in_array().
  • Again for performance reasons, do a quick check against which tokens you want to handle at the start of the main loop in computeFor...() and continue if not one of your targets.
    You are now also passing whitespace and comment tokens off for processing which is just plain inefficient.
  • $nextToken in isIncrementingToken() is not code style agnostic.

Tests:

  • These are definitely still using the wrong (copied) namespace.

Anyways, hope this helps.

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.