Difference between revisions of "Joomla CodeSniffer"

From Joomla! Documentation

(→‎Eclipse: + PHP Tools fix)
(Removed dead URLs to screenshots.)
 
(58 intermediate revisions by 14 users not shown)
Line 1: Line 1:
== A Nose For Joomla ==
+
<noinclude><languages /></noinclude>
 
 
This is a custom coding standard for the PHP CodeSniffer that attempts to codify and enforce the Joomla coding standards. This article covers how to set the automatic code style checker.
 
  
 +
<translate>
 +
== A Nose For Joomla == <!--T:1-->
 +
</translate>
 +
<translate><!--T:2--> This is a custom coding standard for the PHP CodeSniffer that attempts to codify and enforce the Joomla coding standards. This article covers how to set the automatic code style checker. It consists of three steps:</translate>
 +
<translate><!--T:3-->
 +
# Install PHP CodeSniffer (phpcs).
 +
# Clone the Joomla Code Style (for use with for phpcs).
 +
# Configure your IDE to work with PHP CodeSniffer and Joomla Code Style.</translate>
  
 
[[File:CodeSnifferInAction.jpg|center|thumb|300px|PHP Code Sniffer in action]]
 
[[File:CodeSnifferInAction.jpg|center|thumb|300px|PHP Code Sniffer in action]]
  
==Why?==
+
<translate>
 +
==Why?== <!--T:4-->
 +
</translate>
 +
<translate><!--T:5--> *Coherent and consistent coding practice makes the files look more professional. Conflicting styles in the same project (or worse, the same file) not only look sloppy, they encourage further sloppiness.</translate>
 +
<translate><!--T:6--> *When all code complies with the same standard, bad code is easier for everyone to spot.</translate>
 +
<translate><!--T:7--> *It makes it easier for someone new to a particular file in the project to find and fix errors or extend functionality.</translate>
 +
<translate><!--T:8--> *If there is no consistent standard maintained, sometimes developers will reformat the code to suit themselves. This causes a wide range of changes in the code repository. If there is a later problem, a significant change could be lost in the chaff produced by a diff.</translate>
  
- Coherent and consisting coding practice makes the files look more professional. Conflicting styles in the same project (or worse, the same file) not only look sloppy, they encourage further sloppiness.
+
<translate>
 +
==Installation of PHP Code Sniffer (phpcs)== <!--T:9-->
 +
</translate>
 +
<translate>
 +
===Composer=== <!--T:10-->
 +
</translate>
 +
<translate><!--T:11--> PHP Code Sniffer is available via Composer. It can be installed system-wide with the following command:</translate><br />
 +
''composer global require --dev squizlabs/php_codesniffer "~3.5"''
 +
<translate>
 +
<!--T:12-->
 +
On '''Linux''' PHP Code Sniffer (phpcs) will be installed under your user folder:</translate>
 +
* <translate><!--T:13--> Symbolic Link:</translate> ''~/.composer/vendor/bin/phpcs''
 +
* <translate><!--T:14--> The file:</translate> ''~/.composer/vendor/squizlabs/php_codesniffer/scripts/phpcs''
 +
<translate><!--T:76--> To create that symbolic link, use on the command line: </translate>
 +
''$ sudo ln -s ~/.config/composer/vendor/squizlabs/php_codesniffer/scripts /usr/bin/phpcs''
  
- When all code complies with the same standard, bad code is easier for everyone to spot.
+
<translate><!--T:15--> or (for example OpenSuse)</translate>
 +
* <translate><!--T:16--> Symbolic Link:</translate> ''~/.config/composer/vendor/bin/phpcs''
 +
* <translate><!--T:17--> The file:</translate> ''~/.config/composer/vendor/squizlabs/php_codesniffer/scripts/phpcs''
  
- It makes it easier for someone new to a particular file in the project to find and fix errors, or extend functionality.
+
<translate><!--T:18--> On '''Windows''' PHP Code Sniffer (phpcs) will be installed under your user folder:</translate>
 +
* <translate><!--T:19--> Symbolic Link:</translate> ''c:\Users\Username\AppData\Roaming\Composer\vendor\bin\phpcs''
 +
* <translate><!--T:20--> The file:</translate> ''c:\Users\Username\AppData\Roaming\Composer\vendor\squizlabs\php_codesniffer\scripts\phpcs''
  
- If there is no consistent standard maintained, the sometimes developers will reformat the code to suit themselves. This causes a wide range of changes in the code repository, and if there is a later problem, a significant change could be lost in the chaff produced by a diff.
+
<translate>
 +
=== Add composer bin directory to your $PATH === <!--T:21-->
 +
</translate>
 +
<translate>
 +
<!--T:22-->
 +
In order to execute PHP Code sniffer from anywhere on Linux or Mac command line you have to add ''.composer/vendor/bin'' to your $PATH variable.</translate>
 +
<translate>
 +
<!--T:23-->
 +
To do this persistent edit your shells start file, like your .profile or .bash_profile file depending which shell you are using (echo $SHELL shows you which one you are using).</translate>
  
==Installation==
+
<translate><!--T:24--> Add the following line to the file:</translate>
 +
''export PATH=$PATH:~/.composer/vendor/bin''
  
First of all you have to install the [http://pear.php.net/package/PHP_CodeSniffer/ PHP CodeSniffer]. This set of files is intended to work with phpcs version 1.4, so behavior with any other version is undefined. One way to do this is to start the console (cmd.exe in windows environments) and type:
+
<translate><!--T:25--> Alternatively you can also create a symbolic link in the bin folder:</translate>
 +
''ln -s ~/.composer/vendor/bin/phpcs /usr/local/bin/phpcs''
  
<code>pear install PHP_CodeSniffer</code>
+
<translate>
 +
==Install Joomla Coding Standards== <!--T:26-->
 +
</translate>
 +
<translate><!--T:27--> In order to have PHP Code Sniffer (phpcs) sniffing your Joomla projects for the right code style, you have to install the Joomla Coding Standards.</translate>
  
To specify a specific version of the PHP CodeSniffer, type:
+
<translate><!--T:28--> Using composer we can execute:</translate>
 +
''composer global require --dev joomla/coding-standards "~3.0@alpha"''
  
<code>pear install PHP_CodeSniffer-1.5.x</code> (specify a number for x, in June 2014 was 1.5.3)
+
<translate><!--T:29--> Notice that it says ''@alpha'', that is because the coding standard is still in alpha state and we need to allow the installation of alpha status code. If we do not include the @alpha the coding standards will not install and throw this error.</translate>
  
'''Important note:''' currently the latest PHPcs  is the 2.x series. But they are under development so Joomla Sniffers are not yet compatible with this version. PEAR gives you the option to install it by default but since Joomla sniffers will not work remind to always install PHPCS 1.5. version not 2.0.
+
<pre>
 +
Your requirements could not be resolved to an installable set of packages.
  
Pear will handle the whole installation by itself.
+
Problem 1
 +
- The requested package joomla/coding-standards ~3.0 is satisfiable by joomla/coding-standards[3.0.0-alpha, 3.0.0-alpha2, 3.x-dev] but these conflict with your requirements or minimum-stability.
 +
</pre>
  
Then download and unzip the [https://github.com/joomla/coding-standards Joomla! CodeSniffer] and copy the contents of it into /path/to/PHP_CodeSniffer/Standards/Joomla.
+
<translate><!--T:30--> Once the installation is done the coding standard will be installed in the global composer folder. The location of this folder depends on your operating system. Some popular locations are:</translate>
  
In Unix systems this path is usually /usr/lib/php/PHP/PHP_CodeSniffer/Standards/Joomla but this varies from system to system. In Xubuntu 12.04, the path is /usr/share/php/PHP/CodeSniffer/Standards/Joomla.
+
'''Mac / Linux'''
Windows based system with XAMPP have the following path: PATH_TO_XAMMP\php\PEAR\PHP\CodeSniffer\Standards (for example: C:\xampp\php\PEAR\PHP\CodeSniffer\Standards)
 
  
Use
+
''~/.composer/vendor/joomla/coding-standards/''
 +
and
 +
''~/.config/composer/vendor/joomla/coding-standards/''
  
<code>pear config-get php_dir</code>
+
'''Windows'''
  
to find out where the PEAR directory is on your system, then add "/PHP/PHP_CodeSniffer/Standards" to it.
+
''c:\Users\Username\AppData\Roaming\Composer\vendor\joomla\coding-standards\''
  
== Usage ==
+
<translate><!--T:31--> This is using Composer on Windows.</translate>
  
You invoke the custom standard by
+
<translate><!--T:32--> If you can't find it in any of the above folders, note that the folder you are looking for ends with ''\joomla\coding-standards\''.</translate>
 +
<translate>
 +
<!--T:33-->
 +
Finally we need to tell Code Sniffer that the Joomla coding standards exist.</translate>
  
<code>phpcs --standard=Joomla file/to/sniff</code>
+
<translate><!--T:34-->
 +
'''Install Joomla Coding Standards'''
 +
# Check if certain paths are already set by running ''phpcs --config-show''
 +
# You can get an answer that looks like this: ''installed_paths: /path/to/installation''
 +
# In step 2, if you see the '''installed_paths''' you need to copy that
 +
# Set the Joomla Coding Standards path in phpcs by executing ''phpcs --config-set installed_paths /Users/user/.composer/vendor/joomla/coding-standards''. If you copied any paths in step 2, include them here as well by separating them with a comma. The command looks like ''phpcs --config-set installed_paths [/to/path1],[/to/path2],[/Users/user/.composer/vendor/joomla/coding-standards]''
 +
# Verify the path is set correctly by running ''phpcs --config-show''
 +
# Verify that phpcs can see the Joomla codestyle by running ''phpcs -i''
 +
# The output should look like this: ''The installed coding standards are MySource, PEAR, PHPCS, PSR1, PSR2, Squiz, Zend and Joomla''</translate>
 +
<translate>
  
To test a platform file using the provided platform coding standards use
+
== Usage == <!--T:35-->
 +
</translate>
 +
<translate><!--T:36--> You invoke the custom standard by</translate>
 +
''phpcs --standard=Joomla file/to/sniff''
  
<code>phpcs --standard=build/phpcs/Joomla path/to/file/or/folder</code>
+
<translate><!--T:37--> To test a platform file using the provided platform coding standards, use</translate>
 +
''phpcs --standard=build/phpcs/Joomla path/to/file/or/folder''
  
Further documentation on the use of phpcs can be found at: [http://pear.php.net/package/PHP_CodeSniffer/docs]
+
<translate><!--T:38--> Further documentation on the use of phpcs can be found at the [https://pear.php.net/package/PHP_CodeSniffer/docs pear.php.net website].</translate>
  
==IDE integration==
+
<translate>
 +
==IDE Integration== <!--T:39-->
 +
</translate>
 +
<translate><!--T:40--> Everybody loves the console. It is, with no doubt, the most effective way to do whatever you need to do. Sometimes even Linux gurus need a little bit of comfort.</translate>
  
While everybody loves the console as it is with no doubt the most effective way to do whatever you need to do.. sometimes even linux gurus need a little bit of comfort.
+
<translate><!--T:41--> Fortunately there is a plug-in available for PhpStorm, Eclipse and Netbeans that integrates the CodeSniffer into your favourite IDE, so any coding standard violations are shown like "normal" errors.</translate>
  
Fortunately there is a plugin available for Eclipse, Netbeans and PHP Storm that integrates the CodeSniffer into your favorite IDE, so any coding standard violations are shown like "normal" errors.
+
<translate>
 +
=== PhpStorm === <!--T:42-->
 +
</translate>
 +
<translate><!--T:43--> Code Sniffer is supported out of the box in PhpStorm. Go to Settings and under {{rarr|Editor,Inspections}} you will see the list of sniffers you have installed.</translate>
 +
<translate>
 +
==== Set Path to Code Sniffer ==== <!--T:44-->
 +
</translate>
 +
<translate><!--T:45-->
 +
# Open Settings (CTRL-ALT-S / CMD-,)
 +
# Go to Languages & Frameworks
 +
# Click on PHP
 +
# Click on Quality Tools
 +
# Click on PHP cs fixer dropdown arrow
 +
# The configuration is set to Local by default
 +
# Click on the 3 dots behind it to open the configuration screen
 +
# The first option is the PHP Code Sniffer (phpcs) path
 +
# Click on the 3 dots behind the path to select the location of the phpcs file. See above on where phpcs may be installed on your site
 +
# Click on Validate to make sure the path is correct and phpcs is working
 +
# Click OK</translate>
  
=== Netbeans ===
+
<translate>
 +
===== Activating the Joomla Code Style ===== <!--T:46-->
 +
</translate>
 +
<translate><!--T:47-->
 +
# Open Settings (CTRL-ALT-S / CMD-,)
 +
# Go to Editor
 +
# Click on Inspections
 +
# In the list, go to PHP
 +
# Click on PHP Code Sniffer Validation
 +
# Click on the check box behind it to activate it
 +
# Click the Reload button (2 arrows) to force a reload of rules from disk
 +
# Joomla should now be available in the list. See following image:{{-}}[[File:PhpStorm8CodeSniffer.png|PHPStorm CodeSniffer|500px]]
 +
# Click OK</translate>
  
For netbeans you have to install the sniffer plugin first. You can download the plugin [http://sourceforge.net/projects/phpmdnb/files/nbm/ here].
+
<translate>
 +
==== PHP PSR-0, PSR-1 and PSR-2 ==== <!--T:48-->
 +
</translate>
 +
* https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
 +
* https://github.com/pmjones/fig-standards/blob/psr-1-style-guide/proposed/PSR-1-basic.md
 +
* https://github.com/pmjones/fig-standards/blob/psr-1-style-guide/proposed/PSR-2-advanced.md
  
# Start your netbeans IDE
+
<translate>
# Open Tools => Plugins => Downloaded and press ''Add Plugin''
+
===== Using PHP PSR-1 and PSR-2 Sniff ===== <!--T:49-->
# Choose the loaded nbm file and confirm the installation
+
</translate>
# Now there is a new tab in Tools => Options => PHP called "PHPCodeSniffer"
+
<translate><!--T:50--> A CodeSniffer sniff to check against the PSR-x Coding Standard can be used as well. In that case you can select a different standard than Joomla.</translate>
# You have to set the path to the ''phpcs.bat'' from the installed PHP_CodeSniffer PEAR package
+
<translate>
#* for Unix based systems the path is something like /usr/bin/phpcs
+
===== Using Joomla Code style ===== <!--T:51-->
#* in XAMPP (windows) you can find the file in the php root folder (e.g. C:\xampp\php\phpcs.bat)
+
</translate>
# As "standard" type "Joomla" to use the Joomla! standard
+
<translate><!--T:52--> It's nice to be able to check that the standards are respected. It's even nicer if PhpStorm helps you format properly too as you are coding.</translate>
# now you can click ''test Settings'' to check the settings and finish the installation by pressing ''Ok''
+
<translate><!--T:53-->
# Open he task window (Window => Tasks) to sniff your code.
+
To use the Joomla code style in PhpStorm
# Most time it is a good idea to filter the task (show only in edited file or create an own filter which displays only sniff errors)
+
# Open Settings (CTRL-ALT-S / CMD-,)
 +
# Go to Editor
 +
# Click on Code Style
 +
# Select Joomla from the Scheme select box</translate>
  
=== Eclipse ===
+
<translate>
[[Image:eclipse_pti.png|left|thumb|200px|1) Eclipse PTI]]
+
==== PhpStorm / Alternative Method ==== <!--T:54-->
 +
</translate>
 +
<translate><!--T:55--> '''NOTE''': This method is '''outdated''', but it might be useful if you are looking for a different integration. It also demonstrates the use of external tools in PhpStorm - so it ''shouldn't be deleted''.</translate>
  
 +
<translate><!--T:77--> The Code Sniffer can also be integrated easily as an external tool. PhpStorm will display the output in the console, including click-able links containing line and column numbers to the files that contain errors.</translate>
  
<div style="clear: both"></div>
+
<translate><!--T:56-->
Installation is a breeze and follows the usual pattern:
+
* Click on "Settings" and search for "External tools"
# <tt>Help => Install new Software...</tt>
+
* Click "Add..."
# <tt>Work with:</tt> Fill in one of the update site URLs found here: http://www.phpsrc.org/eclipse/pti/
+
* Choose a "Name", "Group" and "Description".
# Select the desired tools
+
* Click "Output Filters"
# Restart Eclipse.
+
** Click "Add...", Choose a name and enter under "Regular expression to match output" the value: ''$FILE_PATH$:$LINE$:$COLUMN$''
 +
* "Program": Search for the phpcs executable on your system. You have to set the path to the ''phpcs.bat'' from the installed PHP_CodeSniffer PEAR package
 +
** For Unix based systems, the path is something like /usr/bin/phpcs
 +
** In XAMPP (windows), you can find the file in the PHP root folder (e.g. C:\xampp\php\phpcs.bat)
 +
* "Parameters":
 +
** ''--standard=<path/to/joomla-platform>/build/phpcs/Joomla'' The path to the Joomla! coding standards.
 +
** ''--report=emacs'' The will generate a simple list containing links to the error files
 +
** Optionally you may want to specify ''-p'' for "progress" or ''-n'' for "errors only".
 +
** The last parameter has to be ''$FilePath$'' specifying the file or folder you want to sniff.</translate>
  
[[Image:eclipse_pti_settings.png|right|thumb|150px|2) Eclipse PTI settings]]
+
<translate><!--T:57--> A typical "Parameters" line on a Linux system might look like this:</translate>
You are now able to sniff for code violations against common standards like PEAR or Zend etc.
 
  
To sniff against your own standards, all you have to do is specify their location and activate them (see screen shot 2)
+
''-np --standard=/home/elkuku/libs/joomla/build/phpcs/Joomla --report=emacs $FilePath$''
  
# <tt>Window => Preferences</tt>
+
<translate><!--T:58--> You may now right click any file or folder and choose the sniffer from the context menu or add a new tool bar button with a nice Joomla! logo</translate> [[File:icon-16-joomla.png]].
# <tt>PHP Tools => PHP CodeSniffer</tt>
 
  
Happy sniffing
+
<translate>
 +
=== Netbeans === <!--T:59-->
 +
</translate>
 +
<translate><!--T:60--> Netbeans has the sniffer functionality integrated into the core system.</translate>
  
==== Eclipse PHP Tools compatibility issue ====
+
<translate><!--T:61-->
 +
# Start your Netbeans IDE
 +
# Open {{rarr|Tools,Options,PHP,Code Analysis,Code Sniffer}}
 +
# You have to set the path to ''phpcs.bat'' from the installed PHP_CodeSniffer PEAR package
 +
#* For Unix based systems the path is something like /usr/bin/phpcs
 +
#* In XAMPP (windows) you can find the file in the PHP root folder (e.g. C:\xampp\php\phpcs.bat)
 +
# As "Default Standard," choose "Joomla" to use the Joomla! standard
 +
# Now you can click ''OK'' to start sniffing
 +
# Open from the top menu {{rarr|Source,Inspect}}
 +
# Enjoy</translate>
  
PHP Tools does not directly support PHP_CodeSniffer-1.5.x. It reports this error:
+
<translate>
 
+
=== Eclipse === <!--T:62-->
<tt>PHP Fatal error:  Uncaught exception 'PHP_CodeSniffer_Exception' with message 'Class PHP_CodeSniffer_CommentParser_ClassCommentParser not found' in /usr/share/php5/PEAR/PHP/CodeSniffer/Standards/Joomla/Sniffs/Commenting/FileCommentSniff.php:18</tt>
+
</translate>
 
+
[[Image:eclipse_pti.png|left|thumb|200px|1) Eclipse PTI]]
It comes with a pre-packaged CodeSniffer version located in eclipse/plugins/org.phpsrc.eclipse.pti.library.pear_.../php/library/PEAR/PHP.
+
{{-}}
 
+
<translate><!--T:63-->
To fix the issue, you can just remove the pre-packaged CodeSniffer version and link the local version. For example, /usr/share/php/PHP.
+
Installation is a breeze and follows the usual pattern:
 
+
# {{rarr|Help,Install New Software}}
<tt>ln -s /usr/share/php/PHP /home/.../eclipse/plugins/org.phpsrc.eclipse.pti.library.pear_.../php/library/PEAR/PHP</tt>
+
# ''Work with:'' Fill in one of the update site URLs found here: http://www.phpsrc.org/eclipse/pti/
 
+
# Select the desired tools
In any case, you can also debug a PHP Tools issue, enabling the debug mode to show the internal commands in Eclipse console:
+
# Restart Eclipse.</translate>
 
 
# <tt>Window => Preferences</tt>
 
# <tt>PHP Tools => PHP CodeSniffer</tt>
 
# <tt>Debug: print PHP output to console</tt>
 
 
 
Command example:
 
 
 
<tt>/usr/bin/php -c /tmp/zend_debug/session8314597725413224814.tmp -d asp_tags=off -d short_open_tag=on /home/.../eclipse/plugins/org.phpsrc.eclipse.pti.tools.codesniffer_1.3.0.R20111119000000/php/tools/phpcs.php --report=xml --standard=/home/.../Joomla /home/..../myphpfile.php</tt>
 
 
 
=== PHPStorm ===
 
 
 
==== PHPStorm ====
 
CodeSniffer is supported out of the box in PHPStorm, just go to settings, and under "Inspections" you will see the list of Sniff you have installed.
 
 
 
See: the [http://www.jetbrains.com/phpstorm/webhelp/using-php-code-sniffer-tool.html JetBrains documentation page for setting the Code Sniffer]  and also  [http://blog.jetbrains.com/webide/2012/03/checking-your-code-with-php-code-sniffer-in-phpstorm-4-0/ phpStorm Blog])
 
  
For users on ubuntu using phpStorm. Don't listen instructions at http://www.jetbrains.com/phpstorm/webhelp/using-php-code-sniffer-tool.html#d59626e1126 because there is no working bat (windows file) on linux system. To validate your CodeSniffer choose /usr/bin/phpcs launcher.
+
[[Image:eclipse_pti_settings.png|right|thumb|150px|2) <translate><!--T:64--> Eclipse PTI settings</translate>]]
 +
<translate><!--T:65--> You are now able to sniff for code violations against common standards like PEAR or Zend etc.</translate>
  
Under Settings->Inspections when you choose joomla profile, in the tree below, search for PHP and open it and than make sure that PHP Code Sniffer validation checkbox is checked. Otherwise PHP Code Sniffer won't sniff your code.
+
<translate><!--T:66--> To sniff against your own standards, specify their location and activate them:</translate>
 +
<translate><!--T:67-->
 +
# {{rarr|Window,Preferences}}
 +
# {{rarr|PHP Tools,PHP CodeSniffer}}</translate>
  
On ubuntu you install code standards with:
+
<translate><!--T:68--> Happy sniffing.</translate>
cd /usr/share/php/PHP/CodeSniffer/Standards
 
sudo git clone http://github.com/joomla/coding-standards.git Joomla
 
===== Installing Joomla Sniff =====
 
 
 
# get the sniffers from the [https://github.com/joomla/coding-standards coding standards repo]
 
# unpack Joomla CodeSniffer rules under:
 
## If you are using XAMPP ''\xampp\php\PEAR\PHP\CodeSniffer\Standards\Joomla''
 
## If not maybe you should check here: ''/usr/share/php/PHP/CodeSniffer/Standards''
 
# Go to Settings (CTRL-ALT-S) and search for "PHP Code Sniffer Validation", click the button Validate to force reload of rules from disk
 
# Joomla should be now available in the list. See following image:
 
<gallery>
 
File:PhpStorm4CodeSniffer.png|PHPStorm  4.x CodeSniffer
 
File:PhpStorm6CodeSniffer.png|PHPStorm  6.x CodeSniffer
 
File:PhpStorm8CodeSniffer.png|PHPStorm  8.x CodeSniffer
 
</gallery>
 
<div style="clear: both"></div>
 
 
 
===== Installing Joomla Code style =====
 
 
It's nice to be able to check that the standards are respected, but it's even nicer if phpstorm helps you formatting properly too as you are coding.
 
To add joomla code style to phpstorm
 
# first get the xml scheme file from here: https://github.com/betweenbrain/phpstorm-joomla-code-style
 
# Then save the file in phpstorm [http://www.jetbrains.com/phpstorm/webhelp/project-and-ide-settings.html#d231397e460 home directory]: <phpstorm home directory>/config/codestyles/Joomla.xml
 
# restart phpstorm, and you should be able to select Joomla from the Code Style > Scheme select box
 
 
 
==== PHP PSR-0, PSR-1 and PSR-2 ====
 
* https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
 
* https://github.com/pmjones/fig-standards/blob/psr-1-style-guide/proposed/PSR-1-basic.md
 
* https://github.com/pmjones/fig-standards/blob/psr-1-style-guide/proposed/PSR-2-advanced.md
 
 
 
===== Installing PHP PSR-0, PSR-1 and PSR-2 Sniff =====
 
 
 
A CodeSniffer sniff to check against the PSR-x Coding Standard
 
 
 
Download files at
 
* https://github.com/squizlabs/PHP_CodeSniffer/tree/master/CodeSniffer/Standards
 
 
 
if you are using Xampp,
 
# unpack PSR-1 CodeSniffer rules under \xampp\php\PEAR\PHP\CodeSniffer\Standards\PSR (SPR or any directory will work)
 
# Go to Settings (CTRL-ALT-S) and search for "PHP Code Sniffer Validation", click the button Validate to force reload of rules from disk
 
# PSR is available in the list
 
 
 
==== PHPStorm / Alternative method ====
 
'''NOTE''': This method is '''outdated''', but it might be useful if you are looking for a different integration. It also demonstrates the use of external tools in PHPStorm - so it ''shouldn't be deleted''.
 
 
 
The CodeSniffer can also be integrated easily as an external tool. PHPStorm will display the output in the console, including clickable links containing line and column numbers to the files that contain errors.
 
 
 
* Click on "Settings" and search for "External tools"
 
* Click "Add..."
 
* Choose a "name", "Group" and "Description".
 
* Click "Output Filters"
 
** Click "Add...", Choose a name and enter under "Regular expression to match output" the value: <tt>$FILE_PATH$:$LINE$:$COLUMN$</tt>
 
* "Program": Search for the phpcs executable on your system. You have to set the path to the ''phpcs.bat'' from the installed PHP_CodeSniffer PEAR package
 
** for Unix based systems the path is something like /usr/bin/phpcs
 
** in XAMPP (windows) you can find the file in the php root folder (e.g. C:\xampp\php\phpcs.bat)
 
* "Paramaters":
 
** <tt>--standard=<path/to/joomla-platform>/build/phpcs/Joomla</tt> The path to the Joomla! coding standards.
 
** <tt>--report=emacs</tt> The will generate a simple list containing links to the error files
 
** Optional you may want to specify <tt>-p</tt> for "progress" or <tt>-n</tt> for "errors only".
 
** The last parameter has to be <tt>$FilePath$</tt> specifying the file or folder you want to sniff.
 
  
A typical "Parameters" line on a Linux system might look like this:
+
<translate>
<pre>-np --standard=/home/elkuku/libs/joomla/build/phpcs/Joomla --report=emacs $FilePath$</pre>
+
=== Geany === <!--T:69-->
 +
</translate>
 +
<translate><!--T:70-->
 +
* Open a PHP file. (Otherwise the build menu is not accessible.)
 +
* On the top menu, select Build->Set Build Commands.
 +
* Select the second field and name it as you wish. Enter this code in the Command: ''phpcs --standard=Joomla "%f" | sed -e 's/^/%f |/' | egrep 'WARNING|ERROR'''
 +
* Enter this code in the Error Regular Expression field: ''(.+) [|]\s+([0-9]+)''
 +
* Select ''OK''.
 +
* If the Message Window is not open, display it by selecting it in the top ''View'' menu.
 +
* When viewing any PHP file, press F9 to see the errors found.</translate>
  
You may now right click any file or folder and choose the sniffer from the context menu or add a new toolbar button with a nice Joomla! logo [[File:icon-16-joomla.png]].
+
<translate>
 +
=== Atom === <!--T:78-->
 +
</translate>
 +
<translate>
 +
<!--T:79-->
 +
* Install phpcs and the Joomla standards as described above.
 +
* In {{rarr|Atom,Preferences,Install}} install ''linter-phpcs'' and all its requirements.
 +
* In {{rarr|Atom,Preferences,Packages,linter-phpcs,Settings}} adjust
 +
** '''Executable Path''' to the path of your phpcs
 +
** '''Code Standard Or Config File''': Joomla
 +
** '''Tab Width''': 4
 +
</translate>
  
=== References ===
+
<translate>
* http://www.phpsrc.org/ PTI - PHP tools integration for Eclipse
+
=== References === <!--T:71-->
* http://sourceforge.net/projects/phpmdnb/ Netbeans plugin
+
</translate>
* http://hakre.wordpress.com/2010/03/06/php-code-sniffer-eclipse-and-wordpress/ - Excellent article. Just change "Wordpress" for "Joomla!" ;)
+
* [https://github.com/joomla/coding-standards Joomla! Coding Standards]
 +
* [https://www.phpsrc.org/ PTI - PHP tools integration for Eclipse]
 +
* [https://sourceforge.net/projects/phpmdnb/ Netbeans plugin]
 +
* https://hakre.wordpress.com/2010/03/06/php-code-sniffer-eclipse-and-wordpress/ - <translate><!--T:75--> Excellent article. Just change ''Wordpress'' for ''Joomla'' ;)</translate>
  
[[Category:Development]][[Category:Bug Squad]]
+
<noinclude>
[[Category:IDE (Integrated development environment)]]
+
[[Category:Development{{#translation:}}]]
 +
[[Category:Bug Squad{{#translation:}}]]
 +
[[Category:IDE (Integrated development environment){{#translation:}}]]
 +
</noinclude>

Latest revision as of 15:57, 5 July 2023

Other languages:
English • ‎Türkçe • ‎français • ‎русский

A Nose For Joomla[edit]

This is a custom coding standard for the PHP CodeSniffer that attempts to codify and enforce the Joomla coding standards. This article covers how to set the automatic code style checker. It consists of three steps:

  1. Install PHP CodeSniffer (phpcs).
  2. Clone the Joomla Code Style (for use with for phpcs).
  3. Configure your IDE to work with PHP CodeSniffer and Joomla Code Style.
PHP Code Sniffer in action

Why?[edit]

  • Coherent and consistent coding practice makes the files look more professional. Conflicting styles in the same project (or worse, the same file) not only look sloppy, they encourage further sloppiness.
  • When all code complies with the same standard, bad code is easier for everyone to spot.
  • It makes it easier for someone new to a particular file in the project to find and fix errors or extend functionality.
  • If there is no consistent standard maintained, sometimes developers will reformat the code to suit themselves. This causes a wide range of changes in the code repository. If there is a later problem, a significant change could be lost in the chaff produced by a diff.

Installation of PHP Code Sniffer (phpcs)[edit]

Composer[edit]

PHP Code Sniffer is available via Composer. It can be installed system-wide with the following command:
composer global require --dev squizlabs/php_codesniffer "~3.5" On Linux PHP Code Sniffer (phpcs) will be installed under your user folder:

  • Symbolic Link: ~/.composer/vendor/bin/phpcs
  • The file: ~/.composer/vendor/squizlabs/php_codesniffer/scripts/phpcs

To create that symbolic link, use on the command line: $ sudo ln -s ~/.config/composer/vendor/squizlabs/php_codesniffer/scripts /usr/bin/phpcs

or (for example OpenSuse)

  • Symbolic Link: ~/.config/composer/vendor/bin/phpcs
  • The file: ~/.config/composer/vendor/squizlabs/php_codesniffer/scripts/phpcs

On Windows PHP Code Sniffer (phpcs) will be installed under your user folder:

  • Symbolic Link: c:\Users\Username\AppData\Roaming\Composer\vendor\bin\phpcs
  • The file: c:\Users\Username\AppData\Roaming\Composer\vendor\squizlabs\php_codesniffer\scripts\phpcs

Add composer bin directory to your $PATH[edit]

In order to execute PHP Code sniffer from anywhere on Linux or Mac command line you have to add .composer/vendor/bin to your $PATH variable. To do this persistent edit your shells start file, like your .profile or .bash_profile file depending which shell you are using (echo $SHELL shows you which one you are using).

Add the following line to the file: export PATH=$PATH:~/.composer/vendor/bin

Alternatively you can also create a symbolic link in the bin folder: ln -s ~/.composer/vendor/bin/phpcs /usr/local/bin/phpcs

Install Joomla Coding Standards[edit]

In order to have PHP Code Sniffer (phpcs) sniffing your Joomla projects for the right code style, you have to install the Joomla Coding Standards.

Using composer we can execute: composer global require --dev joomla/coding-standards "~3.0@alpha"

Notice that it says @alpha, that is because the coding standard is still in alpha state and we need to allow the installation of alpha status code. If we do not include the @alpha the coding standards will not install and throw this error.

Your requirements could not be resolved to an installable set of packages.

Problem 1
 - The requested package joomla/coding-standards ~3.0 is satisfiable by joomla/coding-standards[3.0.0-alpha, 3.0.0-alpha2, 3.x-dev] but these conflict with your requirements or minimum-stability.

Once the installation is done the coding standard will be installed in the global composer folder. The location of this folder depends on your operating system. Some popular locations are:

Mac / Linux

~/.composer/vendor/joomla/coding-standards/ and ~/.config/composer/vendor/joomla/coding-standards/

Windows

c:\Users\Username\AppData\Roaming\Composer\vendor\joomla\coding-standards\

This is using Composer on Windows.

If you can't find it in any of the above folders, note that the folder you are looking for ends with \joomla\coding-standards\. Finally we need to tell Code Sniffer that the Joomla coding standards exist.

Install Joomla Coding Standards

  1. Check if certain paths are already set by running phpcs --config-show
  2. You can get an answer that looks like this: installed_paths: /path/to/installation
  3. In step 2, if you see the installed_paths you need to copy that
  4. Set the Joomla Coding Standards path in phpcs by executing phpcs --config-set installed_paths /Users/user/.composer/vendor/joomla/coding-standards. If you copied any paths in step 2, include them here as well by separating them with a comma. The command looks like phpcs --config-set installed_paths [/to/path1],[/to/path2],[/Users/user/.composer/vendor/joomla/coding-standards]
  5. Verify the path is set correctly by running phpcs --config-show
  6. Verify that phpcs can see the Joomla codestyle by running phpcs -i
  7. The output should look like this: The installed coding standards are MySource, PEAR, PHPCS, PSR1, PSR2, Squiz, Zend and Joomla

Usage[edit]

You invoke the custom standard by phpcs --standard=Joomla file/to/sniff

To test a platform file using the provided platform coding standards, use phpcs --standard=build/phpcs/Joomla path/to/file/or/folder

Further documentation on the use of phpcs can be found at the pear.php.net website.

IDE Integration[edit]

Everybody loves the console. It is, with no doubt, the most effective way to do whatever you need to do. Sometimes even Linux gurus need a little bit of comfort.

Fortunately there is a plug-in available for PhpStorm, Eclipse and Netbeans that integrates the CodeSniffer into your favourite IDE, so any coding standard violations are shown like "normal" errors.

PhpStorm[edit]

Code Sniffer is supported out of the box in PhpStorm. Go to Settings and under Editor  Inspections you will see the list of sniffers you have installed.

Set Path to Code Sniffer[edit]

  1. Open Settings (CTRL-ALT-S / CMD-,)
  2. Go to Languages & Frameworks
  3. Click on PHP
  4. Click on Quality Tools
  5. Click on PHP cs fixer dropdown arrow
  6. The configuration is set to Local by default
  7. Click on the 3 dots behind it to open the configuration screen
  8. The first option is the PHP Code Sniffer (phpcs) path
  9. Click on the 3 dots behind the path to select the location of the phpcs file. See above on where phpcs may be installed on your site
  10. Click on Validate to make sure the path is correct and phpcs is working
  11. Click OK
Activating the Joomla Code Style[edit]
  1. Open Settings (CTRL-ALT-S / CMD-,)
  2. Go to Editor
  3. Click on Inspections
  4. In the list, go to PHP
  5. Click on PHP Code Sniffer Validation
  6. Click on the check box behind it to activate it
  7. Click the Reload button (2 arrows) to force a reload of rules from disk
  8. Joomla should now be available in the list. See following image:
    PHPStorm CodeSniffer
  9. Click OK

PHP PSR-0, PSR-1 and PSR-2[edit]

Using PHP PSR-1 and PSR-2 Sniff[edit]

A CodeSniffer sniff to check against the PSR-x Coding Standard can be used as well. In that case you can select a different standard than Joomla.

Using Joomla Code style[edit]

It's nice to be able to check that the standards are respected. It's even nicer if PhpStorm helps you format properly too as you are coding. To use the Joomla code style in PhpStorm

  1. Open Settings (CTRL-ALT-S / CMD-,)
  2. Go to Editor
  3. Click on Code Style
  4. Select Joomla from the Scheme select box

PhpStorm / Alternative Method[edit]

NOTE: This method is outdated, but it might be useful if you are looking for a different integration. It also demonstrates the use of external tools in PhpStorm - so it shouldn't be deleted.

The Code Sniffer can also be integrated easily as an external tool. PhpStorm will display the output in the console, including click-able links containing line and column numbers to the files that contain errors.

  • Click on "Settings" and search for "External tools"
  • Click "Add..."
  • Choose a "Name", "Group" and "Description".
  • Click "Output Filters"
    • Click "Add...", Choose a name and enter under "Regular expression to match output" the value: $FILE_PATH$:$LINE$:$COLUMN$
  • "Program": Search for the phpcs executable on your system. You have to set the path to the phpcs.bat from the installed PHP_CodeSniffer PEAR package
    • For Unix based systems, the path is something like /usr/bin/phpcs
    • In XAMPP (windows), you can find the file in the PHP root folder (e.g. C:\xampp\php\phpcs.bat)
  • "Parameters":
    • --standard=<path/to/joomla-platform>/build/phpcs/Joomla The path to the Joomla! coding standards.
    • --report=emacs The will generate a simple list containing links to the error files
    • Optionally you may want to specify -p for "progress" or -n for "errors only".
    • The last parameter has to be $FilePath$ specifying the file or folder you want to sniff.

A typical "Parameters" line on a Linux system might look like this:

-np --standard=/home/elkuku/libs/joomla/build/phpcs/Joomla --report=emacs $FilePath$

You may now right click any file or folder and choose the sniffer from the context menu or add a new tool bar button with a nice Joomla! logo Icon-16-joomla.png.

Netbeans[edit]

Netbeans has the sniffer functionality integrated into the core system.

  1. Start your Netbeans IDE
  2. Open Tools  Options  PHP  Code Analysis  Code Sniffer
  3. You have to set the path to phpcs.bat from the installed PHP_CodeSniffer PEAR package
    • For Unix based systems the path is something like /usr/bin/phpcs
    • In XAMPP (windows) you can find the file in the PHP root folder (e.g. C:\xampp\php\phpcs.bat)
  4. As "Default Standard," choose "Joomla" to use the Joomla! standard
  5. Now you can click OK to start sniffing
  6. Open from the top menu Source  Inspect
  7. Enjoy

Eclipse[edit]

1) Eclipse PTI

Installation is a breeze and follows the usual pattern:

  1. Help  Install New Software
  2. Work with: Fill in one of the update site URLs found here: http://www.phpsrc.org/eclipse/pti/
  3. Select the desired tools
  4. Restart Eclipse.
2) Eclipse PTI settings

You are now able to sniff for code violations against common standards like PEAR or Zend etc.

To sniff against your own standards, specify their location and activate them:

  1. Window  Preferences
  2. PHP Tools  PHP CodeSniffer

Happy sniffing.

Geany[edit]

  • Open a PHP file. (Otherwise the build menu is not accessible.)
  • On the top menu, select Build->Set Build Commands.
  • Select the second field and name it as you wish. Enter this code in the Command: phpcs --standard=Joomla "%f" | sed -e 's/^/%f |/' | egrep 'WARNING|ERROR'
  • Enter this code in the Error Regular Expression field: (.+) [|]\s+([0-9]+)
  • Select OK.
  • If the Message Window is not open, display it by selecting it in the top View menu.
  • When viewing any PHP file, press F9 to see the errors found.

Atom[edit]

  • Install phpcs and the Joomla standards as described above.
  • In Atom  Preferences  Install install linter-phpcs and all its requirements.
  • In Atom  Preferences  Packages  linter-phpcs  Settings adjust
    • Executable Path to the path of your phpcs
    • Code Standard Or Config File: Joomla
    • Tab Width: 4

References[edit]