Code Monkey home page Code Monkey logo

phpcsextra's People

Contributors

dependabot[bot] avatar fredden avatar garyjones avatar jrfnl avatar stronk7 avatar szepeviktor 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpcsextra's Issues

can't install in composer by version match conflict

PS C:\wamp64\www\Project> composer require --dev phpcsstandards/phpcsextra:"^1.0"


  [InvalidArgumentException]
  Could not find package phpcsstandards/phpcsextra in a version matching 1.0


require [--dev] [--dry-run] [--prefer-source] [--prefer-dist] [--fixed] [--no-suggest] [--no-progress] [--no-update] [--no-install] [--no-scripts] [--update-no-dev] [-w|--update-with-dependencies] [-W|--update-with-all-dependencies] [--with-dependencies] [--with-all-dependencies] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix 
APCU-AUTOLOADER-PREFIX] [--] [<packages>]...

Add the unneeded ternary sniff

Is your feature request related to a problem?

A sniff creation was underway here: WordPress/WordPress-Coding-Standards#1771 but it makes no sense to have it in WPCS.

I'll create a PR for this with all the comments in the original PR addressed (add additional test cases).

  • I intend to create a pull request to implement this feature.

Question: what scenarios would using post inc/dec cause issues if code were moved around?

Hi! Hopefully this is the appropriate place to ask. I was wondering in what scenarios would this cause issues if code were moved around as per the description of the sniff.

A snippet from the source has this description currently:

* Using pre-in/decrement is more in line with the principle of least astonishment
* and prevents bugs when code gets moved around at a later point in time.

To a certain degree, I agree that it is easier to reason about (principle of least astonishment / surprise) the value of the variable incremented/decremented, at that point in the code, when it is used.

But the check:

  • errors and auto-fixes standalone instances (e.g. $i++;, or $arr['key']++)
  • skips for non-standalone statements (e.g for loops, while loops, essentially where it is used with other things),
  • warns for weird usage (+1 from me) such as the below:
    ++$i--;
    ++ -- $i ++ ++;
    

I'm trying to see where the value would be for adding this check, in particular enforcing pre inc/dec as opposed to post, as the description mentions it would help in the following manner:

prevents bugs when code gets moved around at a later point in time

Is anyone able to provide an example so I can better understand please?

Thank you.

NonInclusiveLanguage sniff

A sniff to examine code and comments for the use of non-inclusive language and throw a warning when found.

Specifically, the sniff should look for sexist, racist, ablist or ethnocentric language, which can contribute to a hostile work environment.

Initial word list

Search for Alternatives to suggest Notes
whitelist, blacklist allowlist/safelist/acceptlist, denylist/blocklist/rejectlist
master, slave primary/main, secondary/replica
he, she, him, her, his, himself, herself they, them, their, themself may need to limit this search to comments
crazy peculiar, baffling
dummy placeholder

Input requested and very welcome !!!

Particularly on:

  • additional words/terms to look for;
  • what should be the preferred alternatives.

What to examine:

Search for these in:

  • Comments and docblocks.
  • Variable names
  • Constant names
  • Namespace names
  • Class names
  • Function names

For constructs, report on these only when the construct is declared, not when used, as usage cannot be changed until the declaration has been changed.

Additional notes:

  • The sniff should be aware of variants of words, i.e. $white_list, whitelisting etc.
  • The regexes used should be careful not to match too much, i.e. sheer should not match she, while master should not match mastering.

External references:

Add option to NormalizedArrays.Arrays.ArrayBraceSpacing to allow single- or multi-line empty arrays

Is your feature request related to a problem?

The NormalizedArrays.Arrays.ArrayBraceSpacing sniff takes a spacesWhenEmpty property that determines the spacing to enforce for empty arrays. This can be set to an arbitrary number of space characters, or 'newline', but not both. I would like to be able to allow both of these styles:

$a1 = [];
$a2 = [
];

Where the second is particularly useful when the value is expected to change, because additions and removals to that array will show more cleanly in git diffs and history.

However, I don't think there's a way to configure the ArrayBraceSpacing sniff so that both styles are allowed.

Describe the solution you'd like

I would like to be able to specify different spacing rules for empty arrays depending on whether they're single-line or multi-line. I think there might be a few ways to achieve that (separate config values for the two cases; a new config flag to decide whether "empty" only applies to the single-line case; etc.). I do not have any preferences as to how this is implemented, as long as it's possible to specify the intended behaviour described above.

  • I intend to create a pull request to implement this feature.

Feature suggestion: new sniff `EchoConcatenation`

Repost from squizlabs/PHP_CodeSniffer#2259:

Inspired by this Twitter thread and this article.

Using concatenation exponentially increases the memory PHP uses. While in a lot of cases, there is no alternative, there are some specific situations, where there is, most notably when using echo where comma's or interpolation can be used instead.

Question: Would there be interest in a sniff to detect (and possibly auto-fix) this ?

I image a sniff like this could go into the Generic.CodeAnalysis category.

Detect:

echo "Hello " . $name . "! Welcome!"; // Use comma's or interpolation instead.
echo '<div><span>' . function_call($foo) . '</span>' . function_call($bar) . '</div>'; // Use comma's instead.

Recommended alternative way of writing this code:

echo "Hello $name! Welcome!";
echo '<div><span>', function_call($foo), '</span>', function_call($bar), '</div>';

For more code examples, see the ClearPHP article.

Sniff to detect useless alias names

Is your feature request related to a problem?

It would be nice to have a sniff which would detect and flag when an alias is the same as the original name.

PHP will allow this just fine - https://3v4l.org/DIT7X#veol / https://3v4l.org/Gd4M7#veol - , but it is useless to do so.

Describe the solution you'd like

A new sniff to detect useless aliases.

// OK.
use Vendor\Package\ClassName as OtherClassName;
use function Vendor\Package\functionName as otherFunctionName;
use const Vendor\Package\CONSTANT_NAME as OTHER_CONSTANT_NAME;

// Not OK.
use Vendor\Package\ClassName as ClassName;
use function Vendor\Package\functionName as functionName;
use const Vendor\Package\CONSTANT_NAME as CONSTANT_NAME;

// Should also be checked for trait `use` statements
class Aliased_Talker {
    use A {
        A::bigTalk as talk; // OK
        A::smallTalk as smallTalk; // Not OK.
    }
}

Additional context (optional)

Aliasing to the same name, but in a different case should also be flagged, though maybe with a separate error code.

Namespace, OO and function names in PHP are case-insensitive, so aliasing to the same name in a different case is just as useless.

Note: constants are generally case-sensitive, except when explicitly declared as case-insensitive using define(). Probably still a good idea to flag that even so.

New sniff: alphabetize interfaces following `implements` keyword

Similar to the AlphabeticallySortedUsesSniff in slevomat/coding-standard, I'd like a sniff that checks whether interface names following the implements keyword are alphabetically sorted and, if not, fixes them, when running phpcbf.

For example, given the following class:

class Baz implements Foo, Bar
{
}

This sniff would result in an error because Foo and Bar are not in alphabetical order.

Using phpcbf on this file would correct the code to:

class Baz implements Bar, Foo
{
}

False positive in Universal.CodeAnalysis.ConstructorDestructorReturn

Bug Description

The sniff Universal.CodeAnalysis.ConstructorDestructorReturn false-positives if an anonymous function is used inside a constructor. Presumably this also happens for destructors.

Given the following reproduction Scenario

The issue happens when running this command:

vendor/bin/phpcs -s --standard=Universal --sniffs=Universal.CodeAnalysis.ConstructorDestructorReturn test.php

... over a file containing this code:

<?php

class Foo {
    public function __construct() {
        do_something(
            function () {
                return true;
            },
        );

        $this->callback = function () {
            return false;
        };
    }
}

I'd expect the following behaviour

No warnings or errors.

Instead this happened

FILE: /tmp/test/test.php
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
FOUND 0 ERRORS AND 2 WARNINGS AFFECTING 2 LINES
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
  7 | WARNING | A "__construct()" magic method can not return a value. Found: "return true;"
    |         | (Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound)
 12 | WARNING | A "__construct()" magic method can not return a value. Found: "return false;"
    |         | (Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------

Environment

Environment Answer
PHP version 8.0.26
PHP_CodeSniffer version 3.7.1
PHPCSExtra version 1.0.0
PHPCSUtils version 1.0.0
Install type Composer project local

Additional Context (optional)

Tested Against develop branch?

  • I have verified the issue still exists in the develop branch of PHPCSExtra.

Sniff to discourage "long" closures

Closures are generally intended for small code snippets.

A sniff could be written to check that a closure is limited to # lines / code line (excluding inline docs) / statements and throw an error suggesting using a named function instead.

The number of lines and whether it should look for lines / code lines / statements could be made configurable.

Ready for a stable release?

Hey, there has been an Alpha release available since Jun last year. Since there are 100+ average installs per day from packagist.org would it be time to cut a 1.0.0 stable release?

We have a case where setting the minimum-stability to dev or alpha in a project composer.json is undesirable, hence the question.

Thanks for putting this package together!

Please add a sniff to format array key => value pairs

Please add a sniff to format array key => value pairs, like PHPStorm does.
Peek 2021-12-20 16-16

The main difference between already existing sniffs is they do not consider empty lines between key => value pairs. Would be great, if this feature will be configurable, e.g. enable/disable.

Sniff to enforce naming conventions for namespace names

Is your feature request related to a problem?

It would be nice to have a sniff which could check that the name in a namespace declarations complies with certain naming conventions.

The most common naming convention would probably be StudlyCaps/PascalCase, but supporting other naming conventions should also be considered.

Describe the solution you'd like

A new sniff with a choice of which naming convention to enforce.
The naming convention would need to be applied to each part of the namespace declaration.

Some examples:

// StudlyCaps/PascalCase.
namespace VendorName\PackageName\SubCategory\SubLevel; // OK.
namespace Vendor_Name\package_name\subCategory\sublevel; // Not OK.

// Camel_Caps with underscores.
namespace Vendor_Name\Package_Name\Sub_Category\Sub_Level; // OK.
namespace VendorName\package_name\subCategory\sublevel; // Not OK.

// snake_case.
namespace vendor_name\package_name\sub_category\sub_level; // OK.
namespace Vendor_Name\packageName\subCategory\Sublevel; // Not OK.

Additional context (optional)

Might be a good idea for the sniff to also check that each part of the name complies with the following additional conventions:

  • No leading underscore(s).
  • No trailing underscore(s).
namespace VendorName\PackageName\SubCategory\SubLevel; // OK.
namespace _VendorName\_PackageName__\SubLevel_; // Not OK.

Feature suggestion: new sniff for detecting brand name or text string

Is your feature request related to a problem?

This could be probably generalization of WordPress.WP.CapitalPDangit. Like we can use it for any brand name or string like WooCommerce, Github, etc

Describe the solution you'd like

Inspired from WordPress/WordPress-Coding-Standards#1945

  • Sniff should be customizable
  • It would take strings/regex
  • Setting for target checks. Eg, ignoring detection in T_COMMENT

Use cases:

  • Detect string like WooCommerce, Github, etc
  • Detect #https?://(localhost|127.0.0.1)# regex

Problem with NormalizedArrays.Arrays.CommaAfterLast in some cases

Bug Description

The NormalizedArrays.Arrays.CommaAfterLast does its job pretty well. But there is a case that is hitting us a lot (because of our own coding standard explicitly allowing it), and that I think that can be hitting others out there too.

Right now we support all these arrays as valid:

$a = [1, 2, 3, 4]; // Normal mono-line.
$a = [
    1,
    2,
    3,
    4,
]; // Normal multi-line
$a = [1, 2,
    3, 4]; // Multi-multi line with same line closer (to call it some way).
$a = [
    1, 2,
    3, 4,
]; // Multi-multi line with closer apart (also to call it some way).

And the Sniff is working ok for all the cases but the 3rd one. And it seems logic not to require a comma there, because, if there are new items to be added to the array later, the line is going to change, yes or yes (the closer will need to be moved.

Given the following reproduction Scenario

Ensure that "Multi-multi line with same line closer " cases don't require a comma.

The issue happens when running this command:

vendor/bin/phpcs --standard=NormalizedArrays --sniffs=NormalizedArrays.Arrays.CommaAfterLast test.php

... over a file containing this code:

<?php

$a = [1, 2,
    3, 4];

$a = [1 => 1, 2 => 2,
    3 => 3, 4 => 4];

$a = [1 => [1 => 1,
    2 => 2,
    3 => 3,
    4 => 4,
], 5 => 5];

$a = [1 => [1 => 1,
    2 => 2,
    3 => 3,
    4 => 4],
5 => 5];

I'd expect the following behaviour

No errors are reported.

Instead this happened

Five errors are reported.

-------------------------------------------------------------------------------------------
FOUND 5 ERRORS AFFECTING 5 LINES
-------------------------------------------------------------------------------------------
  4 | ERROR | [x] There should be a comma after the last array item in a multi-line array.
  7 | ERROR | [x] There should be a comma after the last array item in a multi-line array.
 13 | ERROR | [x] There should be a comma after the last array item in a multi-line array.
 18 | ERROR | [x] There should be a comma after the last array item in a multi-line array.
 19 | ERROR | [x] There should be a comma after the last array item in a multi-line array.
-------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 5 MARKED SNIFF VIOLATIONS AUTOMATICALLY
-------------------------------------------------------------------------------------------

Environment

Environment Answer
PHP version Any
PHP_CodeSniffer version 3.7.2
PHPCSExtra version 1.1.1
PHPCSUtils version 1.0.8
Install type Normal composer, used by our standard

Additional Context (optional)

This was originally reported for us @ moodlehq/moodle-cs#76
And this change seems to fix the problem:

diff --git a/NormalizedArrays/Sniffs/Arrays/CommaAfterLastSniff.php b/NormalizedArrays/Sniffs/Arrays/CommaAfterLastSniff.php
index d03d1ff..6472e5c 100644
--- a/NormalizedArrays/Sniffs/Arrays/CommaAfterLastSniff.php
+++ b/NormalizedArrays/Sniffs/Arrays/CommaAfterLastSniff.php
@@ -159,6 +159,12 @@ final class CommaAfterLastSniff implements Sniff
                     return;
                 }
 
+                // If the line of the last non-empty token is the same as the closer, we're not
+                // going to require a comma. TODO: Put this under some Sniff configuration setting.
+                if ($tokens[$lastNonEmpty]['line'] === $tokens[$closer]['line']) {
+                    return;
+                }
+
                 $error     = 'There should be a comma after the last array item in a %s array.';
                 $errorCode = 'Missing' . $errorCode;
                 $data      = [$phrase];

Note the TODO that I've put there. IMO there are 4 alternatives:

  • We make that the default behaviour. After all, it doesn't make sense to force commas when the closer is in the same line.
  • We make it a new $validValues, say: enforce_but_when_sameline_closer.
  • We make it a new, apart sniff setting: enforce_skipped_when_sameline_closer.
  • The change is not acceptable (so we'll have to duplicate the sniff into our standard and apply the patch there.

If there is any insight/preference about any of the 1-3 alternatives above... I'm happy preparing a PR with tests and so on...

Ciao :-)

Tested Against develop branch?

  • I have verified the issue still exists in the develop branch of PHPCSExtra.

Sniff to flag `is_a()` and possibly replace with `instanceof`

Is your feature request related to a problem?

PHP has tried to deprecate the use of is_a() a couple of times already, so it is probably a good idea to have a sniff which can detect and (whenever possible) auto-fix any calls to is_a() with instanceof comparisons.

Additional reasons why this sniff would be a nice idea:

  • Performance: using a PHP native operator will generally be faster than a function call, though it is a micro-optimization.
  • IDE support: IDEs will be able to automatically fix/replace all uses of a class name when a class is renamed when the class name is used like a plain name and will, in most cases, not do so when a class name is in a text string.

Refs:

Describe the solution you'd like

A new sniff in the Modernize standard.

Some example code:

// Bad.
if ( is_a( $var, 'MyClass' ) ) {}
if ( is_a( $var, MyClass::class ) ) {}
if ( is_a( $var, self::class ) ) {}

// Okay.
if ( $var instanceof \MyClass ) {}
if ( $var instanceof MyClass ) {} // If file is non-namespaced and/or there is an import `use` statement for the class.
if ( $var instanceof self ) {}

// Should probably be ignored by this sniff, or only flagged, but not auto-fixed ?
if ( is_a( $var, get_class( $obj ) ) ) {}
if ( is_a( $var, get_parent_class( $obj ) ) ) {}

Additional context (optional)

The sniff will need to take namespace/use statement resolution into account and be wary of creative code in the second parameter of the call to is_a() as it should be careful not to create bugs when auto-fixing.

Also note that since PHP 8.0 $obj::class is supported, so is_a( $var, $obj::class ) should be replaceable by ( $var instanceof $obj ).

Also be wary of the PHP 8.0 change that instanceof can then be used in arbitrary expressions, which means this wasn't allowed before and the auto-fixer should take this into account and be wary of this when auto-fixing.

Potential new sniff: scan code for "Trojan source"

Report from squizlabs/PHP_CodeSniffer#3465:

A new security advisory and associated article have recently been published about an attack vector called "Trojan Source" and someone already suggested to me to write a sniff to detect this pattern.

The trick is to use Unicode control characters to reorder tokens in source code at the encoding level.
These visually reordered tokens can be used to display logic that, while semantically correct, diverges from the logic presented by the logical ordering of source code tokens.
Compilers and interpreters adhere to the logical ordering of source code, not the visual order.

A sniff could be written to detect these specific unicode control characters in files and flag these.
The attack has been confirmed to work in JS, but I expect it to also work in PHP, even though PHP is not mentioned in the paper. Will test this, of course, to confirm.

Would this be a sniff which would be acceptable for PHPCS itself (in a new Generic - Security category) or should I prepare it for one of the external standards ?

For the test data, I'd need a combination of both the typical attacks as well as text strings/comments with legitimate uses of those code points to prevent false positives.
That last part will probably be the hardest to handle, so code samples for that would be helpful to receive.

Links to info about Trojan Source:


The Security standard was my first thought, unfortunately I know from experience that that standard is not being actively maintained, so chances of the sniff ever getting merged are slim to none.

The repo for the standard is here: https://github.com/FloeDesignTechnologies/phpcs-security-audit/

When I finally have some breathing room again, I may consider taking over that standard or starting a fork which will be actively maintained, but that may be a while yet.

I might just create a sniff for this anyway and pull it to PHPCSExtra for now.

Sniff to Evaluate Usages of imports

I would very much like a sniff that allows you to specifically allow/disallow usage of types of imports and usage of said imports. This sniff could detect types of imports and aliasing or not of imports within files.

Scenario 1:
I want to limit the usage of use function, but still allow the usage of use {namespace} or use const in our ruleset.

Scenario 2:
I want to limit the usage of use function, but allow use function {name} as {moreSpecificName} aliasing.

The most important (for my needs) and, I assume, easiest implementation is just to flag types of importing that are disallowed in a codebases. Do ping me if any of this is confusing or ambiguous!

Compatibility with PHP CodeSniffer PHAR

I installed PHP CodeSniffer as PHAR using Phive tool. I want to use some features that PHPCSExtra and PHPCSUtils provide, but because they rely and require PHP CodeSniffer installed with Composer, it will be duplicated and probably won't work.

Is there any way how to install this to be compatible with PHP CodeSniffer in PHAR, without requiring to download duplicated dependencies using Composer?

Incorrect detection of PHP 4-style constructors by Universal.CodeAnalysis.ConstructorDestructorReturn

Bug Description

If a __construct() method exists (and you're not still on PHP 4), that is the constructor and any method named like a PHP 4-style constructor is not a constructor. The Universal.CodeAnalysis.ConstructorDestructorReturn sniff treats it as a PHP 4-style constructor anyway.

Also, unless you're using PHP between 5.3.0 and 5.3.2, namespaced classes cannot have PHP 4-style constructors. The Universal.CodeAnalysis.ConstructorDestructorReturn sniff treats it as a PHP 4-style constructor anyway.

Also of note is that PHP 4-style constructors were removed in PHP 8. As this package does not seem to have a "minimum PHP version" setting, I'd recommend using a different code for PHP 4-style constructors so a project that doesn't support older versions of PHP can exclude "Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFoundPHP4" (or whatever name you choose) in its configuration.

Given the following reproduction Scenario

The issue happens when running this command:

vendor/bin/phpcs -s --standard=Universal --sniffs=Universal.CodeAnalysis.ConstructorDestructorReturn test.php test2.php

... over a file containing this code:

<?php

class Foo {
    public function __construct() {
        echo __METHOD__ . "\n";
    }

    public function foo() {
        echo __METHOD__ . "\n";
        return true;
    }
}

... and over a second file containing this code:

<?php

namespace NS;

class Foo {
    public function foo() {
        echo __METHOD__ . "\n";
        return true;
    }
}

I'd expect the following behaviour

No errors or warnings

Instead this happened

FILE: /tmp/test.php
--------------------------------------------------------------------------------------------------------------------------------------------------------------
FOUND 0 ERRORS AND 1 WARNING AFFECTING 1 LINE
--------------------------------------------------------------------------------------------------------------------------------------------------------------
 10 | WARNING | A PHP 4-style constructor can not return a value. Found: "return true;"
    |         | (Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound)
--------------------------------------------------------------------------------------------------------------------------------------------------------------


FILE: /tmp/test2.php
-------------------------------------------------------------------------------------------------------------------------------------------------------------
FOUND 0 ERRORS AND 1 WARNING AFFECTING 1 LINE
-------------------------------------------------------------------------------------------------------------------------------------------------------------
 8 | WARNING | A PHP 4-style constructor can not return a value. Found: "return true;"
   |         | (Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound)
-------------------------------------------------------------------------------------------------------------------------------------------------------------

Environment

Environment Answer
PHP version 8.0.26
PHP_CodeSniffer version 3.7.1
PHPCSExtra version dev-develop 0f55c12
PHPCSUtils version 1.0.0
Install type Composer project local

Additional Context (optional)

See https://3v4l.org/3CAYK and https://3v4l.org/dpRB6 for verifications of the described behaviors. Or just require the test files and construct instances of the classes.

Tested Against develop branch?

  • I have verified the issue still exists in the develop branch of PHPCSExtra.

Universal.Arrays.MixedArrayKeyTypes should report on explicit keys, if implicit keys are the majority

Is your feature request related to a problem?

array(
'hello' => 'world',
'foo',
'bar',
)

phpdoc for code above could be array<string> or string[]

The error reports for all lines that have a numeric key (implicit or explicit).
However in the above case - if there are more implicit keys, than there are explicit - often the string key can be removed completely, instead of adding an explicit key for the majority of array elements.
This has the advantage, that the type can then also be specified more narrowly as list<string> which is shorter and has more useful properties compared to array<string, string> which this error wants to get.

Describe the solution you'd like

If the majority of keys is implicit, report an error for the explicit keys only.

Additional context (optional)

This also makes sense for Universal.Arrays.MixedKeyedUnkeyedArray

  • I intend to create a pull request to implement this feature.

Sniff(s) to detect proper usage of preg_quote()

Originally suggested in WordPress/WordPress-Coding-Standards#1371:

I'd like to suggest adding two new sniffs around the usage of preg_quote().

  • Verify the $regex parameter of any PCRE function calls to make sure that if the regex is being build up by concatenating parts together, that any $variable parts are wrapped in a call to preg_quote().
    preg_match( '`http[s]?://[^\s<>\'"()]*' . preg_quote( $match_data[0], '`' ) . '`', $content ); // OK.
    preg_match( '`http[s]?://[^\s<>\'"()]*' . $match_data[0] . '`', $content ); // Warning.
    preg_match( $regex, $content ); // OK, ignore as impossible to check reliably.
  • Verify that the optional second parameter $delimiter of preg_quote() is always passed.
    Too often I come across code where it is missing and unless it is passed, the default / delimiters are presumed, which is often wrong.

Initially these sniffs would go into Extra, but I'd encourage the WP Core team to consider accepting them into the Core ruleset.

Opinions ?

Ignore specific keys for Universal.Arrays.MixedArrayKeyTypes and Universal.Arrays.MixedKeyedUnkeyedArray

Is your feature request related to a problem?

Some libraries expect some keys to be string and others to not be set, and since it's an external library I cannot change how it accepts the array.

array(
'relation' => 'AND',
array( 'key' => 'foo' ),
array( 'key' => 'bar' ),
)

While I have only 1 explicitly keyed element, I might have 20 non-keyed, which means I would have to add 20 phpcs:ignore or phpcs:disable a lot of times.

Describe the solution you'd like

An "allow" (or "ignore") property list for both rules.

	<rule ref="Universal.Arrays.MixedArrayKeyTypes">
		<properties>
			<property name="ignore" type="array">
				<element value="relation"/>
			</property>
		</properties>
	</rule>
	<rule ref="Universal.Arrays.MixedKeyedUnkeyedArray">
		<properties>
			<property name="ignore" type="array">
				<element value="relation"/>
			</property>
		</properties>
	</rule>

Additional context (optional)

  • I intend to create a pull request to implement this feature.

Allman styling control structures

Seems that Allman styling for control structures are still missing in PHPCS. Below an example of a valid structure:
https://en.wikipedia.org/wiki/Indentation_style#Allman_style

I also noticed some work already has been done over here:
squizlabs/PHP_CodeSniffer#1847

<?php

declare(strict_types=1);

namespace My\Namespace;

use Foo\Bar;

final class MyClass implements Foo
{
    // Example from PSR12 / https://www.php-fig.org/psr/psr-12/
    use C
    {
        B::bigTalk insteadof C;
        C::mediumTalk as FooBar;
    }

    public function __construct()
    {

    }

    public function aVeryLongMethodName(
        TypeHint $hint,
        &$arg2,
        array $arg3 = []
    ): void
    {
        // method body
    }

    public function anonymouseClasses()
    {
        $instance = new class {};

        $instance = new class extends \Foo implements \HandleableInterface
        {
            // Class content
        };

        $instance = new class extends \Foo implements
            \ArrayAccess,
            \Countable,
            \Serializable
        {
            // Class content
        };
    }
    public function closure()
    {
        // No idea if below is the way due the open method "(" but the indenting is allman way though
        $app->get('/hello/{name}', function ($name) use ($app)
        {
            return 'Hello ' . $app->escape($name);
        });

        $foo->bar(
            $arg1,
            function ($arg2) use ($var1)
            {
                // body
            },
            $arg3
        );

        $closureWithArgs = function ($arg1, $arg2)
        {
            // body
        };

        $closureWithArgsAndVars = function ($arg1, $arg2) use ($var1, $var2)
        {
            // body
        };

        $closureWithArgsVarsAndReturn = function ($arg1, $arg2) use ($var1, $var2): bool
        {
            // body
        };
    }

    public function structures()
    {
        foreach ($a as $b)
        {
            // do something
        }

        for ($i = 0; $i < 10; $i++)
        {
            // do something
        }

        for (
            $i = 0;
            $i < 10;
            $i++
        )
        {
            // for body
        }

        while (true)
        {

        }

        while (
            $expr1
            && $expr2
        )
        {
            // structure body
        }

        do
        {
            // structure body;
        }
        while ($expr);

        switch ($var)
        {
            case 'foo':
                // do something
                break;
            default:
                // do something
                break;
        }

        if ($foo === true)
        {
            // do
        }
        elseif ($bar === true)
        {
            // elseif
        }
        else
        {
            // else
        }

        try
        {
            // try body
        }
        catch (FirstThrowableType $e)
        {
            // catch body
        }
        catch (OtherThrowableType | AnotherThrowableType $e)
        {
            // catch body
        }
        finally
        {
            // finally body
        }
    }
}

Sniff to enforce naming conventions for class/function/const aliases

Is your feature request related to a problem?

It would be nice to have a sniff which could check that an alias name provided in import use statements and trait use statements complies with certain naming conventions.

The most common naming convention for class names would probably be StudlyCaps/PascalCase.
Along the same lines, the most common naming convention for function names would probably be camelCase, while for constants it would be MACRO_CASE.

Supporting other naming conventions for each should also be considered.

Describe the solution you'd like

A new sniff with a choice of which naming convention to enforce for each type of alias.

Some examples:

// StudlyCaps/PascalCase class aliases.
use Vendor\Package\ClassName as MyClass; // OK.
use Vendor\Package\ClassName as myClass; // Not OK.
use Vendor\Package\ClassName as My_Class; // Not OK.

// camelCase function aliases.
use function Vendor\Package\functionName as myFunction; // OK.
use function Vendor\Package\functionName as my_function; // Not OK.

class Aliased_Talker {
    use A, B {
        B::bigTalk as talk; // OK
        B::smallTalk as TALKING; // Not OK.
    }
}

// MACRO_CASE constant aliases,
use const Vendor\Package\CONSTANT_NAME as MY_CONSTANT; // OK.
use const Vendor\Package\CONSTANT_NAME as myCONSTANT; // Not OK.

Additional context (optional)

Might be a good idea for the sniff to also check that aliases also complies with the following additional conventions:

  • No leading underscore(s).
  • No trailing underscore(s).

preg_replace replacement with variable must be wrapped in addcslashes

Is your feature request related to a problem?

Simplistic example:

$text = 'The product is free';
$price = '$0.5';

echo preg_replace( '/is free/', 'costs ' . $price, $text ) . PHP_EOL;
// wrong:
// The product costs is free.5
echo preg_replace( '/is free/', addcslashes( 'costs ' . $price, '\\$' ), $text ) . PHP_EOL;
// correct:
// The product costs $0.5

In practice anytime you use a variable as the replacement, if it contains \ or $ followed by a number, preg replace will convert this to a back replacement group.
Since this is an extremely rare occurence, most people don't know that this can possibly happen or aren't aware.

Describe the solution you'd like

If a preg_replace call uses a variable as 2nd argument, the whole replacement arg or each variable in it must be wrapped in addcslashes( $variable, '\\$' ) to fix this issue.

Additional context (optional)

If this rule is something you think is better added in another phpcs ruleset, please let me know.

  • I intend to create a pull request to implement this feature.

Sniff to detect the irregular whitespace characters

Originally created in the WPCS repo

Motivation

The motivation behind the sniff was that I got errors in my php code, and I couldn't see where the errors were coming from, unless I highlighted the code in the editor (Sublime), where I could see that there is not a dot in my space.

So this sniff would detect these irregular white spaces in the code and warn the user not to use them.

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.