Git Product home page Git Product logo

php-coding-standards's Introduction

Syde PHP Coding Standards

PHP 7.4+ coding standards for Syde WordPress projects.

PHP Quality Assurance


Usage

When the package is installed via Composer, and dependencies are updated, everything is ready and the coding standards can be checked via:

vendor/bin/phpcs --standard="Inpsyde" <path>

Here, <path> is at least one file or directory to check, for example:

vendor/bin/phpcs --standard="Inpsyde" ./src/ ./my-plugin.php

There are many options that can be used to customise the behavior of the command, to get documentation use:

vendor/bin/phpcs --help

Configuration File

A phpcs.xml.dist file can be used to avoid passing many arguments via the command line. For example:

<?xml version="1.0"?>
<ruleset name="MyProjectCodingStandard">

    <description>My Project coding standard.</description>

    <file>./src</file>
    <file>./tests/src</file>

    <arg value="sp"/>
    <arg name="colors"/>

    <config name="testVersion" value="7.4-"/>
    <config name="text_domain" value="my-project"/>

    <rule ref="Inpsyde">
        <exclude name="WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize"/>
    </rule>

    <rule ref="Inpsyde.CodeQuality.Psr4">
        <properties>
            <property
                name="psr4"
                type="array"
                value="
                    Inpsyde\MyProject=>src,
                    Inpsyde\MyProject\Tests=>tests/src|tests/unit
                "/>
        </properties>
    </rule>

</ruleset>

Such a configuration allows to run the code style check like so:

vendor/bin/phpcs

Moreover, thanks to the text_domain setting, PHP_CodeSniffer will also check that all WordPress internationalization functions are called with the proper text domain.


Included rules

For the detailed lists of included rules, refer to ruleset.xml.

PSR-1, PSR-2, PSR-12

For more information about included rules from PHP Standards Recommendations (PSR), refer to the official documentation:

WordPress Coding Standards

To ensure code quality, and compatibility with WordPress VIP, some rules have been included from:

Slevomat

A few rules have been included from the Slevomat Coding Standard.

PHPCompatibility

For PHP cross-version compatibility checks, the full PHP Compatibility Coding Standard for PHP CodeSniffer standard has been included.

The target PHP version (range) can be changed via a custom phpcs.xml file.

Generic Rules

Some rules are also included from PHP_CodeSniffer itself, as well as PHPCSExtra.

Custom Rules

The following custom rules are in use:

Sniff Name Description Has Config Auto-Fixable
ArgumentTypeDeclaration Enforce argument type declaration.
DisableCallUserFunc Disable usage of call_user_func.
DisableMagicSerialize Disable usage of __sleep, __wakeup.
DisableSerializeInterface Disable usage of Serializable interface.
DisallowShortOpenTag Disallow short open PHP tag (short echo tag allowed).
ElementNameMinimalLength Use minimum 3 chars for names (with a few exclusions)
EncodingComment Detect usage of opening -*- coding: utf-8 -*-
ForbiddenPublicProperty No public class properties
FunctionBodyStart Handle blank line at start of function body.
FunctionLength Max 50 lines per function/method, excluding blank lines and comments-only lines.
HookClosureReturn Ensure that actions callbacks do not return anything, while filter callbacks return something.
HookPriority Report usage of PHP_INT_MAX and PHP_INT_MIN as hook priority.
LineLength Max 100 chars per line
NestingLevel Max indent level of 3 inside functions
NoAccessors Discourage usage of getters and setters.
NoElse Discourage usage of else.
NoRootNamespaceFunctions Report usage of global functions in the root namespace.
NoTopLevelDefine Discourage usage of define where const is preferable.
PropertyPerClassLimit Discourage usage of more than 10 properties per class.
Psr4 Check PSR-4 compliance
ReturnTypeDeclaration Enforce return type declaration
StaticClosure Points closures that can be static.
VariablesName Check variable (and properties) names

For notes and configuration, refer to the inpsyde-custom-sniffs.md file in this repository.


Template Rules

The InpsydeTemplates ruleset extends the standard Inpsyde ruleset with some template-specific sniffs.

The recommended way to use the InpsydeTemplates ruleset is as follows:

<ruleset>
    <file>./src</file>
    <file>./templates</file>
    <file>./tests</file>
    <file>./views</file>

    <rule ref="Inpsyde"/>

    <rule ref="InpsydeTemplates">
        <include-pattern>*/templates/*</include-pattern>
        <include-pattern>*/views/*</include-pattern>
    </rule>
</ruleset>

The following template-specific rules are available:

Sniff Name Description Has Config Auto-Fixable
TrailingSemicolon Remove trailing semicolon before closing PHP tag.

Removing or Disabling Rules

Rules Tree

Sometimes it is necessary not to follow some rules. To avoid error reporting, it is possible to:

  • remove rules for an entire project via configuration;
  • disable rules from code, only is specific places.

In both cases, it is possible to remove or disable:

  • a complete standard;
  • a standard subset;
  • a single sniff;
  • a single rule.

These things are in a hierarchical relationship: standards are made of one or more subsets, which contain one or more sniffs, which in turn contain one or more rules.

Removing Rules via Configuration File

Rules can be removed for the entire project by using a custom phpcs.xml file, like this:

<?xml version="1.0"?>
<ruleset name="MyProjectCodingStandard">

    <rule ref="Inpsyde">
        <exclude name="PSR1.Classes.ClassDeclaration"/>
    </rule>

</ruleset>

In the example above, the PSR1.Classes.ClassDeclaration sniff (and all the rules it contains) has been removed.

By using PSR1 instead of PSR1.Classes.ClassDeclaration, one would remove the entire PSR1 standard, whereas using PSR1.Classes.ClassDeclaration.MultipleClasses would remove this one rule only, but no other rules in the PSR1.Classes.ClassDeclaration sniff.

Removing Rules via Code Comments

Removing a rule/sniff/subset/standard only for a specific file or a part of it can be done by using special phpcs annotations/comments, for example, // phpcs:disable followed by an optional name of a standard/subset/sniff/rule. Like so:

// phpcs:disable PSR1.Classes.ClassDeclaration

For more information about ignoring files, please refer to the official PHP_CodeSniffer Wiki.


IDE Integration

PhpStorm

After installing the package as explained above, open PhpStorm settings, and navigate to

Language & Frameworks -> PHP -> Quality Tools -> PHP_CodeSniffer

Choose "Local" in the "Configuration" dropdown.

Click the "..." button next to the dropdown. It will show a dialog where you need to specify the path for the PHP_CodeSniffer executable.

Open the file selection dialog, navigate to vendor/bin/ in your project, and select phpcs. On Windows, choose phpcs.bat.

Click the "Validate" button next to the path input field. If everything is working fine, a success message will be shown at the bottom of the window.

Still in the PhpStorm settings, navigate to:

Editor -> Inspections

Type codesniffer in the search field before the list of inspections, then select:

PHP -> Quality Tools -> PHP_CodeSniffer validation

Enable it using the checkbox in the list, press "Apply".

Select "PHP_CodeSniffer validation", click the refresh icon next to the "Coding standard" dropdown on the right, and choose Inpsyde.

If you don't see Inpsyde here, you may need to specify the phpcs.xml file by selecting "Custom" as standard and then use the "..." button next to the dropdown.

Once the PhpStorm integration is complete, warnings and errors in your code will automatically be shown in your IDE editor.


Installation

Via Composer, require as development dependency:

composer require "inpsyde/php-coding-standards:^2@dev" --dev

(Please note that @dev can be removed as soon as a stable 2.0.0 version has been released, or if your root package minimum stability is dev).

php-coding-standards's People

Contributors

alexp11223 avatar antonioeatgoat avatar bueltge avatar chrico avatar cristianobaptista avatar dnaber-de avatar fsw avatar garyjones avatar gmazzap avatar luislard avatar meszarosrob avatar shvlv avatar tfrommen avatar tyrann0us avatar widoz 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-coding-standards's Issues

[Feature Request]: Replace cyclomatic complexity with Cognitive Complexity

Is your feature request related to a problem?

Curently we have a rule that enforces a reasonable amount of cyclomatic complexity.

Cyclomatic complexity is a purely aritmetic value, which duplicates the value at every logic bifurcation in code. Usually this is also referred as "how many unit tests you need to write to have 100% coverage".

Cognitive complexity, on the other hand, is an indication of how complex a piece of code is to read and understand.

For example, a match expression with 3 branches has the same cyclomatic complexity of a if/elseif/else structure, but it is easier to read.

if (condition_one()) {
    do_one();
} elseif (condition_two()) {
    do_two();
} else {
    do_else();
}

// VS

match (true) {
    condition_one() => do_one(),
    condition_two() => do_two(),
    default => do_else(),
}

There's a document published by Sonar that can be downloaded here that explains cognitive complexity in detail.

I believe that we should check our codebase for cognitive complexity instead of cyclomatic complexity.

Describe the desired solution

The Slevomat coding standard has a sniff that checks for cognitive complexity, implementing the rules in the Sonar's document mentioned above.

I propose that we use that Slevomat sniff, replacing the current sniff for cyclomatic complexity.

Describe the alternatives that you have considered

Keep cyclomatic complexity sniff.

Implementing both does not make much sense because any code with that makes cyclomatic complexity sniff pass will also make the cognitive complexity pass, unless the cognitive complexity threshold is much higher, but at that point cyclomatic complexity sniff will make no sense.

Additional context

While this still suggest a Slevomat rule, I'm proposing this issue separately from #71 because it is not just about embracing a Slevomat sniff, but also use it to replace another rule we have.

Code of Conduct

  • I agree to follow this project's Code of Conduct

Return Type check is not valid

The Inpsyde sniff (https://github.com/inpsyde/php-coding-standards/blob/master/Inpsyde/Sniffs/CodeQuality/ReturnTypeDeclarationSniff.php#L175) for check id return type is existing works only for method, like

public function get_media_strings(array $strings): array and not for functions, without a property visibility.

However if it will fail if is a function, without class, only namespace usage, then will the sniff get an error message ' Return type is missing'.

function get_media_strings(array $strings): array

bildschirmfoto-20180828211236-1920x1080

NoAccessors.NoSetter - wrong warning for "non-setters"

I've following error message with the latest 0.7.x - release:

Setters are discouraged. Try to use immutable objects, constructor injection and for objects that really needs changing state try behavior naming instead, e.g. changeName() instead of setName(). InpsydeCodingStandard.CodeQuality.NoAccessors.NoSetter)

code is following:

/**
 * @return array
 */
public function settingsSpec(): array
{
	// snip
}

It seems the quality tool does match by the keyword set, which is contained in settingsSpec.

NoAccessors.NoGetter - don't check for native/psr interfaces

Sometimes it is required to implement get/set or whatevery methods which are maybe not allowed by coding standard but fixed by an interface.

Following error occurs in version 0.7.x - release:

Getters are discouraged. "Tell Don't Ask" principle should be applied if possible, and if getters are really needed consider naming methods after properties, e.g. name() instead of getName().(InpsydeCodingStandard.CodeQuality.NoAccessors.NoGetter)

As code example we've following:

<?php declare(strict_types=1); # -*- coding: utf-8 -*-

class Foo implements IteratorAggregate
{


    public function getIterator(): Traversable
    {
        // snip
    }
}

Link: http://php.net/manual/en/iteratoraggregate.getiterator.php


Secondly it could be also possible to e.G. implement PSR-standard interfaces like PSR container which are having a get($id) method.

Installation via composer fails

I tried to install the package via composer, but it failed with some errors:

>composer require inpsyde/php-coding-standards --dev
Using version ^0.13.4 for inpsyde/php-coding-standards
./composer.json has been created
Running composer update inpsyde/php-coding-standards
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - dealerdirect/phpcodesniffer-composer-installer[v0.4.0, ..., v0.4.4] require composer-plugin-api ^1.0 -> found composer-plugin-api[2.0.0] but it does not match the constraint.
    - inpsyde/php-coding-standards 0.13.4 requires dealerdirect/phpcodesniffer-composer-installer ^0.4 -> satisfiable by dealerdirect/phpcodesniffer-composer-installer[v0.4.0, ..., v0.4.4].
    - Root composer.json requires inpsyde/php-coding-standards ^0.13.4 -> satisfiable by inpsyde/php-coding-standards[0.13.4].

You are using Composer 2, which some of your plugins seem to be incompatible with. Make sure you update your plugins or report a plugin-issue to ask them to support Composer 2.

Installation failed, deleting ./composer.json.

I'm using Windows 10, PHP 7.3.24, Composer 2.0.8

I cloned the package from github repository.
"composer install" have worked fine.
It works normally in this way of installation.

LineLength.TooLong - not for comments

I'm getting following error message with the latest 0.7.x - release:

Line exceeds 120 characters; contains 130 characters (InpsydeCodingStandard.CodeQuality.LineLength.TooLong)

But this is for a comment which contains a link:

/**
 * Returns the <noscript>-tag for GTM.
 *
 * @link https://developers.google.com/tag-manager/devguide#adding-data-layer-variables-for-devices-without-javascript-support
 *
 * @return string
 */

This rule shouldn't test for comments.

PHPCBF Breaks Syntax

The Problem

When running unit tests, I see over 30 errors saying that classes like Translationmanager\Exception\UnexpectedEntityException are not found. Further up in the output, I see raw PHP code for those classes, like so:

.....E<?php# -*- coding: utf-8 -*-

namespace Translationmanager\Exception;

/**
 * Class InvalidPostException
 */
class UnexpectedEntityException extends EntityException
{
    /**
     * Create a new Exception for Unexpected Post Value Retrieved
     *
     * @param string $postType
     * @param string $message
     * @return UnexpectedEntityException
     */
    public static function forPostValue($postType, $message)
    {
        $message = $message ?: "Unexpected post value retrieved for post type {$postType}";

        return new self($message);
    }

    /**
     * Create a new Exception for Unexpected Term Value Retrieved
     *
     * @param mixed $value
     * @param string $message
     * @return UnexpectedEntityException
     */
    public static function forTermValue($value, $message)
    {
        $valueType = is_object($value) ? get_class($value) : gettype($value);
        $message = $message ?: "Unexpected term value retrieved. Should be WP_Term but got {$valueType}";

        return new self($message);
    }
}

Possible Cause

The start of comment sequences // or # are too close to the opening PHP tag <?php. This makes the interpreter misinterpret the files included by autoloading as text instead of PHP.

Suggested Solution

Amend the rules to include a space between the starting PHP tag and the encoding declaration comment.

Specs

  • PHP: 7.1;
  • PHPUnit: 7.5.20;
  • inpsyde/php-coding-standards: 38546e6.

[Feature Request]: Embrace PHPCSUtils

Is your feature request related to a problem?

We have PHPCSUtils as part of dependencies. They were a transitive dependency of WPCS, now they are also required explicitly.

That package provides a lot of helpers to write rules, and an example are the rules wrote as part of #70 which are pretty lean thanks to that library.

We could use that library also for other existing sniff, to simplify them and to make sure they get up-to-date in the case new PHP features are released without maintenance effort on our end.

We could probably also replace many of the code currently in the PhpcsHelpers file.

Describe the desired solution

Replace part of existing sniffs and helpers code in this repository using PHPCSUtils helpers.

Describe the alternatives that you have considered

Leave existing code alone.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Feature Request]: Bump squizlabs/php_codesniffer

Is your feature request related to a problem?

Can't update/install over PHPCS standards that require latest php_codesniffer version.

Describe the desired solution

Currently squizlabs/php_codesniffer is locked at ~3.6.0, but now suggests 3.* or latest is now 3.7.1.

Describe the alternatives that you have considered

??

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Feature Request]: Add check for whitespace after type casting

Is your feature request related to a problem?

Currently, there is no rule that checks whether there is a space after the type casting. As a result, several spellings exist.

Without a space:

return (int)$lowStockThreshold;

With spaces:

return (string) max($lowStockThresholds);

Describe the desired solution

Add a rule that checks that there is a space after the type casting.

Describe the alternatives that you have considered

None.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

WP hooks callback issues

The check for type declarations has an handy exceptions that don't require type declaration when the callback is used for a WordPress hook.

It works when a closure is directly added to an hook, e.g.:

add_action('init', function () { /* ... */ });

or when the @wp-hook annotation is used:

/**
 * @wp-hook init
 */
function fooBar() { /* ... */ }

However, there are two issues currently:

  1. Closures are not recognized when they are static
  2. Class methods are not recognized if not public

Regarding second point, it is true that only public methods can be used directly in a hook, but it is quite common to have a closure that acts as a proxy to a private method, something like:

add_action('init', function ($args) { $this->doSomething($args) });

This allows to use separate methods, without exposing them as public. However, in the example above the closure will not be required to have type, but the doSomething method will be required, even if the @wp-hook annotation is used, so only chance is to either make it public (at that point having the closure does not make sense anymore) or manually excluding the type declaration check.

Built in interface - Argument type is missing

I see following warning:

Argument type is missing | (Inpsyde.CodeQuality.ArgumentTypeDeclaration.NoArgumentType)

when i'm using following:

<?php

class Foo implements Serializable
{
    private $values = [];

    public function serialize(): string
    {

        // phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
        return serialize($this->values);
    }

    public function unserialize($serialized)
    {

        $this->values = unserialize($serialized);
    }

}

but i cannot add type hint string to the argument. :)

[Question] When using phpcbf there is a bug for the rule that leaves the first line with opening php tag

Describe the bug
Not sure if this bug should be tackled in here

Some auto fixing is not working as expected
Notice the phpdeclare at the right after running phpcbf
image

To Reproduce
Steps to reproduce the behavior:
Have the following file with code:

<?php declare(strict_types=1); // -*- coding: utf-8 -*-
/*
 * This file is part of @package CCV\ElasticWPCustomizations
 *
 * (c) Inpsyde GmbH
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CCV\ElasticWPCustomizations\Tests\Unit\Index\Mapping\Settings;

Expected behavior
image

System (please complete the following information):

  • OS: Ubuntu
  • PHP Version 7.4-fpm under docker container

PSR-2 - lower case constants

As in PSR-2 defined, PHP constants should be lower case. So we have to remove the <exclude name="Generic.PHP.LowerCaseConstant" /> from our ruleset.

Error in detecting return type

public function test() : bool
{
    $var = 1;
    return null !== $var;
}

Return type with no return (Inpsyde.CodeQuality.ReturnTypeDeclaration.MissingReturn)

[Feature Request]: Add a rule against unused imports

Is your feature request related to a problem?

After code refactoring or merging, we often have redundant namespace imports with the use keyword. This is a dead code that does nothing but pollution. It's easy to overlook these lines.

Describe the desired solution

Add a sniff raising warning or error on redundant namespace imports.

Describe the alternatives that you have considered

Require the code standard with this rule and just use it.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Generators - Return type with no return

I've found following new issue with latest version 0.10.0:

Error

Return type with no return?  (Inpsyde.CodeQuality.ReturnTypeDeclaration.MissingReturn)

Code

/**
     * @param string $content
     *
     * @return \Generator
     */
    private function readLines(string $content): \Generator
    {

        $line = strtok($content, "\n");

        while ($line !== false) {
            $line = strtok("\n");
            yield is_string($line) ? trim($line) : '';
        }
    }

[Feature Request]: Add check for Emacs UTF-8 file header

Is your feature request related to a problem? Please describe.
At Inpsyde, PHP files used to have the following file header:

<?php # -*- coding: utf-8 -*-

or

<?php declare(strict_types=1); // -*- coding: utf-8 -*-

As of 2021-06-25, there are more than 15.000 PHP files with this header. It originates from Emacs and including it was adapted by developers undiscussed for years.

However, (nowadays) it doesn't make any sense to keep it. In fact, it is no longer used in most new packages and should be removed gradually from legacy packages too.

Describe the solution you'd like

  • Add a coding standard check for the header that warns the user if the header is present.
  • Make sure that phpcbf deletes it.

Describe alternatives you've considered
None.

Additional context
None.

PHPCS colors being wrongly displayed on windows

In the file ruleset.xml on line 17 you append the parameter "colors" to every process of phpcs using your coding standards. While it probably looks great on Unix systems, the windows console cannot really display or process these symbols generated by it, leading to a confusing display.

Now my question would be if it wouldn't be better to remove this parameter, maybe missing some frontend cherries but overall achieving a greater compatibility?

In the end this feature is just a nice-to-have and not a necessity so in my opinion any dev that wants to use this feature can just append the parameter themselves while the main repo remains good to use for more systems.

[Feature Request]: Add a sniff for unused services

Is your feature request related to a problem?

A projects using Inpsyde Modularity would benefit from a sniffs detecting declared but never used services. Having with time more and more service definitions, we need an automated way of removing them.

Describe the desired solution

Add a sniff, checking for unused services.

Describe the alternatives that you have considered

Extending original sniffs detecting dead code? Would be great to help PHP_CodeSniffer to understand the container and services, then unused services probably would be detected by a regular dead code sniffer.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Considering iterable as proper return type declaration for generators

Inpsyde.CodeQuality.ReturnTypeDeclaration.NoGeneratorReturnType complains about the following:

public function listSomething(): iterable {
     yield 1;
     yield 2;
}

I'm not sure if iterable suggests a rewinding of the returned list because that wouldn't be possible. If not, this construct should be allowed IMO.

Review Squiz.Scope.MethodScope.Missing rule in interfaces and PhpAnnotator conflict

Is your feature request related to a problem? Please describe.
I was trying to develop some system using traits and interfaces and I came with this issue:

Lets say we have a contract:

interface BlockInterface
{
    public function boot(): void;
    public function getBlockName(): string;
    public function getDirectory(): string;
    private function getBlockBuildFolderPath(): string;
}

When doing this you will get a PhpAnotator issue:
"Access type for interface member must be omitted"
image

It makes sense that a contract doesnt add access level. But lets say it is opinionated.
I tried to remove the phpAnotator issue but I couldnt.

Then reading this and this it makes sense that interfaces dont declare any kind of access.

This has been reported to jetbrain as well see this

Describe the solution you'd like
I will suggest that other devs, more experienced than me, throw their opinion, and then recommend what to do.

Describe alternatives you've considered

  1. Disabling the Squiz.Scope.MethodScope.Missing for interfaces in the coding standard
  2. Adjust/override Squiz.Scope.MethodScope.Missing to enforce not adding access level on interfaces (I would say this is the way to go)
  3. Recommend to add phpcs:disable Squiz.Scope.MethodScope.Missing in the interface docblock
  4. Recommend how to ignore this issue in phpannotator
  5. Recommend to simply ignore phpannotator and use access level in interfaces

Additional context
Private conversation: https://inpsyde.slack.com/archives/C071B9S5Q/p1644489768755489

[Feature Request]: Add more tests for array spread operator

Is your feature request related to a problem?

There are few cases, when array spread operator is used with method of classes, that are not covered by tests.

Describe the desired solution

Cover the cases with tests.

Describe the alternatives that you have considered

Cover the cases with tests.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Feature Request]: Update dependencies to be compatible with PHP 8

Is your feature request related to a problem?

Right now the packages requires "wp-coding-standards/wpcs": "^2.3" and "automattic/vipwpcs": "^2.2", which are not compatible with PHP 8.

Version 3 of WordPress Coding Standard has been released and a new version of Vip Coding Standards is under development in this branch.

Keeping from the the release description of WordPress-Coding-Standards version 3, these are the PHP features for which support has been added or improved:

  • PHP 7.2
    • Keyed lists.
  • PHP 7.3
    • Flexible heredoc/nowdoc (providing the PHPCS scan is run on PHP 7.3 or higher).
    • Trailing commas in function calls.
  • PHP 7.4
    • Arrow functions.
    • Array unpacking in array expressions.
    • Numeric literals with underscores.
    • Typed properties.
    • Null coalesce equals operator.
  • PHP 8.0
    • Nullsafe object operators.
    • Match expressions.
    • Named arguments in function calls.
    • Attributes.
    • Union types // including supporting the false and null types.
    • Constructor property promotion.
    • $object::class
    • Throw as an expression.
  • PHP 8.1
    • Enumerations.
    • Explicit octal notation.
    • Final class constants
    • First class callables.
    • Intersection types.
  • PHP 8.2
    • Constants in traits.

It could be possible to ensure that their rules are in line with

Describe the desired solution

Since branch 3.0/updates-for-wpcs-3.0 looks quite stable and almost finished, it could be possible to use it until it is merged, it already requires "wp-coding-standards/wpcs": "^3.0" so we can just remove it from our dependencies.

Once the dependencies are updated, it is needed to replaces some Sniffs names as described in their documentation here.

Describe the alternatives that you have considered

An alternative of using 3.0/updates-for-wpcs-3.0 could be wait that it is merged and tagged in a stable version (and maybe work on some of the opened issues) but for now there is no ETA provided for it.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Reference non auto loaded class in ReturnTypeDeclarationSniff

In

$testVersion = trim(PHPCompatibility\PHPCSHelper::getConfigData('testVersion') ?: '');

we see this:

    private function areNullableReturnTypesSupported(): bool
    {
        $testVersion = trim(PHPCompatibility\PHPCSHelper::getConfigData('testVersion') ?: '');
        if (!$testVersion) {
            return false;
        }

But it seems that PHPCompatibility\PHPCSHelper is not part of the Composer autoloader. Therefore the according unit test fails:

Time: 343 ms, Memory: 12.00MB

There was 1 failure:

1) Inpsyde\CodingStandard\Tests\Cases\FixturesTest::testAllFixtures
Class 'PHPCompatibility\PHPCSHelper' not found

php-coding-standards/tests/cases/FixturesTest.php:47

Test fails for current master as well as for 0.13.4.
Reproduce: Check out the repo, run composer install and vendor/bin/phpunit. PHP Version tested in: 7.4.1

[Feature Request]: Configure Dependabot

Is your feature request related to a problem?

Let's just configuring dependabot so that dependencies can be automatically updated.

Describe the desired solution

Configure dependabot following the steps described here: https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuring-dependabot-version-updates#enabling-github-dependabot-version-updates

Describe the alternatives that you have considered

No alternatives available.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Line length of use statements should not be checked

Inpsyde.CodeQuality.LineLength.TooLong should not check for use statements.

When working with nested namespaces to organize code, length of namespaces can exceed 100 characters. This should not lead to validation errors against our coding standards.

[Feature Request]: Evaluate which "Slevomat" coding standard sniffs to use

Is your feature request related to a problem?

In #58 @strangerkir Proposed to make use of the "unused use" sniff from Slevomat coding standard.

As part of #70, that standard will be effectively part of the dependencies of this package.

Consider the large amount of sniff it has, we could consider to use more of them, because I can see many of them have potential to be a good addition.

But we need to gather consensus on which to use. This issue is the place where we will track that progress, even though not sure yet which will be the vest way to do such thing.

Describe the desired solution

Collect consensus on the standard to use, possibly their setting, and then require the sniffs in our rule set.

Describe the alternatives that you have considered

N/A

Additional context

N/A

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Feature Request]: Get rid of Neutron PHP Standard

Is your feature request related to a problem?

Neutron PHP Standard is a coding standard for PHP Code Sniffer. It was developed by Automattic but it is now abandoned by ~2 years.

As they state in their readme, they abandoned it because wanted to fully switch to Vip Coding Standards, however it is not clear of all the roles from the old package have been moved.

Describe the desired solution

These are the rules coming from Neutron that are used in this package:

  • NeutronStandard.AssignAlign.DisallowAssignAlign
  • NeutronStandard.Functions.DisallowCallUserFunc
  • NeutronStandard.Globals.DisallowGlobalFunctions
  • NeutronStandard.MagicMethods.DisallowMagicSerialize
  • NeutronStandard.StrictTypes.RequireStrictTypes
  • NeutronStandard.Whitespace.DisallowMultipleNewlines
  • NeutronStandard.Whitespace.RequireNewlineBetweenFunctions

We need to check one by one if they have already a replacement in VIP Coding Standards, if not, we should probably write a custom one for them.

Describe the alternatives that you have considered

I cannot see any alternative solution.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

VariableAnalysis.UnusedVariable - bug when using foreach

I see following warnings with the latest 0.7.x - release:

Unused variable $filter.(VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable)
Unused variable $validator. (VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable)
Unused variable $stored_data. (VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable)

The code is following:

/**
 * Add a single Element.
 *
 * @param ElementInterface     $element
 * @param FilterInterface[]    $filters
 * @param ValidatorInterface[] $validators
 */
public function addElement(ElementInterface $element, array $filters = [], array $validators = [])
{

	$this->form->add_element($element);

	foreach ($filters as $filter) {
		$this->form->add_filter($element->get_name(), $filter);
	}

	foreach ($validators as $validator) {
		$this->form->add_validator($element->get_name(), $validator);
	}
}

Discrepancy between PhpStorm and these styles regarding blank lines before function body

These coding styles enforce a quite complex logic in determine blank lines at the start of the function. It says that when a function signature is multiple lines, it has to have a blank line at the beginning. E.g.

function foo(
  string $someQuiteLongNane,
  array $fooBarBaz,
  int $anotherParam = SomeClass::SOME_CONSTANT_NAME
): string {

   return "Please notice the blank line above.";
}

However, when the function is one single line, no blank line is required:

function foo(): string
{
   return "No blank line above.";
}

The reason behind this is that in single-line signature functions PSR-1 enforces the opening brace on a new line, so there's already a line that separates the function signature form the body.

Whereas in multi-line signature functions the opening brace is on the same line of the end of signature, which means that not using a blank line there is no separation between function body and signature, making it harder to read, especially when return type declaration is there.

This works well in theory, the problem is that in PhpStorm there's no way to tell auto-format to behave this way. Resulting in more work to be done manually to be compliant.

My suggestion would be to make styles keep requiring a blank line before body of multi-line signature functions, while tolerating no blank line in in case of single-line signature functions.

This way all existing code that is already compliant with our styles would not require to be re-formatted but at same time output of PhpStorm auto-format (that is "just use a blank line, always") would be compliant as well.

The relevant class is https://github.com/inpsyde/php-coding-standards/blob/master/Inpsyde/Sniffs/CodeQuality/FunctionBodyStartSniff.php

Closure Turned Static Breaks Code

The Problem

After this change, I started receiving warnings like the following:

Warning: Cannot bind an instance to a static closure in /var/www/html/wp-content/plugins/translationmanager/src/Project/Taxonomy.php on line 72

Predictably, this also causes fatal errors down the line:

Fatal error: Uncaught Error: Function name must be a string in /var/www/html/wp-content/plugins/translationmanager/src/Project/Taxonomy.php:75
--
  | Stack trace:
  | #0 /var/www/html/wp-includes/class-wp-hook.php(288): Translationmanager\Project\Taxonomy->project_form(Object(Translationmanager\TableList\ProjectItem))
  | #1 /var/www/html/wp-includes/class-wp-hook.php(312): WP_Hook->apply_filters('', Array)
  | #2 /var/www/html/wp-includes/plugin.php(478): WP_Hook->do_action(Array)
  | #3 /var/www/html/wp-content/plugins/translationmanager/src/TableList/ProjectItem.php(171): do_action('translationmana...', Object(Translationmanager\TableList\ProjectItem))
  | #4 /var/www/html/wp-content/plugins/translationmanager/views/project/page-layout.php(13): Translationmanager\TableList\ProjectItem->views()
  | #5 /var/www/html/wp-content/plugins/translationmanager/src/Pages/Project.php(112): require_once('/var/www/html/w...')
  | #6 /var/www/html/wp-includes/class-wp-hook.php(288): Translationmanager\Pages\Project->render_template('')
  | #7 /var/www/html/wp-includes/cl in /var/www/html/wp-content/plugins/translationmanager/src/Project/Taxonomy.php on line 75

Possible Cause

When using PHPCBF, one of the snifs turns all or most closures static. Static closures are slightly cheaper, but don't allow binding. It appears that the sniff in question is Inpsyde.CodeQuality.StaticClosure.

Remarks

  • How does the sniff determine whether or not to make a closure static?
  • How can I prevent closures that need to be bound from becoming static?

[Upgrade]: Modernize existing sniffs

Description of the bug

Currently many existing sniffs does not support modern features like Enum.

We need to make sure all sniffs work well with all the PHP 8+ features.

Moreover, there are conditions that exists due to support of PHP 7.3-, for exmple void return type is enforced conditionally if PHP 7.1+ is supported.
Because now we have PHP 7.4 we can reduce the complexity of sniffs removing those now unnecessary conditions.

Reproduction instructions

N/A

Expected behavior

All sniff should take into account PHP 8+ features.
All sniff should remove support for PHP 7.3-

Environment info

No response

Relevant log output

No response

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

LineLengthSniff returns "Line 0" instead of line number in the warning message

1.0.0-beta.7 returns the "Line 0 exceeds 100 characters" warning message instead of the actual line number.

For example this code that was located on line 86

$script = (new Script(self::HANDLE_EDITOR, $assetUri . "$fileName.js", Asset::BLOCK_EDITOR_ASSETS))->withFilePath($assetDir . "$fileName.js")

returns this message

FILE: AssetProvider.php
-----------------------------------------------------------------------------------------------------------------
FOUND 0 ERRORS AND 1 WARNING AFFECTING 1 LINE
-----------------------------------------------------------------------------------------------------------------
 86 | WARNING | Line 0 exceeds 100 characters; contains 142 characters.
-----------------------------------------------------------------------------------------------------------------

Warning or Error when PHP_INT_MAX or PHP_INT_MIN is used in add_action or add_filter

Is your feature request related to a problem? Please describe.
This is more a question:

Would it be a good idea to throw an error or a warning when the priority argument of add_action and add_filter is PHP_INT_MAX or PHP_INT_MIN?

Describe the solution you'd like
phpcs throwing a warning or an error.

Describe alternatives you've considered

Additional context
Someone wrote "I do not like the usage of PHP_INT_MAX for the hook order, because it is not possible to remove them with another plugin. Yes, maybe not relevant in this case of custom plugin for a customer, but see it too often and have no chance to remove them silently."

Also wrote "But good style in coding is not always a topic of rules and standards, more a process of learning.
The value for php int max is always different and is dependent from the client, from the machine."

Move wimg/ to phpcompatibility/

Suggest updating the composer require for wimg/php-compatibility.

Package wimg/php-compatibility is abandoned, you should avoid using it. Use phpcompatibility/php-compatibility instead.

[Feature Request]: Add rules for arrow functions

Is your feature request related to a problem?

Right now the arrow functions are not analyzed, so they cannot stick to a precise standard.

Describe the desired solution

Arrow functions should be processed the same way standard function are processed.

Describe the alternatives that you have considered

Add tests for them and improve the custom sniffer.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Tests should be filterable to run them separately

Right now I can only run all tests at once which makes it hard to debug/investigate a single sniff or part of code. It would be nice to have a possibility to run a singe test fixture. This can be achieved using PHPUnit's data provider. So

$ vendor/bin/phpunit --filter function-length-no-blank-lines

will run only the function-length-no-blank-lines.php fixture.

Remove WordPressVIPMinimum.VersionControl.MergeConflict in favor of the new sniff

The VIP Coding Standards removed WordPressVIPMinimum.VersionControl.MergeConflict sniff in favor of Generic.VersionControl.GitMergeConflict. See the changelog here: https://github.com/Automattic/VIP-Coding-Standards/releases/tag/2.1.0.

We still reference it

<rule ref="WordPressVIPMinimum.VersionControl.MergeConflict"/>
and it causes an error when running phpcs.

ERROR: Referenced sniff "WordPressVIPMinimum.VersionControl.MergeConflict" does not exist

We don't require a specific version of the VIP CS:

"automattic/vipwpcs": "^2",

Giant leap forward

Please consider upgrading versions

$ composer outdated
dealerdirect/phpcodesniffer-composer-installer v0.4.4 v0.5.0 PHP_CodeSniffer Standards Composer Installer Plugin
phpdocumentor/reflection-common                1.0.1  2.0.0  Common reflection classes used by phpdocumentor to reflect the code structure
phpdocumentor/type-resolver                    0.4.0  1.0.0
phpunit/php-code-coverage                      5.2.0  7.0.7  Library that provides collection, processing, and rendering functionality for PHP code coverage...
phpunit/php-file-iterator                      1.4.5  2.0.2  FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-timer                              1.0.9  2.1.2  Utility class for timing
phpunit/php-token-stream                       2.0.2  3.1.0  Wrapper around PHP's tokenizer extension.
phpunit/phpunit                                6.0.13 8.3.1  The PHP Unit Testing framework.
phpunit/phpunit-mock-objects                   4.0.4  6.1.2  Mock Object library for PHPUnit
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
sebastian/comparator                           2.0.0  3.0.2  Provides the functionality to compare PHP values for equality
sebastian/diff                                 1.4.3  3.0.2  Diff implementation
sebastian/environment                          2.0.0  4.2.2  Provides functionality to handle HHVM/PHP environments
sebastian/global-state                         2.0.0  3.0.0  Snapshotting of global state
sebastian/resource-operations                  1.0.0  2.0.1  Provides a list of PHP built-in functions that operate on resources
wp-coding-standards/wpcs                       0.14.1 2.1.1  PHP_CodeSniffer rules (sniffs) to enforce WordPress coding conventions

[Feature Request]: Add a sniff to enforce property type

Is your feature request related to a problem?

We already enforce functions' arguments and return types, considering that version v2 of this repo is PHP 7.4+ we should also enforce types on properties.

Describe the desired solution

Add a sniff that adds a warning whenever a class or trait declares properties without a type.

Describe the alternatives that you have considered

We either add it or not.

Additional context

To be noted: property type is invariant, so if a class overrides a property from a parent class in vendor (so the parent will not be scanned via the sniff) and the parent type has no type declaration, forcing the type declaration on the child (that would be scanned) will cause a parse error. PHPCS can't know that having a single-file context. Example

Using this rule with inheritance and without a static analyzer like Psalm could be dangerous.
(Another good reason to use Psalm and use inheritance sparingly).

Code of Conduct

  • I agree to follow this project's Code of Conduct

Composer require vs require-dev

Curious as to why you've got most of these packages in the require vs the require-dev:

"require": {
    "php": ">=7.0",
    "squizlabs/php_codesniffer": "^3",
    "dealerdirect/phpcodesniffer-composer-installer": "^0.4",
    "wp-coding-standards/wpcs": "^0.14",
    "automattic/phpcs-neutron-standard": "^1",
    "wimg/php-compatibility": "^8.0"
  },
  "require-dev": {
    "phpunit/phpunit": "6.0.*"
},

I personally don't want all those packages going up to my PROD box.

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.