Git Product home page Git Product logo

vscode-php-sniffer's Introduction

PHP Sniffer

Build Status PHP Sniffer on the Visual Studio Marketplace

Uses PHP_CodeSniffer to format and lint (mainly) PHP code.

Features

  • Runs phpcs to lint code.
  • Runs phpcbf to format fixable code validation errors, using the built-in commands "Format Document" or "Format Selection" (PHP only).
    • One may need to set this extension as the default language formatter for some languages. The following snippet is an example for PHP that can be added in a settings.json:
      {
        "[php]": {
          "editor.defaultFormatter": "wongjn.php-sniffer"
        }
      }

Requirements

Extension Settings

Quick Setup

settings.json:

{
  "phpSniffer.autoDetect": true
}

And if your projects look like this:

workspace-folder/
  vendor/
    bin/
      phpcs
      phpcbf
  .phpcs.xml

Validation and formatting will work (see below for alternative filenames for .phpcs.xml).

In Depth

This extension contributes the following settings:

  • phpSniffer.run: When to run phpcs (the linter). Can be onSave, onType or never.
  • phpSniffer.onTypeDelay: When phpSniffer.run is onType, this sets the amount of milliseconds the validator will wait after typing has stopped before it will run. The validator will also cancel an older run if the run is on the same file.
  • phpSniffer.extraFiles: Glob patterns of extra files to match that this extension should run on. Useful for standards that don't just validate PHP files. This extension will always run on PHP files — be sure to have your files.associations setting correctly setup for PHP files.
  • phpSniffer.executablesFolder: The folder where both phpcs and phpcbf executables are. Use this to specify a different executable if it is not in your global PATH, such as when using PHP_Codesniffer as a project-scoped dependency. Can be absolute, or relative to the workspace folder.
  • phpSniffer.autoDetect: Set to true for the extension to auto-detect phpSniffer.executablesFolder as ./vendor/bin/ per workspace folder (applies only if phpSniffer.executablesFolder is empty).
  • phpSniffer.standard: The standards to check against. This is passed to the phpcbf and phpcs executables as the value for --standard. Can be absolute, or relative to the workspace folder. If not set, PHP_CodeSniffer will attempt to find a file to use, at the root of the currently open file's workspace folder in the following order:
    1. .phpcs.xml
    2. phpcs.xml
    3. .phpcs.xml.dist
    4. phpcs.xml.dist
  • phpSniffer.snippetExcludeSniffs: Sniffs to exclude when formatting a PHP code snippet (such as when formatting on paste or on the command format on selection). This is passed to the phpcbf command as the value for --exclude when not formatting a whole file.
  • phpSniffer.disableWhenDebugging: Disable sniffing when any debug session is active.

Known Issues

Windows Hanging PHP Process

When phpcs encounters a malformed array declaration, it can sometimes hang from an error. This is exacerbated by the fact that we do not have access to the spawned php process in the extension code and cannot kill php.exe directly. This causes many non-exiting PHP processes on Windows machines which can really slow down the machine. The fix for this is to update squizlabs/PHP_Codesniffer in use to >=3.4.2.

vscode-php-sniffer's People

Contributors

bartlangelaan avatar dependabot[bot] avatar mathieu71 avatar wongjn 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

Watchers

 avatar  avatar

vscode-php-sniffer's Issues

phpcbf does not format selection (format doc works)

Describe the bug
phpcbf does not format selection, though it does work to format the entire document

Using a remote connection over VS Code's ssh remote capabilities. phpcs/phpcbf is installed remotely (and works to warn and format entire document, as mentioned, just not selection)

To Reproduce
Steps to reproduce the behavior:

  1. Go to a PHP file
  2. Select a portion of code
  3. Right click and select "Format Selection With...", and select PHP Sniffer
  4. Bottom bar shows php sniffer runs, but no editing/formatting occurs

Expected behavior
The selected code should be reformatted per the linting rules.

Environment

  • OS: RHEL 7 (via remote ssh), (Windows 10 (local))
  • VSCode version: 1.42.0
  • PHP CLI version: 7.3.11
  • squizlabs/PHP_CodeSniffer version: 3.5.4 (stable)

Extension settings

{
    "phpSniffer.executablesFolder": "/home/myname/bin/",
    "phpSniffer.standard": "/opt/my_ruleset.xml",
    "phpSniffer.run": "onType"
}

Additional context
Using a remote connection over VS Code's ssh/remote capabilities.

Extension won't respect <file> settings

Describe the bug
There are different results between the extension and running phpcs directly. Please test the attachment file to see the bug. On that simple project, phpcs should inspect files under src dir only.

To Reproduce
Steps to reproduce the behavior:

  1. Open the project file (testbug.code-workspace).
  2. Open test.php under test directory
  3. The extension will report some violations.

Expected behavior
No error reported.

Environment

  • OS: Arch Linux
  • VSCode version: 1.35.1
  • PHP CLI version: 7.3.6
  • squizlabs/PHP_CodeSniffer version: 3.4.0

Extension settings

{
  "phpSniffer.executablesFolder": "",
  "phpSniffer.onTypeDelay": 250,
  "phpSniffer.run": "onSave",
  "phpSniffer.snippetExcludeSniffs": [],
  "phpSniffer.standard": "phpcs.xml",
  "phpSniffer.windowsHardkill": false,
  "phpSniffer.windowsPhpCli": "php.exe"
}

Additional context
Add any other context about the problem here.
vscode-php-sniffer-bug.tar.gz

Extension doesn't work via remote ssh

Describe the bug
The extension doesn't have any action after install.
command line has normal behavior.

To Reproduce
Steps to reproduce the behavior:

  1. just install extension
  2. Click Format Document
  3. Anything doesn't happen.

Expected behavior
The document should format by PSR standard.
And will show error or warning in documents.

Environment

  • OS: fedora 34
  • VSCode version: 1.60.2
  • PHP CLI version: 8.0.11 use docker by (exec docker run --rm --publish-all -v $PWD:/source -v /tmp:/tmp -v /opt:/opt -v /home:/home -w /source php:phpcs php "$@")
  • squizlabs/PHP_CodeSniffer version: PHP_CodeSniffer version 3.6.0 (stable) (global ✔)
  • phpcs and phpcbf in the same way like php do.

dockerfile

FROM php:cli-alpine
# RUN cp "/usr/local/etc/php/php.ini-production" "/usr/local/etc/php/php.ini"
RUN apk update && apk add bash \
    curl \
    unzip

# composer
RUN curl -s https://getcomposer.org/installer | php
RUN mv composer.phar /usr/local/bin/composer
RUN composer global require squizlabs/php_codesniffer
RUN ln -s /root/.composer/vendor/bin/phpcs /usr/local/bin/phpcs && \
    ln -s /root/.composer/vendor/bin/phpcbf /usr/local/bin/phpcbf

COPY ./php.ini /usr/local/etc/php/php.ini

Extension settings

{
    "phpSniffer.run": "onSave",
    "phpSniffer.onTypeDelay": 250,
    "phpSniffer.executablesFolder": "",
    "phpSniffer.autoDetect": true,
    "phpSniffer.standard": "psr12",
    "phpSniffer.snippetExcludeSniffs" : [],
}

Additional context
I can do normal phpcs and phpcbf in command line.
But the extension doesn't work.

圖片

php: No such file or directory

Describe the bug
PHP Sniffer can't find php.
Screenshot 2023-05-17 at 11 44 05 AM

To Reproduce
Steps to reproduce the behavior:

  1. Save a .php file

Expected behavior
A clear and concise description of what you expected to happen.

Environment

  • OS: macOS Ventura (13.13.1 (a))
  • VSCode version: 1.78.2 (Universal) // Darwin arm64 22.4.0
  • PHP CLI version: 8.2.6
  • squizlabs/PHP_CodeSniffer version: 3.7.2

Extension settings

{
    "phpSniffer.run": "onSave",
    "phpSniffer.onTypeDelay": 250,
    "phpSniffer.executablesFolder": "",
    "phpSniffer.autoDetect": true
    "phpSniffer.standard": "./phpcs.xml.dist",
    "phpSniffer.snippetExcludeSniffs" : ["formatOnPaste"],
}

Additional context
Not sure what happened, as it was working fine. which php outputs /opt/homebrew/bin/php and it's in my PATH.

Dumps error output into document

Describe the bug
Just now, when copying and pasting the word false, upon pasting I got these two notices dumped into my document at the paste point, following by what I was trying to paste:

Notice: Undefined offset: 2 in /Users/username/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Tokenizers/PHP.php on line 1369

Notice: Undefined offset: 2 in /Users/username/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Tokenizers/PHP.php on line 1380
false

To Reproduce
Steps to reproduce the behavior:

  1. Copy the word false in a document
  2. Highlight the word true in the same document
  3. Cmd+V to paste over it
  4. Get above output

Expected behavior
The word should have just been replaced with no notices being dumped -- or, if there were any notices, they should have been sent to the appropriate Output panel.

Environment

  • OS: macOS 10.14.3
  • VSCode version: 1.31.1
  • PHP CLI version: 7.1.23
  • squizlabs/PHP_CodeSniffer version: 2.9.1

Extension settings
none

Exclude folder options.

Is your feature request related to a problem? Please describe.
Hello.
First thanks for the making this extension for developers. This extension saves many days of mine. I have some problem. I am a WordPress Developer. Yesterday i have little problem. I need to use external PHP library for my project. This library is huge, includes many many files. After added this library to my project phpcs linting was very slow. Sometimes fixer does not work. CPU loading is increased.

Describe the solution you'd like
I have an idea for this issue. I want to exclude huge library folder. Just want to sniff my project code. I tried to exclude folder from phpcs.xml.dist file. But can't get success.

Additional context
Do you have any solution way like this problem? If you have it, please recommend me.

Thanks.

Config "phpSniffer.snippetExcludeSniffs" not working

Config snippetExcludeSniffs Not Working
My config:

{
    "phpSniffer.executablesFolder": "./vendor/bin/",
    "phpSniffer.standard": "PSR2",
    "phpSniffer.snippetExcludeSniffs": [
        "Squiz.Classes.ValidClassName.NotCamelCaps"
    ]
}

Everything works fine, except the exclude sniffs.

Doesn't work anymore in VSCode 1.63.1

I love this extension but it seems not working anymore in the recent VSCode version. I can't find any reference in logs/output window, it just doesn't show errors and auto-formatting isn't working anymore.

Workspace settings:

{
  "[php]": {
    "editor.defaultFormatter": "wongjn.php-sniffer",
    "editor.formatOnSave": true
  },
  "phpSniffer.autoDetect": true,
  "phpSniffer.run": "onType",
}

My phpcs.xml.dist:

<?xml version="1.0" encoding="UTF-8"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
    <arg name="colors" />
    <arg name="extensions" value="php" />

    <file>deploy.php</file>
    <file>scheduler.php</file>
    <file>src/</file>
    <file>tests/</file>
    <exclude-pattern>config/bootstrap.php</exclude-pattern>
    <exclude-pattern>config/preload.php</exclude-pattern>
    <exclude-pattern>tests/bootstrap.php</exclude-pattern>
    <exclude-pattern>var/</exclude-pattern>
    <exclude-pattern>vendor/</exclude-pattern>

    <rule ref="PSR12" />
</ruleset>

Executables path does not work with a relative path

Describe the bug
Relative settings path to vendor phpcs does not work

To Reproduce
Steps to reproduce the behavior:

  1. clone project: https://github.com/Daronspence/wongjn-phpsniffer-bug
  2. composer install
  3. Assert sniffing fails with relative executablesPath setting

Expected behavior
For the executables path setting to work when the value is a relative path for the project.

Environment

  • OS: Mac 11.2.3 (intel)
  • VSCode version: Version: 1.54.3
  • PHP CLI version: [e.g. 7.2/3/4]
  • squizlabs/PHP_CodeSniffer version: 3.4 (global and local)

Additional context
Using a full path for the executable folder setting works. Without a full path, it fails.

Autodetect phpcs from the workspace sub-directory where the file belongs

If the workspace root folder has vendor and phpcs.xml.dist then everything is okay but while developing with WordPress we have to take care of "Go to definition" for which we have to include all the project files and within inner sub-directory phpcs.xml.dist and vendor directory exists. How can we achieve this kind of workspace? How can this kind of configuration auto detect?

Environment

  • OS: Windows 10
  • VSCode version: 1.42.1
  • PHP CLI version: 7.3.5
  • squizlabs/PHP_CodeSniffer version: 3.5.4

Extension settings

{
     "phpSniffer.autoDetect": true,
    "phpSniffer.executablesFolder": "./vendor/bin/",
    "phpSniffer.standard": "./phpcs.xml",
}

Additional context
Tried setting "phpSniffer.autoDetect": true but didn't work and phpSniffer.executablesFolder doesn't accept ${workspaceFolder} like variables nor ./vendor/bin is working as it displays below error.

image

Option to have the errors/suggestions on top of the infowindow

Love the extension. One frustration is when using other systems that give information about the functions and else, the errors/suggestions are added at the bottom, which makes it hard to see the correct problems, because it requires scrolling a lot.

EO3R15NRz7

Describe the solution you'd like
It could be nice to be able to toggle a setting that prepends the PHPCS errors/suggestions ON TOP of the window.
PHPStorm displays the code-sniffing messages on top.

Describe alternatives you've considered
No other alternative considered.

Many thanks!

Only run if `.phpcs.xml` was found in project

Is your feature request related to a problem? Please describe.
Opening random PHP files which are not formatted for PHP Sniffer always highlights tons of errors which makes it difficult to read.

Describe the solution you'd like
It would be great if there is an option which makes PHP Sniffer to only run if there is a .phpcs.xml file in the project because projects formatted for PHP Sniffer usually have the config file.
This way it's automatically disabled for all PHP files and only enabled for projects which use PHP Sniffer.

Describe alternatives you've considered
Disabling PHP Sniffer globally and creating a workspace for each project and turning it on for these workspaces.

Ability to disable sniffing when a debugging session is started

When I am debugging, I often have to go through a lot of (often big) files. Then the listings process starts for each of them, and since a debugging session is in place, PHPCS is also slowed, which means my CPU is often hogged up with linting files that I don't want to lint right now.

I would like to have a setting in the extension to just don't lint the files if a debugging session is launched.

Passing VSCode's tab spacing option is unexpected

After upgrading to version 1.2.1 I get this error:
Illegal argument: character must be non-negative

After upgrading to version 1.2.2 the coding standards are not getting picked up correctly.
Running phpcs -i correctly shows my installed coding standards but VS Code shows errors all over the code. Downgrading to version 1.2.0 seems to work.

Any suggestions?

PHP Sniffer complains about php version even though needed php version is there

Describe the bug
PHP Sniffer complains about a wrong config, specifically the php version, although the right is present. Error:

Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0". You are running 7.3.24-(to be removed in future macOS). in /Users/mhaehnel/.composer/vendor/composer/platform_check.php on line 24

The right php is installed:

php -i
phpinfo()
PHP Version => 8.0.8
...

PHP is installed through phpbrew:

which -a php
/Users/mhaehnel/.phpbrew/php/php-8.0.8/bin/php
/usr/bin/php

And the right php is also in my path first:

echo $PATH
/Users/mhaehnel/.composer/vendor/bin/:/Users/mhaehnel/bin/:/Users/mhaehnel/.phpbrew/php/php-8.0.8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

To be clear. This message doesn't always appear, but is in any case wrong.

Screen Shot 2021-09-06 at 18 24 47

To Reproduce
Not sure yet. Especially since it doesn't consistently happen. But I'm happy to investigate.

Expected behavior
No error.

Environment

  • OS: macOS 11.5.2 (Big Sur)
  • VSCode version: 1.60.0
  • PHP CLI version: 8.0.8
  • squizlabs/PHP_CodeSniffer version: 3.6.0 (global ✔)

Extension settings

{
    "phpSniffer.run": "onSave",
    "phpSniffer.onTypeDelay": 250,
    "phpSniffer.executablesFolder": "",
    "phpSniffer.autoDetect": false,
    "phpSniffer.standard": "PSR12",
    "phpSniffer.snippetExcludeSniffs" : [],
}

Refactor validation timeout to a user setting

Is your feature request related to a problem? Please describe.
For larger files, the hard-coded timeout of 3 seconds may not be sufficient.
This timeout is only needed for windows hanging bug.

Describe the solution you'd like
Make the timeout a user setting. Only use it all for windows.

Additional context
The hanging bug has actually been fixed in PHP_CodeSniffer 3.4.2.

Error massage: spawn ENOTDIR

Hey,
I set the executablesFolder in the settings as relative path or as path and get the error message spawn ENTODIR.

Steps to reproduce the behavior:

  1. Set Executables folder to: /Users/jonaseliasfiedler/dev/subfolder/workspace-folder/cake/framework/Vendor/bin/phpcs
  2. Set the Sniff standard to: /Users/jonaseliasfiedler/dev/subfolder/workspace-folder/phpcs.xml.dist
  3. Opened a file from the project and saved it.
  4. See the error spawn ENTODIR
    Screenshot 2020-11-22 at 11 59 16

Expected behavior
The file is scanned and the errors and warnings are displayed.

Environment

  • OS: macOS Catalina 10.15.6
  • VSCode version: 1.51.1
  • PHP CLI version: 7.1.3
  • squizlabs/PHP_CodeSniffer version: 3.5.8 (global installed)

Extension settings

{
    "phpSniffer.executablesFolder": "/Users/jonaseliasfiedler/dev/subfolder/workspace-folder/cake/framework/Vendor/bin/phpcs",
    "phpSniffer.autoDetect": true,
    "phpSniffer.standard": "/Users/jonaseliasfiedler/dev/subfolder/workspace-folder/phpcs.xml.dist"
}

Additional context
I would be very grateful if there is a solution. I have been trying to solve the whole thing for 4 days. My hope is, that I can use your extension. Otherwise I will have to switch to SublimeText, which I don't want to do. Since I love VSCode. I also felt that your extension is the only one that is still being developed and supported for phpcs for VSCode.

Activate extension on other file types

Is your feature request related to a problem? Please describe.
Some standards validate other file types, such as CSS, JS, markdown but the extension in its current state only activates for PHP files.

Describe the solution you'd like
Add a setting to run the extension on other file types.

Additional context
The drupal/coder standards checks on markdown as well as .info files for example.

Running with PHP inside docker

I'm having the same problem, but my php is running inside a docker container, I have a /usr/bin/php that looks like this:

#!/bin/bash

docker exec \
    -it \
    -u $(id -u) \
    -w "$PWD" \
    php7 \
    php "$@"

Originally posted by @elvishp2006 in #1 (comment)

Are you running the latest version of the extension?
What is the command to run phpcs with PHP in docker?
Could you provide the settings you are using?

@wongjn #1 (comment)

Yes, I'm using the latest version of the extension.
I got a script on my composer.json:

  "scripts": {
    "lint": "phpcs",
    "lint:fix": "phpcbf"
  }

I just need to run composer lint to run my phpcs.

@elvishp2006 #1 (comment)

Indentation not fixed completely when adding and removing curly brace

Describe the bug
When using format on save ad when accidently adding a curly brace (or similar), saving, removing the brace and saving again, the indentation is not fixed completely.

Gif showing the problem:

Kapture 2020-03-25 at 15 35 01

To Reproduce
Steps to reproduce the behavior:

  1. Add curly brace, where it doesn't belong
  2. Save
  3. Remove curly brace
  4. Save again

Expected behavior
Everything should look like before with all correct indentations.

Environment

  • OS: macOS 10.15.4
  • VSCode version: 1.43.2
  • PHP CLI version: 7.3.11
  • squizlabs/PHP_CodeSniffer version: 3.4.2 (global ✔)

Extension settings

{
    "phpSniffer.run": "onSave",
    "phpSniffer.onTypeDelay": 250,
    "phpSniffer.executablesFolder": "",
    "phpSniffer.autoDetect": false,
    "phpSniffer.standard": "~/phpcs.xml",
    "phpSniffer.snippetExcludeSniffs" : [],
}

Additional context
Contents of phpcs.xml

<?xml version="1.0" ?>
<ruleset name="Custom Standard">
    <rule ref="PSR2">
        <exclude name="PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace" />
    </rule>
</ruleset>

Unexpected token D in JSON at position 1

When PHP Sniffer runs, VSCode pops up the following notification:

"Unexpected token D in JSON at position 1"

To Reproduce
Steps to reproduce the behavior:

  1. Open a PHP file.
  2. Save it.
  3. See error

Expected behavior

PHP Sniffer runs as expected, no errors displayed.

Environment

  • OS: MacOS X 10.13.6
  • VSCode version: 1.42.1
  • PHP CLI version: 7.3.6
  • squizlabs/PHP_CodeSniffer version: 3.5.2

Extension settings

{
    "phpSniffer.run": "onSave",
    "phpSniffer.onTypeDelay": 250,
    "phpSniffer.executablesFolder": "",
    "phpSniffer.standard": "",
    "phpSniffer.snippetExcludeSniffs" : [],
}

disable option

Is your feature request related to a problem? Please describe.
I have not found a way to disable the extension in the settings. Whenever I don't want the code to be sniffed I have to disable the extension from the the extensions entry, then change the workspace/user settings file, since it doesn't know about the extension anymore.

Describe the solution you'd like
It would be nice to have the option to disable linting in the user or workspace settings.

It is a wonderful extension.
Thanks

Working with project dependencies

Hello,

First of all, thank you very much for this extension. I really appreciate the time and effort you've put behind this. Kudos.

So I am trying to switch over from vscode-phpcs extension. I have phpcs installed as my project dependency. My composer.json is something like this

{
	"require": {},
	"require-dev": {
		"squizlabs/php_codesniffer": "3.3.1",
		"wp-coding-standards/wpcs": "1.0.0",
		"wimg/php-compatibility": "8.2.0",
		"dealerdirect/phpcodesniffer-composer-installer": "0.4.4",
		"giacocorsiglia/wordpress-stubs": "^4.9"
  }
}

And I have a phpcs.xml file in the root of my project/repo.

<?xml version="1.0"?>
<ruleset name="WordPress Coding Standards for Plugins">
	<description>Generally-applicable sniffs for WordPress plugins</description>

	<rule ref="WordPress-Core">
		<exclude name="WordPress.Files.FileName.NotHyphenatedLowercase"/>
		<exclude name="WordPress.Arrays.MultipleStatementAlignment.DoubleArrowNotAligned"/>
		<exclude name="Generic.Formatting.MultipleStatementAlignment.NotSameWarning"/>
		<exclude name="WordPress.PHP.YodaConditions"/>
	</rule>

	<rule ref="WordPress.WP.I18n">
		<properties>
			<property name="text_domain" type="array" value="ipt_fsqm" />
		</properties>
	</rule>
	<rule ref="WordPress.Files.FileName">
		<properties>
			<property name="strict_class_file_names" value="false" />
		</properties>
	</rule>
	<rule ref="WordPress.NamingConventions.ValidVariableName">
		<properties>
			<property name="customPropertiesWhitelist" type="array" value="myMixedCasePropery,AnotherMixedCaseProperty" />
		</properties>
	</rule>
	<rule ref="WordPress.Arrays.MultipleStatementAlignment">
		<properties>
			<property name="exact" value="false" />
		</properties>
	</rule>
	<rule ref="Generic.Formatting.MultipleStatementAlignment">
		<properties>
			<property name="maxPadding" value="10" />
		</properties>
	</rule>

	<rule ref="WordPress-Docs">
		<exclude name="Squiz.Commenting.InlineComment.InvalidEndChar"/>
		<exclude name="Squiz.PHP.CommentedOutCode"/>
		<exclude-pattern>*/tests/phpunit/*</exclude-pattern>
	</rule>

	<rule ref="WordPress-Docs">
		<exclude name="Squiz.Commenting.FileComment.Missing"/>
		<exclude name="Squiz.Commenting.FunctionComment.Missing"/>
		<exclude name="Squiz.Commenting.FunctionComment.ParamCommentFullStop"/>
	</rule>


	<!-- Check all PHP files in directory tree by default. -->
	<arg name="extensions" value="php"/>
	<file>.</file>

	<!-- Show sniff codes in all reports -->
	<arg value="s"/>

	<!-- PHPCompatibility -->
	<config name="testVersion" value="5.6-7.2"/>
	<rule ref="PHPCompatibility"/>

	<exclude-pattern>*/node_modules/*</exclude-pattern>
	<exclude-pattern>*/vendor/*</exclude-pattern>
	<exclude-pattern>*/bower_components/*</exclude-pattern>
	<exclude-pattern>*/dist/*</exclude-pattern>
</ruleset>

Within vscode preference, I have set the following to tell the extension about phpcs path.

{
    "phpSniffer.executablesFolder": "${workspaceFolder}/vendor/bin/"
}

PS: I do have the trailing slash added, but still nothing really happens.

But nothing really happens. I am not sure how the extension is supposed to work. I assumed, it would show lint errors when I open a file? I can confirm phpcs itself works because if I run

./vendor/bin/phpcs somefile.php

It works just fine. Am I missing something? Please let me know.

Getting "Parse error" since vscode 1.52.0

Describe the bug
Better give some screenshot to explain well what happens:

Brace on a new line
gnome-shell-screenshot-XP4ZV0

Brace on the same line
gnome-shell-screenshot-KX89V0

This cause side effect like this
gnome-shell-screenshot-WOXJW0

To Reproduce
Steps to reproduce the behavior:

  1. Create a basic PHP class
  2. Trigger sniff/lint
  3. See the lint error

Expected behavior
Braces should be correctly detected.

Environment

  • OS: Ubuntu 18.04 LTS
  • VSCode version: 1.52.1
  • PHP CLI version: 7.3.24
  • squizlabs/PHP_CodeSniffer version: 2.9.2 project scoped

Extension settings

{
    "phpSniffer.autoDetect": true,
    "phpSniffer.standard": "/.../project-workspace/build/config/phpcs/Calleo3",
    "phpSniffer.executablesFolder": "/.../project-workspace/bin/"
}

Additional context
Was working fine on vscode 1.51.0

Why does this run when pasting code? How to turn off?

Describe the bug
With this extension enabled and set up to only run onSave, I still get weird issues when I paste PHP code into a document, where it always adds a docblock above the pasted code. I can't figure out how to disable this other than changing "editor.formatOnPaste" to false, which is not what I want. Is there any way to prevent the docblock from getting added on paste?

To Reproduce
Steps to reproduce the behavior:

  1. open a PHP file
  2. copy paste a php snippet from another file
  3. code gets pasted, but above it gets added a @file docblock
  4. sometimes this docblock gets added within the code you've pasted

Expected behavior
I would just like the code I am pasting to be added and properly indented without adding the docblock above/within it.

Environment

  • OS: Mac OS X 10.14.6
  • VSCode version: 1.43.2
  • PHP CLI version: PHP 7.3.14
  • squizlabs/PHP_CodeSniffer version: PHP_CodeSniffer version 3.3.2 (global ✔)

Extension settings

{
    "phpSniffer.run": "onSave",
    "phpSniffer.onTypeDelay": 250,
    "phpSniffer.executablesFolder": "",
    "phpSniffer.autoDetect": true,
    "phpSniffer.standard": "Drupal",
    "phpSniffer.snippetExcludeSniffs" : [],
}

Additional context
Add any other context about the problem here.

executablesFolder setting requires different values for windows and unix.

Describe the bug
Setting executablesFolder with unix path separator doesn't work on windows.

To Reproduce

  1. install squizlabs/PHP_CodeSniffer in project sub folder.
  2. set executablesFolder in project settings using unix path separator (ex: tools/phpcs/vendor/bin).
  3. Open project on windows machine.

Expected behavior
For the executables path setting to work without modification.

Environment

  • OS: Windows 7 Pro
  • VSCode version: 1.56.2
  • PHP CLI version: 8.0.1
  • squizlabs/PHP_CodeSniffer version: 3.6.0 (local in ${workspaceFolder}/tools/phpcs)

Extension settings

{
  "phpSniffer.executablesFolder": "tools/phpcs/vendor/bin"
}

Additional context
Error message

"tools" is not recognized as an internal or external command, operable program or batch file.

While platform specific settings isn't implemented in VSCode there two possible solutions:

  1. Use path.normalize (as in psalm/psalm-vscode-plugin)
  2. Add separate settings for windows (as in junstyle/vscode-php-cs-fixer)

Allow me to specify which php binary to use

Is your feature request related to a problem? Please describe.
Because of our dev setup we have scripts in place that are symlinked to user/local/bin and run whatever php code you want inside our kubernetes environment. This is great and all, but has its challenges for an extension like this, because the only way to get this extension to work would be to add php-code-sniffer to the shared repo I'm currently working. But since it's just me who wants to use phpcs I do not want to pollute the repo unnecessarily.

Describe the solution you'd like
It would therefore be nice, if we could specify which php binary to use by specifiying a path.

Describe alternatives you've considered
Hacking around in our dev setup, adding it to the repo.

Absolute path to phpcs.xml not working

I have the extension installed with the following settings:

"[php]": {
    "editor.defaultFormatter": "wongjn.php-sniffer"
},
"phpSniffer.standard": "/Users/rilwis/elightup/dotfiles/phpcs.xml",
"phpSniffer.run": "onType",

The phpcs.xml is put in the exact folder as described. It's available online.

When I run the "Format Document", it doesn't work.

However, when I run the command line:

phpcs --standard="/Users/rilwis/elightup/dotfiles/phpcs.xml" src/Renderer/Base.php

It works.

Environment

  • OS: Mac Big Sur 11.5
  • VSCode version: 1.64.2
  • PHP CLI version: 7.4.27
  • squizlabs/PHP_CodeSniffer version: 3.7.0 (installed globally ✔)

Respect file-related settings in a phpcs.xml

The extension is not following these configs:

	<!-- What to scan -->
	<file>.</file>
	<!-- Ignoring Files and Folders:
		https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#ignoring-files-and-folders -->
	<exclude-pattern>api-reference/</exclude-pattern>
	<exclude-pattern>dist/</exclude-pattern>
	<exclude-pattern>node_modules/</exclude-pattern>
	<exclude-pattern>resources/</exclude-pattern>
	<exclude-pattern>vendor/</exclude-pattern>
	<!-- Scrutinizer dependency -->
	<exclude-pattern>wordpress/</exclude-pattern>

It's pointing errors at files inside vendor folder, but it's on exclude-pattern tag.

Originally posted by @elvishp2006 in #2 (comment)

Specify in README that one needs to use the "Format document" command to invoke phpcbf

Hello!

Thank you for this great extension, thanks to it I have completely replaced the phpcs extension 👍🏼

May I suggest to make it clear in the README how to invoke phpcbf ?
I was expecting an ad-hoc command; it took me a while to understand that I had to format the document via the standard VS Code "Format document" and "Format selection" commands.

Thank you,
Guido

format on save not working

Describe the bug

I have VSCode configured to format on save using this formatter. The Format Document command works but formatting on save does not work. When viewing the debug log I see the message WARN Aborted format on save after 750ms.

To Reproduce

  1. Configure formatting on save
  2. Save the file
  3. Nothing happens

Expected behavior

Format on save should work.

Environment

  • OS: macOS 10.14.4
  • VSCode version: 1.33.1
  • PHP CLI version: 7.3.3-1
  • squizlabs/PHP_CodeSniffer version: 3.5.0

Extension settings

{
    "phpSniffer.standard": "phpcs.xml",
    "editor.formatOnSave": true
}

Ignored bad indentations

Describe the bug
It seems indentations are ignored for most part - everything except classses and functions. Here's code example to format:

<?php

            namespace App\Http\Controllers;

                use Illuminate\Http\Request;

                class HomeController extends Controller
                {
                    /**
                                    * Create a new controller instance.
                                *
                                    * @return void
                            */
                            public function __construct()
                            {
                            $this->middleware('auth');
                        }

                    /**
                     * Show the application dashboard.
                     *
                     * @return \Illuminate\Contracts\Support\Renderable
                     */
                    public function index()
                    {
                        return view('home');
                    }
                }

To Reproduce

  1. VSCode settings:
"[php]": {
	"editor.tabSize": 4,
	"editor.formatOnSave": true,
	"editor.defaultFormatter": "wongjn.php-sniffer"
}
  1. Format on save results:
    phpsniffer

Expected behavior
Extension should apply proper indentation.

Environment

  • OS: Windows 10
  • VSCode version: 1.42.1
  • PHP CLI version: 7.3.5
  • squizlabs/PHP_CodeSniffer version: 3.5.4] (global ✔)

Extension settings

{
    "phpSniffer.autoDetect": true,
    "phpSniffer.onTypeDelay": 500,
    "phpSniffer.run": "onType",
    "phpSniffer.standard": "PSR12",
}

Additional context

Exclude-Pattern for a specifc sniff don't seem to work

Describe the bug
An exclude pattern for a specific sniff like so:

<!-- Do not warn about _before/_after in codeception tests (relevant for IDEs) -->
<rule ref="PSR2.Methods.MethodDeclaration.Underscore">
    <exclude-pattern>*/tests/*</exclude-pattern>
</rule>

And a codeception test like this:

<?php

class MinimalCest
{

    public function _before(UnitTester $I)
    {
    }

    // tests
    public function minimalCheck(UnitTester $I)
    {
        $I->assertTrue(true);
    }
}

Doesn't seem to be working correctly.

To Reproduce
Steps to reproduce the behavior:

  1. Include the snippet above in your phpcs.xml
  2. You'll still see the error about _before/_after in codeception cest files

Screenshot 2023-05-03 at 12 29 13

Expected behavior
Just as phpcs run from the commandline, the exclude pattern should be honored:

Without the snippet from above:

Screenshot 2023-05-03 at 12 30 09

With the snippet from above:

Screenshot 2023-05-03 at 12 30 41

Environment

  • OS: MacOs Ventura 13.3.1
  • VSCode version: 1.77.3
  • PHP CLI version: 8.1.18
  • squizlabs/PHP_CodeSniffer version: 1.3.0 (global ✔)

Extension settings

{
    "phpSniffer.run": "onSave",
    "phpSniffer.onTypeDelay": 250,
    "phpSniffer.executablesFolder": "",
    "phpSniffer.autoDetect": false,
    "phpSniffer.standard": "config/phpcs.xml",
    "phpSniffer.snippetExcludeSniffs" : [],
}

WSL help?

What can I do to enable Code Sniffing via WSL2 and DDEV/Docker? For Intelephense, I was able to fake this by using an executable bash script at /usr/local/bin/php as follows:

#!/bin/bash docker exec -i --user=1000:1000 ddev-my-container-web php "$@"

However, a similar fake-out with docker exec -i --user=1000:1000 ddev-my-container-web phpcs "$@" does not work, since the Code Sniffer wants a path to a folder for phpcs and phpcbf, not a specific pointer to one executable.

PHP Installed from ASDF not Recognized

image

which php
/home/USER/.asdf/shims/php

/home/USER/.asdf/shims/ is present on $PATH. The php, phpcs and phpcb binaries commands response normally.

And so why this Extension can't recognize the php executable?

See asdf.

OnType can kill itself

Describe the bug
OnType phpcs updates fail to start.

To Reproduce
Steps to reproduce the behavior:

  1. use vs code for a while
  2. notice it stopped running phpcs
  3. save to see the fixed issues
  4. restart vscode to restore ontype

Expected behavior
ontype to not kill itself, and if it does
to wait and auto recover.
Only if it was working before and the phpcs.xml config
has not changed.

Environment

  • OS: windows 10
  • VSCode version: 1.50.1 (User setup)
  • PHP CLI version: 7.4.11 @ built: sep 29 2020 [Zend v3.4.0]
  • squizlabs/PHP_CodeSniffer version: Global

Extension settings

{
    "phpSniffer.run": "onType",
    "phpSniffer.onTypeDelay": 120,
    "phpSniffer.autoDetect": true,
}

Trash being added to file.

Describe the bug

Warning: preg_match(): Compilation failed: unknown property name after \P or \p at offset 5 in 
squizlabs\php_codesniffer\src\Filters\Filter.php on line 275

gets added to the top of the file when you save.

To Reproduce

  1. create a php file in the root folder
  2. save

Expected behavior
Never write to the file being worked on if there is a issue.

Environment

  • OS: windows 11
  • VSCode version: 1.66.1
  • PHP CLI version: PHP 8.1.4 (cli)
  • squizlabs/PHP_CodeSniffer version: 3.6.2 (global ✔)

Extension settings

{
    "editor.defaultFormatter": "wongjn.php-sniffer",
    "editor.formatOnSave": true,
}

Additional context
dont write to the file :(

Ignore project when using this extension

Is your feature request related to a problem? Please describe.
Many times I'm using legacy code where PHPCS was never used. And extension mark every mistake on those pages (a lot of squiggly lines). I won't fix those at this moment.

Zrzut ekranu 2023-05-12 o 12 34 52

Describe the solution you'd like
I would like to have the option to disable this extension for a certain project (or workspace).

Describe alternatives you've considered
I played with the settings in VS Code but with no result.
I tried using phpcs.xml with exclude pattern but it doesn't work.

<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
    <description>PHP Code Sniffer configuration file.</description>
    <exclude-pattern>*</exclude-pattern>
</ruleset>

Additional context
I have installed phpcs globally with the path in phpSniffer.executablesFolder

preg_match() error after downgrade from PHP 7.3 to 7.2

I'll not follow the template as I don't have much time.
I posted this issue on the phpcs page first: squizlabs/PHP_CodeSniffer#2884

However, I found out that forcing the PSR2 standard for the extension while having autoDetect: true fixed my problem. The issue happens randomly and I don't have a precise way to reproduce it. Most of the files I was editing were not inside of the declared <file></file> configuration in phpcs.xml in the root project directory. (Some were even in the /vendor dir)

I hope this helps with a bug somewhere :) I have a feeling it was trying to use some fixes for version above PHP 7.2.

Regards

False positives when using PHP 7.3 flexible HEREDOC syntax

Describe the bug

I'm experiencing what I believe to be false-positive error highlighting when attempting to use PHP 7.3's flexible HEREDOC syntax. From what I can tell, it's failing to consider the HEREDOC terminator as the actual end of a string unless it's in the first column of the editor.

PHPCS itself doesn't flag any errors with the way I'm using HEREDOC in this case, nor does PHP throw errors/warnings; only the extension seems to think something is out of place. My code's actual output works as intended.

To Reproduce

The following contrived example highlights an error:

function outputDiv($content)
{
    if (!$content) { // Line indented incorrectly; expected 0 spaces, found 4 (Generic.WhiteSpace.ScopeIndent.IncorrectExact)
        $content = 'No content';
    }

    // Valid HEREDOC syntax as of PHP 7.3
    $output = <<<HTML
        <div>{$content}</div>
        HTML;

    echo $output;
}

You can resolve this error by moving the HEREDOC terminator to the first column (a pre-7.3 requirement):

function outputDiv($content)
{
    if (!$content) {
        $content = 'No content';
    }

    // Valid HEREDOC syntax as of PHP 7.3, with terminator in column 0
    $output = <<<HTML
        <div>{$content}</div>
HTML;

    echo $output;
}

You can also resolve it by not using HEREDOC at all, naturally:

function outputDiv($content)
{
    if (!$content) {
        $content = 'No content';
    }

    $output = "<div>{$content}</div>";

    echo $output;
}

But the previous example will give an identical error to the first if you forget to close your double-quote, like so:

function outputDiv($content)
{
    if (!$content) { // Line indented incorrectly; expected 0 spaces, found 4 (Generic.WhiteSpace.ScopeIndent.IncorrectExact)
        $content = 'No content';
    }

    // Missing the closing quote, causing the previous error
    $output = "<div>{$content}</div>;

    echo $output;
}

This is what leads me to believe that the HEREDOC string is being treated as "unclosed" unless its terminator begins at column 0.

Expected behavior

No highlighted errors in the first example.

Environment

  • OS: macOS v10.14.6 (18G5033)
  • VSCode version: 1.47.2
  • PHP CLI version: 7.4
  • squizlabs/PHP_CodeSniffer version: 3.5.5 (global ❌)

Extension settings

{
    "phpSniffer.run": "onSave",
    "phpSniffer.onTypeDelay": 250,
    "phpSniffer.executablesFolder": "",
    "phpSniffer.autoDetect": true,
    "phpSniffer.standard": "",
    "phpSniffer.snippetExcludeSniffs" : [],
}

Additional context

I'm not 100% convinced vscode-php-sniffer is to blame for what I'm seeing, but so far it's the only link in the chain I don't have any additional control over. The test cases above were checked in VS Code with all other extensions disabled.

Thanks for any insight you can provide!

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.