Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPMD and PHPCS Camelcase for Tests

Tags:

phpcs

phpmd

I just installed both PHPMD and PHPCS with my Project.

Now, I would like to customize them a bit, but can't seem to achieve it.

I get 2 warnings that I would like to remove for all my project:

  • phpcs: public method name MyTests::my_test_that_should_pass is not in camel caps format
  • phpmd: the method my_test_that_should_pass is not in camel case

With PHPMD, I tried to change : .composer/vendor/phpmd/phpmd/src/main/resources/rulesets/controversial.xml and set allow-underscore-test to true like mentioned here

With PHPCS, I don't really know how to do it.

Any idea???

https://phpmd.org/rules/controversial.html

like image 368
Juliatzin Avatar asked Feb 04 '23 10:02

Juliatzin


1 Answers

PHPCS uses a file called ruleset.xml to allow you to create your own custom standard. The documentation for it is here: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-Ruleset

If you want a specific standard for your project, you can include a phpcs.xml file at the root of your project. It's exactly the same format as a ruleset.xml file and can even specify which files and folders need checking by default. Documentation for that is here: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#using-a-default-configuration-file

I have no idea what coding standard you are using with PHPCS right now, but I'll assume you are using PSR2.

If you run phpcs with the -s option, you'll see an error message with an error code, like this: Method name "MyTests::my_test_that_should_pass" is not in camel caps format (PSR1.Methods.CamelCapsMethodName.NotCamelCaps). The code is the bit you need here.

For your custom standard, you want PSR2, but you don't want the PSR1.Methods.CamelCapsMethodName sniff because you obviously don't want PHPCS checking for camel case. So create a ruleset with this content:

<?xml version="1.0"?>
<ruleset name="MyStandard">
    <description>My custom coding standard.</description>
    <rule ref="PSR2">
        <exclude name="PSR1.Methods.CamelCapsMethodName"/>
    </rule>
</ruleset>

Save that file and call it ruleset.xml or phpcs.xml and then run PHPCS using it: phpcs /path/to/code --standard=/path/to/ruleset.xml

Take a look at the annotated ruleset docs I linked at the top of the comment because there is a lot more you can do with those rulesets.

like image 80
Greg Sherwood Avatar answered May 16 '23 08:05

Greg Sherwood