PHP.Style ✨

A guidebook to writing prettier PHP, faster!

🏗 Getting started is easy!

Install php-cs-fixer

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

Create a .php-cs-fixer.dist.php configuration file. (these rules are just a suggestion!)

<?php
$finder = (new PhpCsFixer\Finder())
    ->in(__DIR__);

return (new PhpCsFixer\Config())
    ->setRules([
        '@PhpCsFixer' => true,
        '@DoctrineAnnotation' => true,
        'blank_line_before_statement' => ['statements' => ['return']],
        'concat_space' => ['spacing' => 'one'],
        'declare_parentheses' => true,
        'global_namespace_import' => true,
        'increment_style' => false,
        'multiline_whitespace_before_semicolons' => ['strategy' => 'no_multi_line'],
        'phpdoc_line_span' => ['property' => 'single'],
        'phpdoc_separation' => false,
        'phpdoc_summary' => false,
        'php_unit_internal_class' => false,
        'php_unit_test_class_requires_covers' => false,
        'single_line_throw' => false,
        'yoda_style' => false,
    ])
    ->setFinder($finder);

Run the fixer

./tools/php-cs-fixer/vendor/bin/php-cs-fixer fix
That's all, re-run the fixer anytime files change!

Want to see a preview of these rules?

<?php class AFormattingNightmare {
/**   @var string    */
var $private;
public function __construct(){ $array = array('wait'=>'itgetsworse');
    $bool = (BOOLEAN) 1;
    $ternaries=$bool?0 : 1;
    if ($bool) { echo 'hello' ; } else
        if ($ternaries === 1) { echo "goodbye";   }
} function dosomething(): ?string {
    return ""; }

}

$nightmare=new AFormattingNightmare() ;
<?php

class AFormattingNightmare
{
    /** @var string */
    public $private;

    public function __construct()
    {
        $array = ['wait' => 'itgetsworse'];
        $bool = (bool) 1;
        $ternaries = $bool ? 0 : 1;
        if ($bool) {
            echo 'hello';
        } elseif ($ternaries === 1) {
            echo 'goodbye';
        }
    }

    public function dosomething(): ?string
    {
        return '';
    }
}

$nightmare = new AFormattingNightmare();
                            

Configuration Tips

PhpCsFixer\Finder uses the Symfony Finder component. You can exclude paths like

$finder->notPath(['excluded/path']);

or include additional paths like

$finder->path(['include/path']);

Style Guide

PHP Standards for style are mature but not comprehensive, PSR-1 and PSR-12 have been mature for years but haven't received updates for the latest versions of PHP which introduce new features that need to be considered.

Most developers adjust style some for their individual projects. Make it your own! Need some inspiration while setting up your project? Check out how these popular projects are configured.

Resources

Documentation is available on the php-cs-fixer website & github.

Thanks!

I hope this quick introduction helps, feel free to leave feedback or comments on github!