r/PHPhelp • • Nov 21 '22

Solved Extensionless scripts in PHP_CodeSniffer

Is there a way to configure phpcs.xml to analyse command-line scripts that do not have an extension?

#!/bin/env php
<?php

phpinfo();

If I use <file> to set the path of the script directory (or even individual files), it seems that the extensions argument still kicks in and my files are ignored.

<arg name="extensions" value="php,phtml"/>
<rule ref="Generic.Arrays.DisallowLongArraySyntax"/>
<file>.</file>
<file>scripts</file>
<file>scripts/phpinfo</file>
8 Upvotes

5 comments sorted by

3

u/bkdotcom Nov 21 '22

extensions need not be specified

https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-Ruleset

also:

By default, PHP_CodeSniffer will check any file it finds with a .inc, .php, .js or .css

so if you're wanting to scan a file with a different extension, you probably need to specify that with "extensions"

1

u/kAlvaro Nov 22 '22

extensions need not be specified

Not for these scripts, but I need the directive to have my HTML templates (phtml) linted.

if you're wanting to scan a file with a different extension, you probably need to specify that with "extensions"

What's the syntax for "no extension"?

1

u/bkdotcom Nov 22 '22

1

u/kAlvaro Nov 22 '22

Literally, no extension. Even if I omit my custom extensions argument, the program seems to use the default extensions and will omit extensionless files even if explicitly referenced:

<file>scripts/phpinfo</file>

That Stack Overflow question has a link to a GitHub issue that basically says it isn't supported out of the box and you need to write your own file filter class.

1

u/kAlvaro Nov 22 '22 edited Nov 23 '22

Alright... I'm probably missing some edge case but...

<file>.</file>
<exclude-pattern>scripts/not-php-script</exclude-pattern>
<exclude-pattern>scripts/another-script-to-exclude</exclude-pattern>

Then:

phpcs --filter=Foo/Bar/Blah/CustomFilter.php

And:

<?php
namespace Foo/Bar/Blah;

use PHP_CodeSniffer\Filters\Filter;
use PHP_CodeSniffer\Util\Common;

class CustomFilter extends Filter
{
    private const SCRIPT_DIRECTORIES = [
        'scripts',
    ];

    private function getProjectDir(): string
    {
        return dirname(__DIR__, 3);
    }

    public function accept(): bool
    {
        $filePath = Common::realpath($this->current());
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
        if (is_dir($filePath) || $extension !== '') {
            return parent::accept();
        }

        if ($this->shouldIgnorePath($filePath)) {
            return false;
        }

        foreach (self::SCRIPT_DIRECTORIES as $allowedDir) {
            $directoryPath = Common::realpath($this->getProjectDir() . '/' . $allowedDir);
            if (str_starts_with($filePath, $directoryPath . DIRECTORY_SEPARATOR)) {
                return true;
            }
        }
        return false;
    }
}