To adapt your Laravel code style to use the K&R style with PHP CS Fixer, you need to create a custom configuration file for PHP CS Fixer. Here’s how you can do it:
-
Install PHP CS Fixer: If you haven't already installed PHP CS Fixer, you can do so via Composer:
composer require --dev friendsofphp/php-cs-fixer -
Create a Configuration File: Create a
.php-cs-fixer.phpfile in the root of your project. This file will contain the configuration for PHP CS Fixer. -
Configure PHP CS Fixer: In your
.php-cs-fixer.phpfile, you can specify the rules to enforce the K&R style. Here’s an example configuration:<?php $finder = PhpCsFixer\Finder::create() ->in(__DIR__) ->exclude('vendor') ->name('*.php') ->notName('*.blade.php'); return PhpCsFixer\Config::create() ->setRules([ '@PSR2' => true, 'braces' => [ 'position_after_functions_and_oop_constructs' => 'same', 'position_after_control_structures' => 'same', 'position_after_anonymous_constructs' => 'same', ], 'indentation_type' => true, 'line_ending' => true, 'no_trailing_whitespace' => true, 'no_trailing_whitespace_in_comment' => true, 'single_blank_line_at_eof' => true, ]) ->setFinder($finder);This configuration sets the braces style to K&R (same line for control structures and functions) and includes some other common rules.
-
Run PHP CS Fixer: You can now run PHP CS Fixer to apply the style to your codebase:
vendor/bin/php-cs-fixer fix
This will format your code according to the specified rules, including the K&R style for braces.
Example
Given your example code:
if (something == true) {
do_this_about_it();
} else {
do_this_instead();
}
After running PHP CS Fixer with the above configuration, it should remain in the K&R style.
Additional Customization
If you need further customization, you can refer to the PHP CS Fixer documentation for more rules and options to tailor the configuration to your exact preferences.
By following these steps, you should be able to enforce your preferred K&R style in your Laravel project using PHP CS Fixer.