Git Product home page Git Product logo

codeclimate-phpcodesniffer's Introduction

Code Climate PHP_CodeSniffer Engine

Code Climate

codeclimate-phpcodesniffer is a Code Climate engine that wraps the PHP_Code Sniffer static analysis tool. You can run it on your command line using the Code Climate CLI, or on our hosted analysis platform.

PHP_CodeSniffer helps you detect violations of a defined coding standard.

Installation

  1. If you haven't already, install the Code Climate CLI.
  2. Run codeclimate engines:enable phpcodesniffer. This command both installs the engine and enables it in your .codeclimate.yml file.
  3. You're ready to analyze! Browse into your project's folder and run codeclimate analyze.

Config Options

Format the values for these config options per the PHP_CodeSniffer documentation.

  • file_extensions - This is where you can configure the file extensions for the files that you want PHP_CodeSniffer to analyze.
  • standard - This is the comma delimited list of standards that you want PHP_CodeSniffer to use while analyzing your files. You may optionally include a relative path to a custom phpcs ruleset.xml file.
  • ignore_warnings - You can hide warnings, and only report errors with this option.
  • encoding - By default, PHPCS uses ISO-8859-1. Use this to change it to your encoding, e.g. UTF-8.

Sample Config

exclude_paths:
 - "/examples/**/*"
engines:
  phpcodesniffer:
    enabled: true
    config:
      file_extensions: "php,inc,lib"
      standard: "PSR1,PSR2,my_custom_php_ruleset.xml"
      ignore_warnings: true
      encoding: utf-8
ratings:
  paths:
  - "**.php"

Supported Coding Standards

In addition to standards provided by default with PHP_CodeSniffer, the Drupal, WordPress, Yii2, and Magento Extension coding standards are supported. Here is the full list:

  • Drupal
  • DrupalPractice
  • MEQP1
  • MEQP2
  • MySource
  • PEAR
  • PHPCS
  • PSR1
  • PSR2
  • Squiz
  • WordPress
  • WordPress-Core
  • WordPress-Docs
  • WordPress-Extra
  • WordPress-VIP
  • Yii2
  • Zend

Need help?

For help with PHP_CodeSniffer, check out their documentation.

If you're running into a Code Climate issue, first look over this project's GitHub Issues, as your question may have already been covered. If not, go ahead and open a support ticket with us.

codeclimate-phpcodesniffer's People

Contributors

ablyler avatar anton-kachurin avatar blakewilliams avatar brynary avatar dantevvp avatar davidfricker avatar dblandin avatar desrosj avatar e3betht avatar fede-moya avatar gdiggs avatar josephdpurcell avatar jpignata avatar landrok avatar larkinscott avatar leftees avatar maxjacobson avatar mxie avatar noahd1 avatar paracycle avatar pointlessone avatar wfleming 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  avatar  avatar  avatar

Watchers

 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

codeclimate-phpcodesniffer's Issues

ReturnTypeWillChange attribute triggers error, false positive

#[\ReturnTypeWillChange] is an attribute added in PHP 8.1, which "signals that a mismatching tentative return type should not emit a deprecation notice". In my local environment, this is not throwing any errors in PHPCS, but CodeClimate reports it as an error:

image

The actual attribute can't be seen there, but the code being checked looks like this:

  /**
   * {@inheritDoc}
   */
  #[\ReturnTypeWillChange]
  public function jsonSerialize() {

Generic.WhiteSpace.ArbitraryParenthesesSpacing missing?

Hi!

I'm getting

D, [2019-03-07T06:00:32.603960 #1] DEBUG -- : engine stderr: Exception: Referenced sniff "Generic.WhiteSpace.ArbitraryParenthesesSpacing" does not exist in /usr/src/app/vendor/squizlabs/php_codesniffer/CodeSniffer.php

When running from the codeclimate CLI. This sniff is clearly referenced in the PHPCS docs here, and I can run it via the phpcs binary.

What could be happening here?

Thanks!

Support for Drupal PHP coding standards

Drupal code standards include sniffs compatible with PHP Code Sniffer as part of the Coder library: https://www.drupal.org/project/coder

It would make it easier for Drupal projects to adopt Code Climate by not requiring those sniffs to be added in each project, but rather added within the Code Climate engine.

This issue is similar to the request for supporting WordPress code standards: #15

Allow a user to choose the phpcs version

With phpcs 3.0+ rules not being compatible with 2.9 and below rule sets we need a way to tell codeclimate which version it should be running tests with. This is especially important when we are using custom sniffs. I believe some of the other plugins/engines allow selecting versions so it should be doable in a similar fashion I would hope.

Analyze not working with custom sniffs

It seems that when custom sniffs are present, everything in the ruleset will be ignored, including the custom sniffs themselves, and phpcodesniffer will just report everything as having passed.

Codeclimate cli version: 0.71.1

My .codeclimate.yml file

version: "2"

plugins:
  phpcodesniffer:
    enabled: true
    config:
      file_extensions: "php"
      standard: "./standards/phpcs/ruleset.xml"

And ./standards/phpcs/ruleset.xml

<?xml version="1.0"?>
<ruleset name="MyStandard">
    <description>Coding Standard.</description>
    <rule ref="PSR2"/>
</ruleset>

I then make some purposeful mistakes in some code that violate PSR2, and run

codeclimate analyze

It will correctly report the issues according to PSR2.

Now, when I add some custom Sniffs, just the mere presence of them will cause everything to pass.

For example, a completely empty sniff

<?php

namespace PHP_CodeSniffer\Standards\MyStandard\Sniffs;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;

class MyCustomSniff implements Sniff
{
    public function register()
    {
        return [];
    }

    public function process(File $phpcsFile, $stackPtr)
    {
    }
}

Now when

codeclimate analyze

is run, everything will report as passed, and the PSR2 enforcements are completely ignored.

Engine flags issues under .git

There seems to be a "this is not a PHP file" check and it's generating issues for files under .git. This 1) doesn't make sense and 2) causes problems when we attempt to render these issues on the site.

Ability to specify which version of code standard

Problem

I can imagine scenarios where a code standard gets updated by Code Climate and someone's repository has their GPA downgraded (or upgraded).

I can also imagine where someone wants to add a custom code style check that isn't officially supported by Code Climate

Proposed Resolution

  1. Add the ability to specify specific versions of a code standard (this version would map to a version that composer understands).
  2. Add the ability to specify a custom package from packagist.org to use as a code standard.

php7-xmlreader required for WordPress Coding Standards beta container image

I've tried using the beta docker image of codeclimate-phpcodesniffer to get access to a more recent phpcs build than is in stable. (I need access to disabling specific sniffs on a single line as documented at https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#ignoring-parts-of-a-file. The inline // phpcs:ignore form is only available in phpcs since version 3.2.0, where the stable docker image by codeclimate is still on 2.9.1.

When I run the beta docker image I am greeted with the following log showing that the container is missing the php7-xmlreader package from the Alpine repository.

Log of execution
$ docker run   --interactive --tty --rm   --env CODECLIMATE_CODE="$PWD"   --volume "$PWD":/code   --volume /var/run/docker.sock:/var/run/docker.sock   --volume /tmp/cc:/tmp/cc   codeclimate/codeclimate analyze -e phpcodesniffer
Starting analysis
Running phpcodesniffer: Done!
error: (CC::CLI::Analyze::EngineFailure) engine phpcodesniffer failed with status 1 and stderr
Unable to find image 'codeclimate/codeclimate-phpcodesniffer:beta' locally
beta: Pulling from codeclimate/codeclimate-phpcodesniffer
5758d4e389a3: Already exists
4ae1f45a9f69: Pulling fs layer
0676d8c6ca5f: Pulling fs layer
5dd9411e7f0f: Pulling fs layer
c0105a21377e: Pulling fs layer
7072198dee72: Pulling fs layer
119f7d69fd65: Pulling fs layer
f4466a97c155: Pulling fs layer
b5fd0274c371: Pulling fs layer
c0105a21377e: Waiting
7072198dee72: Waiting
119f7d69fd65: Waiting
f4466a97c155: Waiting
b5fd0274c371: Waiting
0676d8c6ca5f: Download complete
4ae1f45a9f69: Verifying Checksum
4ae1f45a9f69: Download complete
4ae1f45a9f69: Pull complete
0676d8c6ca5f: Pull complete
5dd9411e7f0f: Verifying Checksum
5dd9411e7f0f: Download complete
5dd9411e7f0f: Pull complete
7072198dee72: Download complete
c0105a21377e: Download complete
c0105a21377e: Pull complete
7072198dee72: Pull complete
f4466a97c155: Verifying Checksum
f4466a97c155: Download complete
b5fd0274c371: Verifying Checksum
b5fd0274c371: Download complete
119f7d69fd65: Verifying Checksum
119f7d69fd65: Download complete
119f7d69fd65: Pull complete
f4466a97c155: Pull complete
b5fd0274c371: Pull complete
Digest: sha256:670d7b4e245222e6735ccc29b7548baffd053dd9f267fbb0f0448af08d46feae
Status: Downloaded newer image for codeclimate/codeclimate-phpcodesniffer:beta
Exception: Class 'XMLReader' not found in /usr/src/app/vendor/wp-coding-standards/wpcs/WordPress/Sniffs/WP/I18nSniff.php
#0 /usr/src/app/vendor/wp-coding-standards/wpcs/WordPress/Sniffs/WP/I18nSniff.php(464): WordPressCS\WordPress\Sniffs\WP\I18nSniff->check_text()
#1 /usr/src/app/vendor/wp-coding-standards/wpcs/WordPress/Sniffs/WP/I18nSniff.php(390): WordPressCS\WordPress\Sniffs\WP\I18nSniff->check_argument_tokens()
#2 /usr/src/app/vendor/wp-coding-standards/wpcs/WordPress/AbstractFunctionRestrictionsSniff.php(288): WordPressCS\WordPress\Sniffs\WP\I18nSniff->process_matched_token()
#3 /usr/src/app/vendor/wp-coding-standards/wpcs/WordPress/AbstractFunctionRestrictionsSniff.php(200): WordPressCS\WordPress\AbstractFunctionRestrictionsSniff->check_for_matches()
#4 /usr/src/app/vendor/wp-coding-standards/wpcs/WordPress/Sniffs/WP/I18nSniff.php(213): WordPressCS\WordPress\AbstractFunctionRestrictionsSniff->process_token()
#5 /usr/src/app/vendor/wp-coding-standards/wpcs/WordPress/Sniff.php(910): WordPressCS\WordPress\Sniffs\WP\I18nSniff->process_token()
#6 /usr/src/app/vendor/squizlabs/php_codesniffer/src/Files/File.php(498): WordPressCS\WordPress\Sniff->process()
#7 /usr/src/app/vendor/squizlabs/php_codesniffer/src/Runner.php(631): PHP_CodeSniffer\Files\File->process()
#8 /usr/src/app/Executor.php(124): PHP_CodeSniffer\Runner->processFile()
#9 /usr/src/app/vendor/barracudanetworks/forkdaemon-php/fork_daemon.php(1934): Executor->run()
#10 /usr/src/app/vendor/barracudanetworks/forkdaemon-php/fork_daemon.php(1846): fork_daemon->invoke_callback()
#11 /usr/src/app/vendor/barracudanetworks/forkdaemon-php/fork_daemon.php(1747): fork_daemon->fork_work_unit()
#12 /usr/src/app/vendor/barracudanetworks/forkdaemon-php/fork_daemon.php(1499): fork_daemon->process_work_unit()
#13 /usr/src/app/Executor.php(33): fork_daemon->process_work()
#14 /usr/src/app/engine.php(26): Executor->queueDirectory()
#15 {main}
My `.codeclimate` file
plugins:
  editorconfig:
    enabled: true
  fixme:
    enabled: true
  git-legal:
    enabled: true
  phpcodesniffer:
    enabled: true
    channel: beta
    config:
      standard: phpcs.xml.dist
  scss-lint:
    enabled: true
My `.phpcs.dist.xml` file
<?xml version="1.0"?>
<ruleset name="WordPress Coding Standards for Plugins">
	<description>Generally-applicable sniffs for WordPress plugins</description>

	<!-- What to scan -->
	<file>.</file>

	<!-- Exclude built assets -->
	<exclude-pattern>/build/</exclude-pattern>

    <!-- Exclude node_modules -->
    <exclude-pattern>*/node_modules/*</exclude-pattern>

	<!-- Exclude tests -->
	<exclude-pattern>/tests/</exclude-pattern>
    <!-- Exclude vendor directories -->
    <exclude-pattern>*/vendor/*</exclude-pattern>

	<exclude-pattern>/wp-includes</exclude-pattern>
	<exclude-pattern>scoper.inc.php</exclude-pattern>

    <!-- Colors! Nice! -->
    <arg name="colors"/>

    <!--- Only check PHP files -->
    <arg name="extensions" value="php"/>

    <!-- Commandline options for PHPCS -->
    <arg value="s"/>
    <arg value="n"/>

	<!-- Rules: Check PHP version compatibility -->
	<!-- https://github.com/PHPCompatibility/PHPCompatibility#sniffing-your-code-for-compatibility-with-specific-php-versions -->
	<!-- <config name="testVersion" value="7.0-"/> -->
	<!-- https://github.com/PHPCompatibility/PHPCompatibilityWP -->
	<!-- <rule ref="PHPCompatibilityWP"/> -->

	<rule ref="Squiz.PHP.Eval"/>

	<!-- Rules: WordPress Coding Standards -->
	<!-- https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards -->
	<!-- https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/wiki/Customizable-sniff-properties -->
	<config name="minimum_supported_wp_version" value="5.0"/>
	<rule ref="WordPress">
		<exclude name="WordPress.Files.FileName.InvalidClassFileName"/>
		<exclude name="WordPress.Files.FileName.NotHyphenatedLowercase"/>
	</rule>
	<rule ref="WordPress-Docs" />
	<rule ref="WordPress.NamingConventions.PrefixAllGlobals">
		<properties>
			<!-- Value: replace the function, class, and variable prefixes used. Separate multiple prefixes with a comma. -->
			<property name="prefixes" type="array" value="a_z_listing,the_a_z_listing,have_a_z_,get_the_a_z,get_the_az,the_a_z,the_az"/>
		</properties>
	</rule>
	<rule ref="WordPress.WP.I18n">
		<properties>
			<!-- Value: replace the text domain used. -->
			<property name="text_domain" type="array" value="a-z-listing"/>
		</properties>
	</rule>
	<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
		<properties>
			<property name="blank_line_check" value="true"/>
		</properties>
	</rule>
	<rule ref="WordPress.NamingConventions.ValidHookName">
		<properties>
			<property name="additionalWordDelimiters" value="-"/>
		</properties>
	</rule>
</ruleset>

WordPress Coding Standard 0.14

Is the latest release of wpcs included?

I'm getting a warning, When an array uses associative keys, each value should start on a new line. This is fixed in the latest release. It's only required for multi-item associative arrays.

configuration not being honored

I'm trying to use a custom configuration via my .codeclimate.yml that is in the root of my repo that contains:

exclude_paths:
 - "/build"
 - "/doc_generator"
 - "/modules"
 - "/resource"
 - "/tests"
engines:
  phpcodesniffer:
    enabled: true
    config:
      - file_extensions: "php"
      - standard: ["/code/modules/code-standards/company/ruleset.xml"]
ratings:
  paths:
  - "**.php"

However, when I look at the running processes while running codeclimate analyze, I see:

 4327 ?        Ss     0:00  \_ /bin/sh /usr/src/app/bin/codeclimate-phpcodesniffer
 4333 ?        S      0:00      \_ php /usr/src/app/bin/../engine.php
 4334 ?        S      0:00          \_ sh -c ./vendor/bin/phpcs --report=json --ignore= --standard=PSR1,PSR2 /code
 4335 ?        R      0:01              \_ php ./vendor/bin/phpcs --report=json --ignore= --standard=PSR1,PSR2 /code

Autofix using phpcbf (?)

Since phpcbf is included, how about adding the option autofix to the config and have phpcbf fix many of the coding standard errors ?

engines:
    phpcodesniffer:
       enabled: true
       config:
          standard: "WordPress-Core"
       autofix: true

Build failing: Referenced sniff does not exist

We've been using codeclimate for a long time on the open source DKAN project. For the last few weeks all of our builds are failing with the error Referenced sniff "SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator" does not exist.

Here is a failing build:

https://codeclimate.com/github/GetDKAN/dkan/builds/2781

We're using only the phpcodesniffer plugin (beta channel), using the Drupal and DrupalPractice standards. Here is the .codeclimate.yml from that particular build.

I have the CLI tool locally and can run codeclimate analyze successfully on the same commit.

The full stack trace from the build:

Exception: ERROR: Referenced sniff "SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator" does not exist

Run "phpcs --help" for usage information

 in /usr/src/app/vendor/squizlabs/php_codesniffer/src/Runner.php
#0 /usr/src/app/Executor.php(116): PHP_CodeSniffer\Runner->init()
#1 /usr/src/app/vendor/barracudanetworks/forkdaemon-php/fork_daemon.php(1934): Executor->run()
#2 /usr/src/app/vendor/barracudanetworks/forkdaemon-php/fork_daemon.php(1846): fork_daemon->invoke_callback()
#3 /usr/src/app/vendor/barracudanetworks/forkdaemon-php/fork_daemon.php(1747): fork_daemon->fork_work_unit()
#4 /usr/src/app/vendor/barracudanetworks/forkdaemon-php/fork_daemon.php(1499): fork_daemon->process_work_unit()
#5 /usr/src/app/Executor.php(33): fork_daemon->process_work()
#6 /usr/src/app/engine.php(26): Executor->queueDirectory()
#7 {main}Exception: ERROR: Referenced sniff "SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator" does not exist

Updating of standards?

Currently it looks like the images is only rebuilt when committing new standards/fixes.

At least the Drupal standard gets running updates, which means that it'll quickly get outdated.

How to handle this?

Cognitive complexity calculation error

I apologize if this isn't the correct repo to report this

CodeClimate reports the Cognitive Complexity of the following function as 14
I believe the value should be 12

It seems that CodeClimate is incorrectly incrementing the continue statements

function testFunction($array)
{
    if (false) {
        return;
    }
    $file = '';
    $line = 0;
    if (false) {
        throw new \RuntimeException('false was true! ');
    }
    foreach ($array as $key => $val) {
        if (\is_int($key)) {
            continue;
        }
        if (\is_string($val)) {
            continue;
        }
        if (\is_array($val)) {
            foreach ($val as $val2) {
                // empty
            }
        }
    }
}

continue; should not increment

continue LABEL; should increment

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.