Giter Site home page Giter Site logo

friendsofphp / php-cs-fixer Goto Github PK

View Code? Open in Web Editor NEW
12.5K 214.0 1.5K 31.54 MB

A tool to automatically fix PHP Coding Standards issues

Home Page: https://cs.symfony.com

License: MIT License

PHP 99.93% Shell 0.05% Dockerfile 0.02% Ruby 0.01%
php static-analysis code-style code-standards hacktoberfest

php-cs-fixer's Introduction

PHP CS Fixer logo

PHP Coding Standards Fixer

The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., or other community driven ones like the Symfony one. You can also define your (team's) style through configuration.

It can modernize your code (like converting the pow function to the ** operator on PHP 5.6) and (micro) optimize it.

If you are already using a linter to identify coding standards problems in your code, you know that fixing them by hand is tedious, especially on large projects. This tool does not only detect them, but also fixes them for you.

Supported PHP Versions

  • PHP 7.4
  • PHP 8.0
  • PHP 8.1
  • PHP 8.2
  • PHP 8.3

Note Each new PHP version requires a huge effort to support the new syntax. That's why the latest PHP version might not be supported yet. If you need it, please, consider supporting the project in any convenient way, for example with code contribution or reviewing existing PRs. To run PHP CS Fixer on yet unsupported versions "at your own risk" - leverage the PHP_CS_FIXER_IGNORE_ENV.

Documentation

Installation

The recommended way to install PHP CS Fixer is to use Composer in a dedicated composer.json file in your project, for example in the tools/php-cs-fixer directory:

mkdir -p tools/php-cs-fixer
composer require --working-dir=tools/php-cs-fixer friendsofphp/php-cs-fixer

Or using the main composer.json:

composer require --dev friendsofphp/php-cs-fixer

For more details and other installation methods, see installation instructions.

Run with Docker

You can use pre-built Docker images to run php-cs-fixer.

docker run -v $(pwd):/code ghcr.io/php-cs-fixer/php-cs-fixer:${FIXER_VERSION:-3-php8.3} fix src

$FIXER_VERSION used in example above is an identifier of a release you want to use, which is based on Fixer and PHP versions combined. There are different tags for each Fixer's SemVer level and PHP version with syntax <php-cs-fixer-version>-php<php-version>. For example:

  • 3.47.0-php7.4
  • 3.47-php8.0
  • 3-php8.3

Usage

Assuming you installed PHP CS Fixer as instructed above, you can run the following command to fix the PHP files in the src directory:

tools/php-cs-fixer/vendor/bin/php-cs-fixer fix src

See usage, list of built-in rules, list of rule sets and configuration file documentation for more details.

If you need to apply code styles that are not supported by the tool, you can create custom rules.

Editor Integration

Dedicated plugins exist for:

Community

The PHP CS Fixer is maintained on GitHub at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer. Bug reports and ideas about new features are welcome there.

You can reach us in the GitHub Discussions regarding the project, configuration, possible improvements, ideas and questions. Please visit us there!

Contribute

The tool comes with quite a few built-in fixers, but everyone is more than welcome to contribute more of them.

php-cs-fixer's People

Contributors

backendtea avatar ceeram avatar clxmstaab avatar derrabus avatar dmvdbrugge avatar fabpot avatar gharlan avatar grahamcampbell avatar hypemc avatar jrmajor avatar julienfalque avatar keradus avatar ktomk avatar kubawerlos avatar localheinz avatar maks3w avatar mvorisek avatar ntzm avatar paulbalandan avatar paulhenri-l avatar seldaek avatar slamdunk avatar soullivaneuh avatar spacepossum avatar sstok avatar staabm avatar stof avatar ucirello avatar vincentlanglet avatar wirone 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  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

php-cs-fixer's Issues

Case sensitive problem for Namespaces (--level=all)

In my file, I used this namespace call:

use Symfony\Component\Security\Acl\Voter\AclVoter as BaseAclVoter;

and my class by mistake extended baseAclVoter that way:

class AclVoter extends baseAclVoter {

The use of the PHP CS Fixer in level=all caused the unwanted deletion of the use statement above.

weird issue with quotes in string in "include" fixer

This is a bit annoying, but my request validation code keeps getting borked up by the "include" fixer.

This:

<?php
exit('POST must include "file"');

becomes:

exit('POST must include 'file'');

For some reason, the word "file" (with double-quotes) is changed to have single-quotes. This, of course, makes the line invalid (the first single-quote string is now terminated prior to the word "file" and the word "file" is just dangling out in the open.

Feature: add a dry-run option

It would be great to be able to list all files in which changes would be done without applying them for real (to see if it would impact some files that should be excluded, like the IDE settings, for instance)

Remove closing PHP tags on class files

Currently (d7e28bd) the fixer adds newlines at the and of files, even if someone put a closing PHP tag at the end of a file. Because I ran into problems with newlines after closing tags, I thought it could introduce problems running the fixer in case of closing tags.
Could the fixer remove those closing PHP tags on class files?

Indentation problem?

I ran it on a sample of our code, and it did not indent 4 spaces, it left the indentation at 2 spaces.

Fix includes

I would like to have fixer for include, require, require_once...statements, and I would like to contribute one.

But before I start working on this (since I know many projects use autoload and do not need this), I would like to know if something like this will be merged?

Here is example of what I want to cover with this:

require_once( 'file.php' ) -> require_once 'file.php'

Also, Some parts maybe can be covered in new ControlSpacesFixer method. Removing brackets maybe belong to new IncludeFixer.

Feedback?

Use of src/ and test/ directories?

Is there any reason that this library does not use a src and test directory in the root directory? I can understand just mixing the tests within the source directory under Tests, but not the former.

PHP Closing Tag

Auto-remove PHP closing tag if it is on last line in a file,
or it's followed only by spaces and newlines and nothing more.

Isn't ?> at the end of file bad practice?

braces, problem with comment and if

In case of code with comment after the if (I know this is bad, but it exists in our code)

example :
if (true) // this is true
{
// ...
}

the braces added the bracket after the comment, then the syntax is not correct
if (true) // this is true {
// ...
}

New line before return adds new line inside string

Before:

throw new Exception("MyClass::myMethod($param1, $param2)
            returned: $status,
            p3=$p3, p4=$p4,
            p5=$p5, style=$style", ERROR_CODE);

After:

throw new Exception("MyClass::myMethod($param1, $param2)

            returned: $status,
            p3=$p3, p4=$p4,
            p5=$p5, style=$style", ERROR_CODE);

Incrementor in for loop not corrected

Incrementor in for loop is not being corrected:

for ($i = 0; $i < $length; $i ++){

is not converted to the expected

for ($i = 0; $i < $length; $i++){

In other words, $i ++ should be converted to $i++

Invalid code generated for files ending in .class.php

If I have the folllowing class

<?php
namespace Tim;

class Test
{

}

Saved in a file in lib/Tim/Test.class.php
The class becomes

<?php
namespace Tim;

class Test.class
{

}

Upon running the command

php php-cs-fixer.phar fix lib/Tim/Test.class.php (using version 0.2)

Expected - a warning is raised about the filename not matching PSR-0 standards, possibly move the file to have just a .php extension

Add --strict option in FixCommand

Some files are currently ommited in UnusedUseStatementsFixer and Psr0Fixer (tests, fixtures, stubs). There is no way to change this behaviour without alerting code. The point of --strict option would be to include those files.

Bug with static variables

The fixer (using --level=all) incorrectly adds public to statics that are part of a function/methods and not a class static
e.g.

public function foo()
{
    static $something;
}

becomes

public function foo()
{
    public static $something;
}

leading to a syntax/parse error.

Feature: Allow to set file or directory as argument

I would like to know if you're interested about adding the possibility to set a file or directory argument on fix command.

I think it could be useful because we may not want to apply cs fix on each files of projects/dir each time we edit a file.

I can make a PR if you're OK

Scope of isset function

This will be modified to

if (!function_exists('myFunc')) {
    function myFunc() {return true;}
}

Becomes

if (!function_exists('myFunc')) {
    public function myFunc() {return true;}
}

[RFC] Fixing files with one fixer or a list of fixers but not all

Hi,

It would be great if we could choose to run only one single fixer (or a list of selected fixer) on files by appending an extra argument to the command line:

php php-cs-fixer fix /path/to/project --fixer=indentations --fixer=curly-braces ...

To do that, we can add a new getName method to the FixerInterface that returns the single identifier of the fixer. We can also add an extra getDescription method that returns a simple sentence describing the fixer (for displaying a list of all registered fixers in a new command for example).

What do you think about that?

I can work on it if you think it's usefull.

no --dry-run?

Wouldn't hurt to show what is changed, before I commit to running fix on a code base.

Extra whitespace for classes declaration

I'm not much familiar with PSR(s), so I'd like to ask - when class declaration is padded with 4 spaces (or more), they are not removed. Example:

    class Test
    {
    }

should it be fixed to become:

class Test
{
}

Thanks!

Symfony upgrade fixers

Just some idea that come to my mind.

Maybe it can be interesting to use this project and build Symfony-Upgrade-Fixer. That can be independent project with fixers which will help people to upgrade their existing projects to new version of Symfony framework.

I find myself find-replacing code to upgrade to latest Symfony version.

One example is latest changes in Form component:

Before:

public function buildForm(FormBuilder $builder, array $options)
public function buildView(FormView $view, FormInterface $form)
public function buildViewBottomUp(FormView $view, FormInterface $form)

After:

public function buildForm(FormBuilderInterface $builder, array $options)
public function buildView(FormViewInterface $view, FormInterface $form, array $options)
public function buildViewBottomUp(FormViewInterface $view, FormInterface $form, array $options)

which is totally doable with a simple fixer.

Spaces in conditional not corrected

When doing a conditional with extra spaces, they are not corrected:

if( SomeClass::doSomething( self::SOME_VALUE ) ) 

is converted to the following

if ( SomeClass::doSomething( self::SOME_VALUE ) ) 

instead of:

if (SomeClass::doSomething(self::SOME_VALUE)) 

Allow user to fix other path than "src"

as in title this will be good for bundle developers to be able to check/fix for example also in certain path under vendor where is natural place for external bundles/libs.

code not cs fixed

I got such part of my not cs valid code which is not touched by fixer:

    public function importAction()
    {
        $repository = $this->getDoctrine()
                           ->getRepository( 'ToolsTFIBundle:Quotes' );
        $query = $repository->createQueryBuilder( 'f' )
                            ->leftjoin( 'c.funds', 'f' )
                            ->where( 'f.status = 1' );
        $companies = $query->getQuery()->getResult();

    }

other example:

            fclose( $quoteFileHandle );

            $this->lastUpdateDate->setTime( (int) $currentDate->format( 'H' ), (int) $currentDate->format( 'i' ) );
            $lastUpdateSetting->setValue( $this->lastUpdateDate->format( 'Y-m-d H:i' ) );
            $this->em->persist( $lastUpdateSetting );
            $this->em->flush();

            unset( $this->fundList )

Support JavaScript files?

I know that it's PHP-CS-Fixer. But XML, YML, Twig files are already parsed. How about JavaScript?

I know I can specify which files to parse in .php_cs but most fixers check if the file ends with PHP extension.

What do you think about adding support of JS extension in some fixers where it would make sense? E.g. CurlyBracketsNewlineFixer, PhpdocParamsAlignmentFixer, ReturnStatementsFixer, IndentationFixer.

SplFileInfo and getExtension

Running 'php-cs-fixer.phar fix' command on PHP version < 5.3.6 (I checked it out on PHP 5.3.3-1ubuntu9.5 with Suhosin-Patch (cli))
will result in PHP Fatal error: Call to undefined method SplFileInfo::getExtension() in phar:///home/user/php-cs-fixer.phar/Symfony/CS/Fixer/VisibilityFixer.php on line 75 (probably because of this http://www.php.net/manual/pl/splfileinfo.getextension.php)

Maybe it'd be better to change it to '$extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION)', like php manual suggests for PHP versions < 5.3.6 ? I'm stressing it out because getExtension is the only one among SplFileInfo methods that requires PHP version > 5.2.2.

I couldn't find any information of this project miminum PHP version, but as far as I know symfony2 itself needs at least PHP 5.3.2 (http://symfony.com/doc/current/reference/requirements.html), so imho it would be nice to keep similiar requirenments for it? What do you think?

Problem with visibility and static

When a static variable is defined inside a method, the visibility filter add a public statement just before and the php 5.3 crashes.

For example :

class C
{
public function f()
{
static $var = 0; // would be converted to public static $var = 0;
}
}

Visibility flag not working

I'm trying to apply all standards excepted one that I disagree with (in this case, spaces instead of tabs). So what I did is I ran a command with all flags excepted that one

php php-cs-fixer.phar fix folder/ --fixers=linefeed,trailing_spaces,visibility,unused_use,return,short_tag,extra_empty_lines,phpdoc_params,eof_ending,elseif,braces,controls_spaces

Now although the visibility fixer flag is indeed present, none of the visibility issues got fixed.
Instead if I do the following :

php php-cs-fixer.phar fix folder/

It gets fixed as it should be. Am I doing something wrong here ?


Note : Even if this is just a minor bug, a way to work the fixers by exclusion would be a really good add. Like that :

php php-cs-fixer.phar fix folder/ --fixers!=indentation,braces

.phar file missing

After last commits php-cs-fixer.phar file is missing in sources to download.

EDIT: found why.

php_closing_tag removed where they shouldn't

Two cases where php_closing_tag is removing ?> when it shouldn't :

Output buffer :

// Middle of a PHP file
ob_start();
?>
    <div>
        <p>foo bar</p>
    </div>
<?php
ob_end_flush();

XML work

$xml = '<?xml version="1.0" encoding="UTF-8"?>';

The ?> in both previous declarations will be removed.

Spaces under brackets are not fixed for if statements

controls_spaces fixer does not handle cases like this:

Original: if( $test ){
Fixed: if ( $test ) {
Expected: if ($test) {

I experimented a bit and managed to fix this issue, but I have some weird case when it does not work.

Works for if ($this->tesT ($test)) {
Does not work for: if ($this->testtesT ($test)) {

Since I'm not a regex guru, this is a call for regex ninjas to take a look at my fix and help me finish it, or suggest new solution. I'm opened for all suggestions. Thanks in advance.

Combining level and fixers

Is there currently a way to combine level and fixers such that it is easier to manage the differences between the psr levels and the all level? I was hoping the following would work:

php php-cs-fixer.phar fix . \
    --level=psr2 \
    --fixers=unused_use,return,extra_empty_lines,eof_ending,controls_spaces

However, it appears that if fixers are specified the level is ignored.

Feature: allow to exclude some paths when running the command

When working on a bundle, I would like to be able to run the CS-fixer on the repo without messing with the metadata of my IDE (i.e. excluding the .idea folder). Using a custom finder (as done for Symfony) is not an option as it would require changing the code of the fixer itself to add the class.

Closure space fixer

Hi,
I noticed that the fixer do not cover the case of missing space between brackets in closure, like in:

array_walk($things, function($v, $k){ // <--
    // ...
});

Issue with docblock spacing

When using --level=all the fixer is incorrectly adding spaces to docblocks in some circumstances:

    /**
     * Set owner
     *
     * @param string $owner
     * @return HookProvider
     */

becomes

    /**
     * Set owner
     *
     * @param  string       $owner
     * @return HookProvider
     */

It seems to be getting aligned to the return statement. If there is no return statement it gets aligned correctly. If there is a blank line after the last @param statement, the params are also correctly aligned.

Ternary operator fix

Any thoughts about fixing this?

$val = (expression)?true:false into $val = (expression) ? true : false;

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.