PHP rules in Coditive

Code formatting has nothing to do with system performance, optimization or any technical aspects. It is intended to help the whole team keep consistency, readability and conventions that are the standard in the team. The article describes formatting rules that should be applied to work smoothly in the team.

Exceptions

Consistency is key when it comes to choosing the formatting standards in the project. If you work in projects which rules are different than the default one – you should choose a coding standard that matches the project code. We should not change the existing standards.

General

The section includes rules that are consistent for the whole application.

CategoryDescription
FormattingThe last return in the function MUST be preceded with an empty line.

PHP

The rules should be applied to the code created in PHP.

CategoryDescription
ConventionThe code MUST use PSR-12 style guide.
ConventionThe code must use camelCase as naming convention for variables and properties.
ConventionThe code must use snake_case as naming convention for array keys and front-end variables.
ConventionArray shorthand [] MUST be used instead of array().
ToolsPHP Code Sniffer SHOULD be used as a linting tool in your development infrastructure
ToolsExecutable PHP version MUST match the minimal version required by coditive_ starter.
ExceptionUse 2 spaces indentation for PHP files.

Linter

No one is able to remember every single requirement specified in the documentation, so we should try to make this easier by using linters that remember about this for us.

#1 Installation

Install phpcs and make sure that is executable. You can do that by following the official instructions or installing it using homebrew. Homebrew is the preferable way because it’s easier, but feel free to choose the way.

> phpcs --version > PHP_CodeSniffer version 3.6.1 (stable) by Squiz (http://www.squiz.net)
Code language: JavaScript (javascript)

#2 Configuration

Create a new file in your home development directory named phpcs.xml that contains basic configuration for the linter. We need to create this, because we decided to use 2 spaces instead of 4 required by PSR-12 so we need to add exception.

<?xml version="1.0"?> <ruleset name="coditive"> <description>Coditive formatting rules.</description> <file>app</file> <file>resources/functions.php</file> <file>resources/index.php</file> <file>resources/views</file> <!-- 2.1 Basic Coding Standard --> <rule ref="PSR12"> <!-- 5.2 switch, case - disable due to problems wuth 2 spaces indentation --> <exclude name="PSR2.ControlStructures.SwitchDeclaration.BreakIndent" /> </rule> <!-- 2.3 Lines --> <rule ref="Generic.Files.LineLength"> <properties> <property name="lineLimit" value="140"/> </properties> </rule> <!-- 2.4 Indenting --> <rule ref="Generic.WhiteSpace.ScopeIndent"> <properties> <property name="indent" value="2" /> </properties> </rule> <!-- Custom Rules --> <rule ref="Generic.Arrays.DisallowLongArraySyntax" /> <rule ref="Generic.Formatting.SpaceAfterCast" /> <rule ref="Generic.Formatting.SpaceAfterNot" /> </ruleset>
Code language: HTML, XML (xml)

Configure your executable phpcs version to use phpcs.xml file that you’ve created standard by using the following command.

phpcs --config-set default_standard path_to_phpcs_file
Code language: JavaScript (javascript)

#3 Test

You can test if your linter works fine by validating one of the files that break some standards.

phpcs Cookies.php FILE: /Users/lorem.ipsum/Sites/coditive.com/wordpress.theme/wp-content/themes/coditive/wps/Module/Cookies.php ------------------------------------------------------------------------------------------------------------------------- FOUND 1 ERROR AND 1 WARNING AFFECTING 2 LINES ------------------------------------------------------------------------------------------------------------------------- 18 | ERROR | [x] Opening brace should be on a new line | | (Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine) 20 | WARNING | [ ] Line exceeds 120 characters; contains 126 characters (Generic.Files.LineLength.TooLong) ------------------------------------------------------------------------------------------------------------------------- PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY ------------------------------------------------------------------------------------------------------------------------- Time: 42ms; Memory: 6MB
Code language: JavaScript (javascript)

Fixer

Fixing problems automatically may be really useful, because we don’t need to spend much time trying to solve all the problems manually. It may be done by phpcbf that is installed together with phpcs so if the second one works, the fixer should also work fine. You can verify this by trying to fix all the problems available in the specific file.

phpcbf Cookies.php PHPCBF RESULT SUMMARY ------------------------------------------------------------------------------------------------------------------------------- FILE FIXED REMAINING ------------------------------------------------------------------------------------------------------------------------------- /Users/przemek.hernik/Sites/coditive.com/wordpress.theme/wp-content/themes/coditive/wps/Module/Cookies.php 1 1 ------------------------------------------------------------------------------------------------------------------------------- A TOTAL OF 1 ERROR WERE FIXED IN 1 FILE ------------------------------------------------------------------------------------------------------------------------------- Time: 67ms; Memory: 6MB
Code language: JavaScript (javascript)

VSCode

By default vscode doesn’t work with phpcs and phpcbf so we need to configure the environment.

#1 Installation

Install phpcs and phpcbf plugin.

#2 Configuration

Add proper configuration for your dev environment. Plugins will automatically use the default standard set for phpcs, but if you need to configure this value per project, please just set phpcs.standard or phpcbf.standard in your workspace settings.

{ "phpcs.enable": true, "phpcs.executablePath": "/usr/local/bin/phpcs", "phpcbf.enable": true, "phpcbf.executablePath": "/usr/local/bin/phpcbf", "[php]": { "editor.formatOnSave": true, }, }
Code language: JSON / JSON with Comments (json)

#3 Test

Open the file that breaks PSR-12 standard and save it. The plugin should automatically run phpcbf on the file and fill all the autofixable problems.

<?php use function Wps\template; use WPS\Init; ini_set('error_reporting', E_ALL); class psr1_test_class { private const constantTest = 'asd'; private $lengthTest = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest'; public function __construct() { $arrayTest = array(); } function visibilityTest() { return; } public function naming_convention_test() { echo 'test'; } private function keywordsTest(STRING $param): void { return; } public function classInitializationTest(): void { $test = new Init; } public function argumentsTest( string $param = '',bool & $test):void { return; } public function controlStructuresTest(string $param): string { if(!true) { return ''; } elseif(true) { return ''; } else { return ''; } switch ($param) { case 'value': return ''; default: return ''; } } public function operatorsTest(): void { $i = 0; $i ++; $i = ( int ) $i; if ($i===1) { return; } $i = $i === 1 ? 0 :1; } } ?>
Code language: HTML, XML (xml)

Summary

Such linting tools and specific rules allow to reduce the number of most common issues and keep the codebase uniform within the company.

Add the first comment and start a discussion

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Cookies

Service namePurposeSettings
Cookies funkcyjneCookies required for the operation of the website.