What built-in codesniff could I use to ensure there are no spaces before parenthesis and after function name

StackOverflow https://stackoverflow.com/questions/20137317

  •  03-08-2022
  •  | 
  •  

Is there a built-in sniff to ensure that

public function foo () {
                   ^---- 

there is no such a space.

I couldn't find it in any built-in standard, or did I just miss it?

有帮助吗?

解决方案

You can easily extend or create your own standard. This is an example how requested functionality could be added to the PEAR standard (which is default).

<?php
//DisallowSpaceBeforeParenthesisSniff.php

class PEAR_Sniffs_Methods_DisallowSpaceBeforeParenthesisSniff implements PHP_CodeSniffer_Sniff
{
    public function register()
    {
        return array(T_FUNCTION);
    }

    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        do {
          $stackPtr++;
          $type = $tokens[$stackPtr]['type'];  
        } while ('T_OPEN_PARENTHESIS' != $type);

        if ('T_WHITESPACE' == $tokens[$stackPtr-1]['type']) {
            $error = 'Spaces before parenthesis and after function name are prohibited. Found: %s';
            $place = $tokens[$stackPtr-2]['content'] . 
                $tokens[$stackPtr-1]['content'] . 
                $tokens[$stackPtr]['content'];
            $error = sprintf($error, $place);
            $phpcsFile->addError($error, $stackPtr-1);
        }
    }
}

The following file is located under: /usr/share/php/PHP/CodeSniffer/Standards/PEAR/Sniffs/Methods

Example:

<?php

// test.php
class abc
{
    public function hello ($world)
    {

    }
}

bernard@ubuntu:~/Desktop$ phpcs test.php

FILE: /home/bernard/Desktop/test.php
--------------------------------------------------------------------------------
FOUND 5 ERROR(S) AFFECTING 2 LINE(S)
--------------------------------------------------------------------------------
 2 | ERROR | Missing file doc comment
 2 | ERROR | Missing class doc comment
 2 | ERROR | Class name must begin with a capital letter
 4 | ERROR | Missing function doc comment
 4 | ERROR | Spaces before parenthesis and after function name are prohibited.
   |       | Found: hello (
--------------------------------------------------------------------------------

I hope this will help you

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top