Monday, August 8, 2016

Using PHP CodeSniffer With WordPress: Installing and Using the WordPress Rules_part2 (end)

3. Running PHP CodeSniffer Against WordPress Projects

Assuming you're working out of a directory that includes a WordPress plugin, then you can skip the following step. If, on the other hand, you do not have a copy of a WordPress script, file, theme, or plugin installed in the project directory, go ahead and copy one over to your project directory now.

As mentioned, we'll be testing the Hello Dolly plugin.

To run PHP CodeSniffer with the WordPress rules against the files in the plugin directory, enter the following command in the Terminal:
  1. $ vendor/bin/phpcs --standard=WordPress hello-dolly
This will result in output that should correspond to what you see here:
  1. FILE: /Users/tommcfarlin/Desktop/tutsplus_demo/hello-dolly/hello.php
  2. ----------------------------------------------------------------------
  3. FOUND 14 ERRORS AFFECTING 14 LINES
  4. ----------------------------------------------------------------------
  5.   2 | ERROR | Missing short description in doc comment
  6.   5 | ERROR | There must be exactly one blank line after the file
  7.     |       | comment
  8.   6 | ERROR | Empty line required before block comment
  9.  15 | ERROR | You must use "/**" style comments for a function
  10.     |       | comment
  11.  46 | ERROR | Inline comments must end in full-stops, exclamation
  12.     |       | marks, or question marks
  13.  49 | ERROR | Inline comments must end in full-stops, exclamation
  14.     |       | marks, or question marks
  15.  53 | ERROR | Inline comments must end in full-stops, exclamation
  16.     |       | marks, or question marks
  17.  54 | ERROR | You must use "/**" style comments for a function
  18.     |       | comment
  19.  56 | ERROR | Expected next thing to be an escaping function (see
  20.     |       | Codex for 'Data Validation'), not '"<p
  21.     |       | id='dolly'>$chosen</p>"'
  22.  59 | ERROR | Inline comments must end in full-stops, exclamation
  23.     |       | marks, or question marks
  24.  62 | ERROR | Inline comments must end in full-stops, exclamation
  25.     |       | marks, or question marks
  26.  63 | ERROR | You must use "/**" style comments for a function
  27.     |       | comment
  28.  64 | ERROR | Inline comments must end in full-stops, exclamation
  29.     |       | marks, or question marks
  30.  67 | ERROR | Expected next thing to be an escaping function (see
  31.     |       | Codex for 'Data Validation'), not '"
  32.     |       | '
  33. ----------------------------------------------------------------------
Of course, some of these things may change depending on when you're reading this tutorial.

The errors should be pretty clear as to what needs to be fixed:
  • The first column denotes the line in which the problem exists.
  • The second column determines if there is an error or a warning.
  • The third column explains the problem and what's expected of the code.
Note that although these are errors or warnings, the code will obviously still work. But let's pull this through end-to-end and see what it's like to fix up a plugin, arguably the most popular since it comes with each installation of WordPress, and review the differences in the quality of the code.

4. Refactoring Hello Dolly

Note the plugin, before we begin working on it, includes the following source code:
  1. <?php
  2. /**
  3.  * @package Hello_Dolly
  4.  * @version 1.6
  5.  */
  6. /*
  7. Plugin Name: Hello Dolly
  8. Plugin URI: https://wordpress.org/plugins/hello-dolly/
  9. Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
  10. Author: Matt Mullenweg
  11. Version: 1.6
  12. Author URI: http://ma.tt/
  13. */ 
  14. function hello_dolly_get_lyric() {
  15.     /** These are the lyrics to Hello Dolly */
  16.     $lyrics = "Hello, Dolly
  17. Well, hello, Dolly
  18. It's so nice to have you back where you belong
  19. You're lookin' swell, Dolly
  20. I can tell, Dolly
  21. You're still glowin', you're still crowin'
  22. You're still goin' strong
  23. We feel the room swayin'
  24. While the band's playin'
  25. One of your old favourite songs from way back when
  26. So, take her wrap, fellas
  27. Find her an empty lap, fellas
  28. Dolly'll never go away again
  29. Hello, Dolly
  30. Well, hello, Dolly
  31. It's so nice to have you back where you belong
  32. You're lookin' swell, Dolly
  33. I can tell, Dolly
  34. You're still glowin', you're still crowin'
  35. You're still goin' strong
  36. We feel the room swayin'
  37. While the band's playin'
  38. One of your old favourite songs from way back when
  39. Golly, gee, fellas
  40. Find her a vacant knee, fellas
  41. Dolly'll never go away
  42. Dolly'll never go away
  43. Dolly'll never go away again"; 
  44.     // Here we split it into lines
  45.     $lyrics = explode( "\n", $lyrics ); 
  46.     // And then randomly choose a line
  47.     return wptexturize( $lyrics[ mt_rand( 0, count( $lyrics ) - 1 ) ] );
  48. } 
  49. // This just echoes the chosen line, we'll position it later
  50. function hello_dolly() {
  51.     $chosen = hello_dolly_get_lyric();
  52.     echo "<p id='dolly'>$chosen</p>";
  53. } 
  54. // Now we set that function up to execute when the admin_notices action is called
  55. add_action( 'admin_notices', 'hello_dolly' ); 
  56. // We need some CSS to position the paragraph
  57. function dolly_css() {
  58.     // This makes sure that the positioning is also good for right-to-left languages
  59.     $x = is_rtl() ? 'left' : 'right'; 
  60.     echo "
  61.     <style type='text/css'>
  62.     #dolly {
  63.         float: $x;
  64.         padding-$x: 15px;
  65.         padding-top: 5px;       
  66.         margin: 0;
  67.         font-size: 11px;
  68.     }
  69.     </style>
  70.     ";
  71. } 
  72. add_action( 'admin_head', 'dolly_css' ); 
  73. ?>
It should be relatively easy to follow as it uses only a few basic PHP features and Matt's done a good job of commenting the code.

But given the 14 errors that the CodeSniffer found, let's refactor the plugin. Taking into account the errors they presented and what it's expecting to see, let's address each of them.

Once done, the plugin should look like the following:
  1. <?php
  2. /**
  3.  * This is a plugin that symbolizes the hope and enthusiasm of an entire
  4.  * generation summed up in two words sung most famously by Louis Armstrong.
  5.  *
  6.  * @package Hello_Dolly
  7.  * @version 1.6
  8.  *
  9.  * @wordpress-plugin
  10.  * Plugin Name: Hello Dolly
  11.  * Plugin URI: https://wordpress.org/plugins/hello-dolly/
  12.  * Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
  13.  * Author: Matt Mullenweg
  14.  * Version: 1.6
  15.  * Author URI: http://ma.tt/
  16.  */ 
  17. /**
  18.  * Defines the lyrics for 'Hello Dolly'.
  19.  *
  20.  * @return string A random line of from the lyrics to the song.
  21.  */
  22. function hello_dolly_get_lyric() {
  23.     /** These are the lyrics to Hello Dolly */
  24.     $lyrics = "Hello, Dolly
  25. Well, hello, Dolly
  26. It's so nice to have you back where you belong
  27. You're lookin' swell, Dolly
  28. I can tell, Dolly
  29. You're still glowin', you're still crowin'
  30. You're still goin' strong
  31. We feel the room swayin'
  32. While the band's playin'
  33. One of your old favourite songs from way back when
  34. So, take her wrap, fellas
  35. Find her an empty lap, fellas
  36. Dolly'll never go away again
  37. Hello, Dolly
  38. Well, hello, Dolly
  39. It's so nice to have you back where you belong
  40. You're lookin' swell, Dolly
  41. I can tell, Dolly
  42. You're still glowin', you're still crowin'
  43. You're still goin' strong
  44. We feel the room swayin'
  45. While the band's playin'
  46. One of your old favourite songs from way back when
  47. Golly, gee, fellas
  48. Find her a vacant knee, fellas
  49. Dolly'll never go away
  50. Dolly'll never go away
  51. Dolly'll never go away again"; 
  52.     // Here we split it into lines.
  53.     $lyrics = explode( "\n", $lyrics );
  54.     // And then randomly choose a line.
  55.     return wptexturize( $lyrics[ mt_rand( 0, count( $lyrics ) - 1 ) ] );
  56. } 
  57. add_action( 'admin_notices', 'hello_dolly' );
  58. /**
  59.  * This just echoes the chosen line, we'll position it later. This function is
  60.  * set up to execute when the admin_notices action is called.
  61.  */
  62. function hello_dolly() {
  63.     $chosen = hello_dolly_get_lyric();
  64.     echo "<p id='dolly'>$chosen</p>"; // WPCS: XSS OK.
  65. } 
  66. add_action( 'admin_head', 'dolly_css' );
  67. /**
  68.  * Add some CSS to position the paragraph.
  69.  */
  70. function dolly_css() { 
  71.     /**
  72.      *This makes sure that the positioning is also good for right-to-left languages.
  73.      */
  74.     $x = is_rtl() ? 'left' : 'right';
  75.     echo "<style type='text/css'> #dolly { float: $x; padding-$x: 15px; padding-top: 5px; margin: 0; font-size: 11px; } </style> "; // WPCS: XSS OK. 
  76. }
Notice that the plugin continues to work and the code is a bit cleaner. Lastly, let's verify that this passes the PHP CodeSniffer test. Let's re-run the code that we used above to initially evaluate the plugin.
  1. $ vendor/bin/phpcs --standard=WordPress hello-dolly
And the output that we see:
  1. Skyhopper5:tutsplus_demo tommcfarlin$
Exactly: There should be no output. Instead, it should be a return to the standard command prompt.

Excellent. The plugin has been brought up to standard. This is why having a code sniffer is so valuable: It finds the errors in your code based on the rules you define and then reports any errors that may exist.

Ultimately, this ensures that you're releasing the highest quality written code into a production-level site. Now, this does not mean you should avoid unit testing or other types of testing, nor does this mean bugs don't exist. It just means that your code is up to a high standard.

Conclusion

And with that, we conclude the series on using PHP CodeSniffer. Recall that throughout the series, we have covered the idea of code smells, how to refactor them, and what tools are available to us when working with PHP applications.

In this article, we saw how we can use a provided set of rules for the WordPress Coding Standards to evaluate our code while working on a new or an existing project. Note that some IDEs support the ability to execute the rules while writing code.

Although that's beyond the scope of this particular tutorial, you can find resources for this in various places throughout the web.
Written by Tom McFarlin

If you found this post interesting, follow and support us.
Suggest for you:

Learning PHP 7: From the Basics to Application Development

The Complete PHP 7 Guide for Web Developers

Up to Speed with PHP 7

PHP MySQL Database Connections

The Complete PHP with MySQL Developer Course (New)

No comments:

Post a Comment