How can I Partially disable PHPCS' PSR-12 declare(strict_types=1) checks?

3.4k views Asked by At

I currently run php vendor/bin/phpcs --standard=PSR12 src in several of my projects' CI.

They have been failing for 6+ months, because my code is organized like:

<?php declare(strict_types=1);

/**
 * This file is part of SimpleDTO, a PHP Experts, Inc., Project.
 *
 * Copyright © 2019 PHP Experts, Inc.
 * Author: Theodore R. Smith <[email protected]>
 *  GPG Fingerprint: 4BF8 2613 1C34 87AC D28F  2AD8 EB24 A91D D612 5690
 *  https://www.phpexperts.pro/
 *  https://github.com/phpexpertsinc/SimpleDTO
 *
 * This file is licensed under the MIT License.
 */

namespace PHPExperts\SimpleDTO;

It currently generates several PHPCS warnings:

--------------------------------------------------------------------------------------------
FOUND 3 ERRORS AFFECTING 2 LINES
--------------------------------------------------------------------------------------------
 1 | ERROR | [x] Header blocks must be separated by a single blank line
 1 | ERROR | [x] Opening PHP tag must be on a line by itself
 3 | ERROR | [ ] The file-level docblock must follow the opening PHP tag in the file header
--------------------------------------------------------------------------------------------

Is there any way to keep the rest of the PSR-12 checks but not those?

1

There are 1 answers

0
MasterOdin On BEST ANSWER

You have two options:

  1. Use the --exclude command line argument, which allows you to specify sniffs you do not want to worry about. Using your example, it would be php vendor/bin/phpcs --standard=PSR12 --exclude=PSR12.Files.FileHeader,PSR12.Files.OpenTag src

  2. Create a phpcs.xml file with the following set-up:

<?xml version="1.0"?>
<ruleset name="Custom Standard" namespace="MyProject\CS\Standard">
  <rule ref="PSR12">
    <exclude name="PSR12.Files.FileHeader" />
    <exclude name="PSR12.Files.OpenTag" />
  </rule>
</ruleset>

The phpcs.xml (or phpcs.xml.dist) file is automatically picked up if you use that name [1], otherwise use the --standard argument to point to its file location. When using the file, you can also specify more exactly a sniff (e.g. PSR12.Files.OpenTag.NotAlone) that you cannot do with the --exclude command line option.