Code Monkey home page Code Monkey logo

symfony-coding-standard's Introduction

Build Status

Symfony PHP CodeSniffer Coding Standard

A coding standard to check against the Symfony coding standards, originally shamelessly copied from the -disappeared- opensky/Symfony2-coding-standard repository.

Installation

Composer

This standard can be installed with the Composer dependency manager.

  1. Install Composer

  2. Install the coding standard as a dependency of your project

     composer require --dev escapestudios/symfony2-coding-standard:3.x-dev
    
  3. Add the coding standard to the PHP_CodeSniffer install path

     vendor/bin/phpcs --config-set installed_paths vendor/escapestudios/symfony2-coding-standard
    
  4. Check the installed coding standards for "Symfony"

     vendor/bin/phpcs -i
    
  5. Done!

     vendor/bin/phpcs /path/to/code
    

Stand-alone

  1. Install PHP_CodeSniffer

  2. Checkout this repository

     git clone git://github.com/djoos/Symfony2-coding-standard.git
    
  3. Add the coding standard to the PHP_CodeSniffer install path

     phpcs --config-set installed_paths /path/to/Symfony2-coding-standard
    

    Or copy/symlink this repository's "Symfony"-folder inside the phpcs Standards directory

  4. Check the installed coding standards for "Symfony"

     phpcs -i
    
  5. Done!

     phpcs /path/to/code
    

symfony-coding-standard's People

Contributors

alamirault avatar bertramakers avatar craige avatar dimabarbul avatar djoos avatar droslaw avatar echernyavskiy avatar frenck avatar garyjones avatar hkdobrev avatar insekticid avatar istrof avatar joshuataylor avatar jrfnl avatar khartir avatar matan avatar matthieusarter avatar mmoll avatar mschroeder avatar npotier avatar romashka avatar rweich avatar soullivaneuh avatar stof avatar wickedone avatar xalopp 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

symfony-coding-standard's Issues

bug: Symfony.ControlStructure.UnaryOperators detect non adjacent unary increment / decrement operatos

Have a look at:

<?php
// currently fails, but 
// https://github.com/djoos/Symfony-coding-standard/issues/94#issuecomment-324047371
// says it should pass
$x++;

// passes, but should fail
--     $x;
--
    $x;
--/* not adjacent */
    $x;
--// not adjacent
    $x;

Scanning this file with Symfony Conding Standard, only points out that $x++ is not adjacent to it's variable. This should be in my opinion adjacent, as pointed out by @razbakov in #94.

All not adjacent occurrences, are unfortunately not properly detected at all. This makes this Sniff actually quite useless. ๐Ÿ˜ž

I'm already working on this issue, so I hope to be able to contribute a fix soon ๐Ÿ˜„

Bad indentation sniff on multiple array arguments

With this code:

        $formMapper
            ->with('General')
                ->add('name')
                ->add('values', 'sonata_type_collection', [
                    'by_reference'      => false,
                    'mapped'            => true,
                ], [
                    'edit'              => 'inline',
                    'inline'            => 'table',
                    'link_parameters'   => ['context' => $context],
                ])
            ->end()
        ;

CS found an error on line with ], [:

Multi-line function call not indented correctly; expected 20 spaces but found 16

But I think this is wrong.

The only way to make phpcs happy is to make this following "correction":

        $formMapper
            ->with('General')
                ->add('name')
                ->add('values', 'sonata_type_collection', [
                    'by_reference'      => false,
                    'mapped'            => true,
                    ], [
                    'edit'              => 'inline',
                    'inline'            => 'table',
                    'link_parameters'   => ['context' => $context],
                    ])
            ->end()
        ;

But that makes no sense IMO.

New line between @expectedException and @expectedExceptionMessage

The Commenting\AnnotationsSniff currently doesn't like:

/**
 * @expectedException \Exception
 * @expectedExceptionMessage Don't do it.
 */
public function testThing() {}

But I don't think this looks right:

/**
 * @expectedException \Exception
 *
 * @expectedExceptionMessage Don't do it.
 */
public function testThing() {}

Could we add a blacklist for these? Possibly make it configurable?

changing standard name from symfony2 to symfony?

as i was working on the phpcs 3 compatibility issue i wondered whether it would be an idea to change the standard name from Symfony2 to Symfony as obviously this standard isn't bound to any version of symfony and might cause confusion in the foreseeable future as the release of Symfony 4 is scheduled for this year... (and basically a major each year thereafter)

any thoughts?

Yoda comparation not complaining for this case

I know that YODA comparation tries to avoid a bad assignation to a variable. But also is an standard saying that the expected value should be on the left (first) when comparing.

This said, in my case I can do this without simple variables and phpcs doesn't complain:

if ($e->getErrorCode() == 2006) {
       ....
}

I think in this case also should complain. This makes the code more standard having all the expected values on the left.

Error with Arrays.MultiLineArrayComma

The following code will break, but it should be valid:

$foo = array('a' => true, 'b' => false, 'c' => array(
    'bar' => 1,
    'baz' => 2,
    'barbaz' => 3,
));

[Current Sniffs] Structure

this issue lists all sniffs currently implemented in this repository as described in the structure segment of the symfony coding standard.

this issue can be marked as resolved once the example class at the bottom triggers all mentioned errors when checked with this standard (be sure to remove all comment lines before checking).

at this time i'm not entirely sure how to check for Use return null; when a function explicitly returns null values and use return; when the function returns void values so any suggestions on that are welcome.

Structure

  • Add a single space after each comma delimiter.
  • Add a single space around binary operators (==, &&, ...), with the exception of the concatenation (.) operator.
  • Place unary operators (!, --, ...) adjacent to the affected variable.
  • Always use identical comparison unless you need type juggling.
  • Use Yoda conditions when checking a variable against an expression to avoid an accidental assignment inside the condition statement (this applies to ==, !=, ===, and !==).
  • Add a comma after each array item in a multi-line array, even after the last one.
  • Add a blank line before return statements, unless the return is alone inside a statement-group (like an if statement).
  • Use return null; when a function explicitly returns null values and use return; when the function returns void values.
  • Use braces to indicate control structure body regardless of the number of statements it contains.
  • Define one class per file - this does not apply to private helper classes that are not intended to be instantiated from the outside and thus are not concerned by the PSR-0 and PSR-4 autoload standards.
  • Declare the class inheritance and all the implemented interfaces on the same line as the class name.
  • Declare class properties before methods.
  • Declare public methods first, then protected ones and finally private ones. The exceptions to this rule are the class constructor and the setUp() and tearDown() methods of PHPUnit tests, which must always be the first methods to increase readability.
  • Declare all the arguments on the same line as the method/function name, no matter how many arguments there are.
  • Use parentheses when instantiating classes regardless of the number of arguments the constructor has.
  • Exception and error message strings must be concatenated using sprintf.
  • Calls to trigger_error with type E_USER_DEPRECATED must be switched to opt-in via @ operator.
  • Do not use else, elseif, break after if and case conditions which return or throw something.
  • Do not use spaces around [ offset accessor and before ] offset accessor.
<?php

namespace Symfony2;

// Declare the class inheritance and all the implemented interfaces on the same line as the class name
class Foo
    extends Bar
    implements Baz
{
    // Add a comma after each array item in a multi-line array, even after the last one
    private $a = [
        'foo',
        'bar'
    ];

    // Add a single space after each comma delimiter
    public function __construct($a,$b)
    {
        // Always use identical comparison unless you need type juggling
        if ($a == $b) {
            // Place unary operators (!, --, ...) adjacent to the affected variable
            $a = $b++;
        }
    }

    // Declare class properties before methods;
    private $b;

    // Declare public methods first, then protected ones and finally private ones.
    protected function bar()
    {
        // Use parentheses when instantiating classes regardless of the number of arguments the constructor has
        $foo = new Bar;

        // Do not use spaces around [ offset accessor and before ] offset accessor.
        $this->a [ 'foo' ] = $foo;
    }

    // Declare all the arguments on the same line as the method/function name, no matter how many arguments there are
    public function baz(
        $foo,
        $bar
    ){
        // Use Yoda conditions when checking a variable against an expression
        if ($foo === 1) {
            // Exception and error message strings must be concatenated using sprintf
            throw new \Exception('Bar'.$foo);
        // Do not use else, elseif, break after if and case conditions which return or throw something
        } else {
            // Add a single space around binary operators (==, &&, ...)
            if ($foo===$bar) {
                // Calls to trigger_error with type E_USER_DEPRECATED must be switched to opt-in via @ operator.
                trigger_error('deprecation', E_USER_DEPRECATED);
            }
        }
    }

    public function foo($a, $b)
    {
        // Use braces to indicate control structure body regardless of the number of statements it contains;
        if ($a === $b)
            ++$a;
            // Add a blank line before return statements, unless the return is alone inside a statement-group (like an if statement);
            return $b;    
    }
}

// Define one class per file
class Bar
{

}

Typo in standalone installation guide

There is a typo in the README.md file in the third point of Stand-alone install:

phpcs --config-set installed_paths /path/to/Symfony2-coding-standards

instead of:

phpcs --config-set installed_paths /path/to/Symfony2-coding-standard

Pre-increment, pre-decrement is forced by the Symfony.ControlStructure.UnaryOperators.Invalid test

If we write:

for ($x = 0; $x < $y; $x++) {}

the UnaryOperatorsSniff will fail with:

Place unary operators adjacent to the affected variable

To quieten the error we need to use pre-increment:

for ($x = 0; $x < $y; ++$x) {}

I'm unsure that this is what the standard is asking us? The post-increment is still 'adjacent' to the variable.

Note that the example code in #66 fails as it includes $a = $b++; at line 22.

Ref: #78

Wrap all with folder Symfony2

I think will be better if wrap this inside folder Symfony2, example:

git clone git://github.com/escapestudios/Symfony2-coding-standard.git Symfony2

PHP_CodeSniffer_Tokenizers_Comment not found

I get the following error when trying to use the Symfony2 code sniff.

โžœ  xyz git:(develop) โœ— phpcs --standard=Symfony2 --ignore="src/legacy/*,vendor/*,web/*,app/*" ./
PHP Fatal error:  Uncaught exception 'PHP_CodeSniffer_Exception' with message 'Class `PHP_CodeSniffer_Tokenizers_Comment not found' in /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php:19
Stack trace:
#0 /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer.php(706): include_once()
#1 /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer.php(476): PHP_CodeSniffer->setTokenListeners('Symfony2', Array)
#2 /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer/CLI.php(582): PHP_CodeSniffer->process(Array, 'Symfony2', Array, false)
#3 /usr/local/Cellar/php-code-sniffer/1.4.7/scripts/phpcs(37): PHP_CodeSniffer_CLI->process()
#4 {main}
  thrown in /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php on line 19

Fatal error: Uncaught exception 'PHP_CodeSniffer_Exception' with message 'Class PHP_CodeSniffer_Tokenizers_Comment not found' in /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php on line 19

PHP_CodeSniffer_Exception: Class PHP_CodeSniffer_Tokenizers_Comment not found in /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php on line 19

Call Stack:
    0.0003     231736   1. {main}() /usr/local/Cellar/php-code-sniffer/1.4.7/scripts/phpcs:0
    0.0107    1153984   2. PHP_CodeSniffer_CLI->process() /usr/local/Cellar/php-code-sniffer/1.4.7/scripts/phpcs:37
    0.0112    1162992   3. PHP_CodeSniffer->process() /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer/CLI.php:582
    0.0112    1164624   4. PHP_CodeSniffer->setTokenListeners() /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer.php:476
    0.0340    1202160   5. include_once('/usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php') /usr/local/Cellar/php-code-sniffer/1.4.7/CodeSniffer.php:706

ReturnTypeSniff and anonymous functions

This code produces an error, Symfony.Functions.ReturnType.Invalid:

$x = array_map(function ($y) {
    return $y;
}, [1, 2, 3]);
170 | ERROR | Use return null; when a function explicitly returns null values and use return; when the function returns void values

Shouldn't anonymous functions be excluded from Return Type Sniffs?

Installation directory

Hi here,

I tried to install this library with command composer require --dev escapestudios/symfony2-coding-standard:~2.0 . It should be installed in the vendor/escapestudios/symfony2-coding-standard like it is explained in the readme but it installed in vendor/escapestudios/symfony2-coding-standard/escapestudios/Symfony2-coding-standard. FYI, I am using the latest version of composer.

What happened? Did I do something something wrong?

Thank you.

Duplicate ScopeClosingBraceSniff

PSR2 imports Squiz.WhiteSpace.ScopeClosingBrace.
Zend imports PEAR.WhiteSpace.ScopeClosingBrace.

It's hard to tell which one is better. I'm leaning towards keeping the one in PSR over Zend though.

Missing return tag from closure

phpcs reports a missing return tag if the method has no return value but contains a closure which returns a value.

For example, this function

/**
 * @param \Symfony\Component\Form\FormEvent $event
 */
public function onPreSetData(FormEvent $event)
{
    $form = $event->getForm();

    $form->add(
        'project',
        'entity',
        [
            'class' => 'AppBundle:Project',
            'choice_label' => 'name',
            'query_builder' => function (ProjectRepository $repository) {
                    return $repository->queryAll();
            },
            'empty_value' => 'search.all',
            'required' => false,
            'label' => 'project',
            'multiple' => true,
            'expanded' => false,
        ]
    );
}

triggers the error Missing @return tag in function comment

Fatal error

Getting following error when trying to run this with jenkins. I have setup everything correctly.

[exec] PHP Fatal error: Uncaught exception 'PHP_CodeSniffer_Exception' with message 'Class PHP_CodeSniffer_CommentParser_ClassCommentParser not found' in /usr/share/php/PHP/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php:19
[exec] Stack trace:
[exec] #0 /usr/share/php/PHP/CodeSniffer.php(1267): include_once()
[exec] #1 /usr/share/php/PHP/CodeSniffer.php(557): PHP_CodeSniffer->registerSniffs(Array, Array)
[exec] #2 /usr/share/php/PHP/CodeSniffer/CLI.php(818): PHP_CodeSniffer->initStandard(Array, Array)
[exec] #3 /usr/share/php/PHP/CodeSniffer/CLI.php(95): PHP_CodeSniffer_CLI->process()
[exec] #4 /usr/bin/phpcs(25): PHP_CodeSniffer_CLI->runphpcs()
[exec] #5 {main}
[exec] thrown in /usr/share/php/PHP/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php on line 19
[exec] Result: 255

Refactoring

"The Zend ruleset isn't a complete standard (just a collection of a few sniffs that Zend people submitted many many years ago) so it's highly unlikely that you want to be doing that. Cherry pick the specific sniffs that you want so you don't choose any that conflict with each other."
@todo take a step back and build the coding standard rules up from scratch

[Current Sniffs] Naming Conventions

this issue lists all sniffs currently implemented in this repository as described in the naming conventions segment of the symfony coding standard.

this issue can be marked as resolved once the example class at the bottom triggers all mentioned errors when checked with this standard (be sure to remove all comment lines before checking and ignore the multiple classes per file error).

Naming Conventions

  • Use camelCase, not underscores, for variable, function and method names, arguments.
  • Use underscores for option names and parameter names.
  • Use namespaces for all classes.
  • Prefix abstract classes with Abstract.
  • Suffix interfaces with Interface.
  • Suffix traits with Trait.
  • Suffix exceptions with Exception.
  • Use alphanumeric characters and underscores for file names.
  • For type-hinting in PHPDocs and casting, use bool (instead of boolean or Boolean), int (instead of integer), float (instead of double or real).
<?php

// Use namespaces for all classes

// Prefix abstract classes with Abstract.
abstract class Foo
{
}

// Suffix traits with Trait
trait Bar
{
}

// Suffix exceptions with Exception
class Baz extends \Exception
{
}

// Suffix interfaces with Interface
interface Qux
{
}

class Corge
{
    /**
     * For type-hinting in PHPDocs and casting, use bool, int, float
     * @var boolean $a
     */
    private $a;
    
    // Use camelCase, not underscores, for variable, function and method names, arguments
    private $foo_bar;
    
    // Use underscores for option names and parameter names
    private $baz = [
        'fooBar' => 'baz',
    ];
    
    public function __construct($a)
    {
        // For type-hinting in PHPDocs and casting, use bool, int, float
        $this->a = (boolean) $a;
    }
    
    // Use camelCase, not underscores, for variable, function and method names, arguments
    public function foo_bar($foo_bar)
    {
        $this->foo_bar = $foo_bar;
    }
}

Conflicting rules for opening brace

The standard seems to not know what to do when it encounters a multiline function declaration such as the following

    public function __construct(
        $content = '',
        $status = 200,
        $headers = array()
    ) {
        //...
    }

PHPCS reports

22 | ERROR | [x] Opening brace should be on a new line

If I put it on a new line...

    public function __construct(
        $content = '',
        $status = 200,
        $headers = array()
    )
    {
        //...
    }

I get the following:

 22 | ERROR | [x] There must be a single space between the closing
    |       |     parenthesis and the opening brace of a multi-line
    |       |     function declaration; found newline

PHP_CodeSniffer version 1.5.0RC2 (beta)

Getting the following errors when trying to use the Symfony Coding Standard with phpcs 1.5.0RC2(beta)

PHP Strict Standards:  Declaration of Symfony2_Sniffs_Commenting_FunctionCommentSniff::processReturn() should be compatible with PEAR_Sniffs_Commenting_FunctionCommentSniff::processReturn($commentStart, $commentEnd) in /usr/share/php/PHP/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/FunctionCommentSniff.php on line 35
PHP Strict Standards:  Declaration of Symfony2_Sniffs_Commenting_FunctionCommentSniff::processParams() should be compatible with PEAR_Sniffs_Commenting_FunctionCommentSniff::processParams($commentStart) in /usr/share/php/PHP/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/FunctionCommentSniff.php on line 35
PHP Fatal error:  Uncaught exception 'PHP_CodeSniffer_Exception' with message 'Class PHP_CodeSniffer_Tokenizers_Comment not found' in /usr/share/php/PHP/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php:19
Stack trace:
#0 /usr/share/php/PHP/CodeSniffer.php(939): include_once()
#1 /usr/share/php/PHP/CodeSniffer.php(422): PHP_CodeSniffer->registerSniffs(Array, Array)
#2 /usr/share/php/PHP/CodeSniffer/CLI.php(614): PHP_CodeSniffer->process(Array, Array, Array, false)
#3 /usr/bin/phpcs(37): PHP_CodeSniffer_CLI->process()
#4 {main}
  thrown in /usr/share/php/PHP/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/ClassCommentSniff.php on line 19

Sniffs/Commenting/FunctionCommentSniff.php not compatible with parent processReturn()

Hey guys. We have your coding standard integrated into our build process at CodeShip. This morning our build process broke, throwing this error:

PHP Strict standards: Declaration of Symfony2_Sniffs_Commenting_FunctionCommentSniff::processReturn() should be compatible with that of PEAR_Sniffs_Commenting_FunctionCommentSniff::processReturn() in /home/rof/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/Symfony2/Sniffs/Commenting/FunctionCommentSniff.php on line 35
PHP Stack trace:
PHP 1. {main}() /home/rof/.composer/vendor/squizlabs/php_codesniffer/scripts/phpcs:0
PHP 2. PHP_CodeSniffer_CLI->process() /home/rof/.composer/vendor/squizlabs/php_codesniffer/scripts/phpcs:37
PHP 3. PHP_CodeSniffer->process() /home/rof/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/CLI.php:647
PHP 4. PHP_CodeSniffer->registerSniffs() /home/rof/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer.php:444
PHP 5. include_once() /home/rof/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer.php:1019

I've tracked it down to this commit: 3313423 and the changes you made to:

Sniffs/Commenting/FunctionCommentSniff.php

Strict PHP standards don't like how you changed the parameter arguments for the processReturn() and processParams() functions to no longer match

We were running CodeSniffer 1.5.6. I upgraded to CodeSniffer 2.0.0 and the problem went away.

Since you don't have any numbered releases, it's not possible to target our dependencies to a particular version of your sniff. Any chance you could utilize releases in the future so CI servers don't have to reference your master branch?

Current sniffs

As suggested in #32, i think it would be good to have some kind of list indicating which standards are already enforced by this repo and which still need to be done.

this not only makes it easier for contributors to find a sniff they can work on, but also to see which new standards have been added to the Symfony standards page as that list appears to be changing quite a bit.

opening a seperate issue for each missing sniff might clutter the issues list so i'd like to propose grouping them like they are grouped on Symfony's standards page. which could look like something like this:

Structure

  • Add a single space after each comma delimiter;
  • Add a single space around binary operators (==, &&, ...), with the exception of the concatenation (.) operator;
  • Place unary operators (!, --, ...) adjacent to the affected variable;
  • Always use identical comparison unless you need type juggling;
  • Use Yoda conditions when checking a variable against an expression to avoid an accidental assignment inside the condition statement (this applies to ==, !=, ===, and !==);
  • Add a comma after each array item in a multi-line array, even after the last one;
  • Add a blank line before return statements, unless the return is alone inside a statement-group (like an if statement);
  • Use return null; when a function explicitly returns null values and use return; when the function returns void values;
  • Use braces to indicate control structure body regardless of the number of statements it contains;
  • Define one class per file
  • Declare the class inheritance and all the implemented interfaces on the same line as the class name;
  • Declare class properties before methods;
  • Declare public methods first, then protected ones and finally private ones. The exceptions to this rule are the class constructor and the setUp() and tearDown() methods of PHPUnit tests, which must always be the first methods to increase readability;
  • Declare all the arguments on the same line as the method/function name, no matter how many arguments there are;
  • Use parentheses when instantiating classes regardless of the number of arguments the constructor has;
  • Exception and error message strings must be concatenated using sprintf;
  • Calls to trigger_error with type E_USER_DEPRECATED must be switched to opt-in via @ operator.
  • Do not use else, elseif, break after if and case conditions which return or throw something;
  • Do not use spaces around [ offset accessor and before ] offset accessor.

and perhaps to clarify include an example for each rule which should trigger an error, e.g.

<?php
    // Add a single space after each comma delimiter;
    function foo($a,$b){}
    
    // Add a single space around binary operators
    if ($a==$b){}
    
    // Place unary operators adjacent to the affected variable
    $a = $b++;
    
    // Always use identical comparison
    if ($a == $b) {}
    
    // Use Yoda conditions
    if ($a == 1) {}
    
    // Add a comma after each array
    $a = [
        'foo',
        'bar'
    ];
    
    // Add a blank line before return statements
    function foo()
    {
        $a = $b;
        return $b;
    }
    
    // ... etc

any thoughts on this?

Use local Composer dependency for build

Can we install PHPUnit locally through composer and use the composer installed versions of phpunit and phpcs for our build script?

The new build.xml section would look something like this

<target name="phpunit" description="Run unit tests with PHPUnit" depends="vendor">
    <exec executable="${basedir}/vendor/bin/phpunit" failonerror="true" >
        <arg value="--filter=Symfony2_*" />
        <arg value="${basedir}/vendor/squizlabs/php_codesniffer/tests/AllTests.php" />
    </exec>
</target>

<target name="phpcs" description="Find coding standard violations using PHP Code Sniffer" depends="vendor">
    <exec executable="${basedir}/vendor/bin/phpcs">
        <arg value="--standard=${phpcs.standard}" />
        <arg value="--ignore=vendor/*" /> 
        <arg path="${basedir}" />
    </exec>
</target>

This will remove the external PHPUnit and PHPCS dependencies, as well as allowing us to enforce the version requirements of both of these tools.

InvalidAbstractName should not throw error on *TestCase class

Example:

FILE: /code/tests/Security/Authorization/Voter/VoterTestCase.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
 16 | ERROR | Abstract class name is not prefixed with "Abstract"
----------------------------------------------------------------------

But it's not true. See Symfony code source. *TestCase classes are not prefixed by Abstract.

Workaround:

<rule ref="Symfony.NamingConventions.ValidClassName.InvalidAbstractName">
    <exclude-pattern>*TestCase.php</exclude-pattern>
</rule>

Opening brace should not match one-lined anonymous function

Found on Symfony codebase: https://github.com/symfony/symfony/blob/cf898572a0194340ca2d8111891f8a6b9f860654/src/Symfony/Component/Config/Definition/Builder/ExprBuilder.php#L40

But phpcs will say:

Opening brace must be the last content on the line
Closing brace must be on a line by itself
Missing blank line before return statement

See also: squizlabs/PHP_CodeSniffer#1580

Workaround:

<exclude name="Squiz.Functions.MultiLineFunctionDeclaration.ContentAfterBrace"/>
<exclude name="Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore"/>
<exclude name="PEAR.WhiteSpace.ScopeClosingBrace.Line"/>
<exclude name="Symfony.Formatting.BlankLineBeforeReturn.Invalid"/>

Symfony2.Objects.ObjectInstantiation.Invalid when using variables in static initializers

When using static initialization functions with the self class name, I get an error:

<?php

namespace Gbirke\Testcases

/**
 * Test class
 */
class ClassWithStaticInit
{
    private $bar;

  /**
   * @param mixed $bar
   */
    public function __construct($bar)
    {
        $this->bar = $bar;
    }

  /**
   * @param mixed $barValue
   * @return ClassWithStaticInit
   */
    public static function newBarInit($barValue)
    {
        return new self($barValue);
    }
}

When changing self to ClassWithStaticInit the sniff works. Very strange.

[Current Sniffs] Documentation

this issue lists all sniffs currently implemented in this repository as described in the documentation section of the symfony coding standard.

this issue can be marked as resolved once the example class at the bottom triggers all mentioned errors when checked with this standard (be sure to remove all comment lines before checking and ignore the multiple classes per file error).

the requirement of a license is debatable as it's specific to contributing to the symfony code base.
we might want to consider implementing this sniff and make it a type warning in the ruleset.xml so it can easily be ignored for builds by a phpcs --config-set show_warnings 0 ?

Documentation

  • Add PHPDoc blocks for all classes, methods, and functions;.
  • Group annotations together so that annotations of the same type immediately follow each other, and annotations of a different type are separated by a single blank line;.
  • Omit the @return tag if the method does not return anything;.
  • The @Package and @subpackage annotations are not used..
  • The license block has to be present at the top of every PHP file, before the namespace.
<?php

// the license block has to be present at the top of every PHP file, before the namespace
namespace Symfony;

// Add PHPDoc blocks for all classes, methods, and functions;
class Foo
{
    /**
     * Group annotations together so that annotations of the same type immediately follow each other, and annotations of a different type are separated by a single blank line
     * @Baz("qux")
     * @Corge("grault")
     * @Baz("qux")
     */
    private $bar;

    /**
     * Omit the @return tag if the method does not return anything
     *
     * @return void
     */
    public function __construct($bar)
    {
        $this->bar = $bar;
    }

    // Add PHPDoc blocks for all classes, methods, and functions;
    protected function bar()
    {
    }

    // Add PHPDoc blocks for all classes, methods, and functions;
    private function baz()
    {
    }
}

/**
 * @package baz
 */
class Bar
{
}

Concatenation on multiple lines

It seems impossible now to do a string concatenation on multiple lines, without getting a warning.
For example like this:

$str = 'some long text that fills the whole line'
          .'some more text';

I propose fixing this in the ruleset:

    <rule ref="Squiz.Strings.ConcatenationSpacing">
        <properties>
            <property name="ignoreNewlines" value="true"/>
        </properties>
    </rule>

Undefined Index when attempting to evaluate PHP file without class / function

This is based on evaluating a laravel config file, which typically only contains a return statement array of configuration values... (ie: https://github.com/laravel/laravel/blob/master/config/app.php)

Example code triggering issue can be located below...

<?php

return [

    'api_domain' => env('API_DOMAIN', 'api.example.com'),

    'app_id' => env('APP_ID'),

    'client_id' => env('CLIENT_ID'),
    'client_secret' => env('CLIENT_SECRET'),

];

The error displayed is as follows...

An error occurred during processing; checking has been aborted. The error message was: Undefined index: scope_opener in vendor/escapestudios/symfony2-coding-standard/Symfony/Sniffs/Formatting/ReturnOrThrowSniff.php on line 78 (Internal.Exception)

https://github.com/djoos/Symfony-coding-standard/blob/master/Symfony/Sniffs/Formatting/ReturnOrThrowSniff.php#L78

Notes:

$function variable is returning false, whereas the return of throw sniff is looking for a function call and assumes it's available.

https://github.com/djoos/Symfony-coding-standard/blob/master/Symfony/Sniffs/Formatting/ReturnOrThrowSniff.php#L74

Ruleset compatibility with PHP-CS-Fixer

I'm using PhpStorm and was pointed to this project in one of its tutorials. I would like to use this standard in conjunction with the PHP-CS-Fixer by SensioLabs.

Is the standard used compatible with the Symfony2 fixes that PHP-CS will attempt to do? Thanks!

The ruleset force to add PHPDoc blocks for all methods

The Symfony coding strandard documentation states:

Add PHPDoc blocks for all classes, methods, and functions (though you may be asked to remove PHPDoc that do not add value);

For example the inherited methods should not contain any PHPDoc comments, except if we want to add additional details.

bug: Symfony.Formatting.ReturnOrThrow detects false positive for closures

Unfortunately, the following false positive

 20 | ERROR   | Do not use else, elseif, break after if and case conditions which return or throw something (Symfony.Formatting.ReturnOrThrow.Invalid)

pops up for closure, as you can see in this code

<?php

namespace Fail;

/**
 * Class PortalDataService
 */
class Clazz
{
    /**
     * @param array $arr
     *
     * @return array
     */
    public function clear($arr)
    {
        if (null !== $arr) {
            $mapped = $arr->map(
                function ($e) {
                    return '';
                }
            )->toArray();
        } else {
            $mapped = [];
        }

        return $mapped;
    }
}

This is a false positive, since the return belongs to the closure an not the function.

Symfony.Formatting.ReturnOrThrow.Invalid false positive on anonymous function

Code sample:

switch ($incident->getState()) {
    case Incident::STATE_OPENED:
        $this->considerIncident($incident);
        break;
    case Incident::STATE_CONSIDERED:
        $this->resolveIncident($incident);
        break;
    case Incident::STATE_RESOLVED:
        $publicComments = $incident->getComments()->filter(static function (IncidentComment $comment): bool {
            return true === $comment->getCustomerVisible();
        });
        $this->closeIncident($incident);
        break;
}

I have:

Do not use else, elseif, break after if and case conditions which return or throw something (Symfony.Formatting.ReturnOrThrow.Invalid)

Pointing on return true === $comment->getCustomerVisible(); of the anonymous function.

It does not seems to make any sense here.

BlankLineBeforeReturn miss reporting inside closure

This gives an error:

$arr = [];
$func = function ($item) { return $item['foo']; };

This works fine:

$arr = [];

$func = function ($item) { return $item['foo']; };

Neither should matter as the return is inside the closure scope.

fix and complete unittests

after migrating to phpcs v3 it appears that the current implementation of travis' phpunit run is ignoring all of the unittests from this repo.

this issue can be marked resolved once that is fixed and all the new sniffs are properly tested...

License agreement

Hi!

What is the license agreement for the use of this repo?

Thanks!

Undefined index: parenthesis_opener in .../Symfony/Sniffs/Errors/ExceptionMessageSniff.php on line 62

Code example:

/**
 * {@inheritdoc}
 */
public function process(ContextInterface $context, Delegate $delegate): void
{
    try {
        $delegate->process($context);
    } catch (\Throwable $t) {
        // TODO: Implement later

        throw $t;
    }
}

Error:

FILE: /.../Middleware/ExceptionInterceptorMiddleware.php
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 1 | ERROR | An error occurred during processing; checking has been aborted. The error message was: Undefined index: parenthesis_opener in
   |       | /.../vendor/escapestudios/symfony2-coding-standard/Symfony/Sniffs/Errors/ExceptionMessageSniff.php on line 62
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


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.