CodeSniffer Part 2: CodeSniffer Output

Continuing from Part 1: Introduction to CodeSniffer this time looking at and interpreting the output from CodeSniffer.

If we take an example block of code such as the following.

 
 
<?php

function DoSomething(array $foo) {
    print_r($foo);
}

?>
 

And run it through CodeSniffer with the Zend coding standard we get:

$ phpcs --standard=Zend foo.php

FILE: /home/bob/sample/foo.php
--------------------------------------------------------------------------------
FOUND 2 ERROR(S) AND 1 WARNING(S) AFFECTING 2 LINE(S)
--------------------------------------------------------------------------------
 2 | ERROR   | End of line character is invalid; expected "\n" but found "\r\n"
 4 | ERROR   | Opening brace should be on a new line
 4 | WARNING | Consider putting global function "DoSomething" in a static class
--------------------------------------------------------------------------------

If we then run the same code through the PHPCS standard we get a more in-depth set of violations:

$ phpcs --standard=PHPCS foo.php

FILE: /home/bob/sample/foo.php
--------------------------------------------------------------------------------
FOUND 16 ERROR(S) AND 2 WARNING(S) AFFECTING 6 LINE(S)
--------------------------------------------------------------------------------
 2 | ERROR   | End of line character is invalid; expected "\n" but found "\r\n"
 2 | ERROR   | End of line character is invalid; expected "\n" but found "\r\n"
 2 | ERROR   | Additional whitespace found at start of file
 3 | ERROR   | Missing file doc comment
 4 | WARNING | Consider putting global function "DoSomething" in a static class
 4 | ERROR   | Missing function doc comment
 4 | ERROR   | Function name "DoSomething" is invalid; consider "doSomething"
   |         | instead
 4 | ERROR   | Expected "function abc(...)\n"; found "function abc(...) "
 4 | ERROR   | Function name "DoSomething" is not in camel caps format
 4 | ERROR   | Expected 2 blank lines before function; 1 found
 4 | ERROR   | Opening brace should be on a new line
 4 | ERROR   | Opening brace should be on a new line
 4 | ERROR   | Opening brace should be on a new line
 5 | WARNING | The use of function print_r() is discouraged
 6 | ERROR   | Expected //end DoSomething()
 6 | ERROR   | Expected 1 blank line before closing function brace; 0 found
 6 | ERROR   | Expected 2 blank lines after function; 1 found
 8 | ERROR   | Additional whitespace found at end of file
--------------------------------------------------------------------------------

Hopefully you can see that the PHPCS standard is significantly more strict that the previous.

Also you should see that apart from more style based checks, this standard also checks for whitespace at the beginning and end of the file. Whitespace being echoed can be very important for some PHP frameworks. When lots of files are included as part of the execution, especially if they are dynamically loaded, the whitespace can cause a fatal error if header information is also being sent to the browser.

The other issues contained in this report are based around the project code layout and documentation requirements.

Other reports

With the release of CodeSniffer 1.2.x there are some new reporting types available.

Rather than the full in-depth report, two reports that I find quite useful for gauging a project’s status are the summary and source reports.

Summary reports the number of errors and warnings found on a file by file basis over a directory tree.

$ phpcs --report=summary --standard=Zend ./_rr

PHP CODE SNIFFER REPORT SUMMARY
--------------------------------------------------------------------------------
FILE                                                            ERRORS  WARNINGS
--------------------------------------------------------------------------------
.../yocal/apps/frontend/modules/_rr/templates/_partial_rr1.php  23      3
...yocal/apps/frontend/modules/_rr/templates/_partial_rr10.php  4       1
...yocal/apps/frontend/modules/_rr/templates/_partial_rr11.php  7       4
.../yocal/apps/frontend/modules/_rr/templates/_partial_rr2.php  8       2
.../yocal/apps/frontend/modules/_rr/templates/_partial_rr3.php  18      2
.../yocal/apps/frontend/modules/_rr/templates/_partial_rr4.php  43      3
.../yocal/apps/frontend/modules/_rr/templates/_partial_rr5.php  22      4
.../yocal/apps/frontend/modules/_rr/templates/_partial_rr6.php  39      3
.../yocal/apps/frontend/modules/_rr/templates/_partial_rr7.php  24      1
.../yocal/apps/frontend/modules/_rr/templates/_partial_rr8.php  17      2
...yocal/apps/frontend/modules/_rr/templates/_thumbsUpDown.php  71      4
--------------------------------------------------------------------------------
A TOTAL OF 276 ERROR(S) AND 29 WARNING(S) WERE FOUND IN 11 FILE(S)
--------------------------------------------------------------------------------

Source shows the  type of errors and warnings found in a project:

$ phpcs --report=source --standard=Zend ./_rr

PHP CODE SNIFFER VIOLATION SOURCE SUMMARY
--------------------------------------------------------------------------------
STANDARD    CATEGORY            SNIFF                                      COUNT
--------------------------------------------------------------------------------
Zend        Files               Line length                                92
Generic     White space         Disallow tab indent                        65
Zend        Naming conventions  Valid variable name                        59
PEAR        White space         Scope closing brace                        33
PEAR        Functions           Function call signature                    26
PEAR        Control structures  Control signature                          12
PEAR        Files               Line endings                               11
PEAR        Functions           Function call argument spacing             5
Generic     PHP                 Disallow short open tag                    1
Zend        Files               Closing tag                                1
--------------------------------------------------------------------------------
A TOTAL OF 305 SNIFF VIOLATION(S) WERE FOUND IN 10 SOURCE(S)
--------------------------------------------------------------------------------

As you can see from this report, although we are using the Zend standard, it consists of individual rules from multiple standards.

In the next part of this series I will cover how to write your own standard, by selecting rules from existing standards.

Posted in Development, PHP, Software | Tagged , , , | 3 Comments

CodeSniffer Part 1: Introduction to CodeSniffer

This started as a quick blog post on my way home. I was drunk, and shouldn’t have been blogging. I’d been to the leaving do of two of my great colleagues at Yahoo!

It ended up way too long,  so I have split it up into sections and will post as a series.

This is a rough transcript of a lightning talk I gave during a team meeting at Yahoo! completely off the cuff, but I am in the process of writing this up as a Yahoo! Tech Talk, and also, as this is not internally sensitive, like most of the stuff I’ve been working on for the last two years, I’ll see if it can be release on Yahoo Developers Network.

What is CodeSniffer?

CodeSniffer is almost a SCA tool. It allows a set of rules or a Standard to be applied to source code.

These rules can be used to detect common programming errors or Anti Patterns, it can also be used to define a set of Coding Standards  for your project.

It is down to your project to come up with some Coding Standards or apply a pre-existing set of standards for your team to adhere to.

CodeSniffer comes with a set of coding standards already defined that are regularly used by other teams.

These are:

  • MySource
  • PEAR
  • PHPCS
  • Squiz
  • Zend

Analysing your code using one or more of these standards will highlight how the code you have provided stacks up against the project’s coding standard.

How to install CodeSniffer

$ sudo pear install PHP_CodeSniffer

This will download and install the CodeSniffer utility from the PEAR repository.

How to run CodeSniffer

Simply run:

$ phpcs --standard=<standard> <path to file or directory>

You will be shown a list any errors or warnings in your code.

CodeSniffer will also exit with a non-zero status code. This can be useful if you are using a Makefile to test your code or some build tool like Phing, or if your CodeSniffer rules are being run as part of a Continuous Integration system.

In the next post I will run through some of the standards and reports.

Posted in Development, PHP, Software | Tagged , , , | 7 Comments

Marksmen and Developers

One of the things I enjoy about the sport of shooting is the almost Zen like mental state you have to get yourself into.

I use my shooting time as meditation time, you have to shed all of those external pressures of work and home life and empty your mind. Then you let all of your muscles relax otherwise you may skew the shot and it will end up somewhere other than the centre.

Normally after a couple of righter shots, you should be entering “The Zone” where you can normally ignore all but the most pervasive interruptions. And then repetition kicks in.

  • Load the rifle into your shoulder, load a round, close the breach.
  • Nestle your cheek onto the cheek piece, check the sighting on the target.
  • Close your eyes, take a breath, check your sighting again, correct your aim if necessary.
  • Breath slowing, slowing your heart rate, exhale and hold, slow squeeze the trigger and fire.
  • Unload the empty case, and check the spotting scope.
  • Rinse and repeat.

Last evening whilst down at my local shooting range this put me in mind about the similarities between being a programmer and being marksman.

First of all software developers also strive for “Flow”, a mental state where all external stimuli are excluded from perception, all your mental energy is concentrated on solving the problem at hand. Some developers try and shroud external interruptions with headphones, I tend to find that distracting unless the office environment is already quite noisy.

Secondly software developers should also be in a routine, but often steps are left out. Most notably testing. I believe a software development routine should follow something along the lines of (at a bare minimum):

  • Update code from source control.
  • Write your code.
  • Check your functionality on a local web instance if possible.
  • Update your test cases or write new ones to cover the new code.
  • Update code from source control.
  • Run your unit tests.
  • Fix any tests if needed.
  • Commit code to source control with a description of change and bug number or feature identifier.
  • Rinse and repeat.

With some of the above steps, the order may change, if your following Test Driven Development, then you may write your tests before you write your code, but all the steps are still present.

Much like my marksman (sorry and women) example, after a while these become instinctive and you almost forget that your doing them, but you get a gut feeling that something is wrong when they are absent.

Thirdly I find that if I stop shooting or developing of any length of time, say a fortnight for shooting or a week for writing code, I start to get an itchy brain. Something is not right and I can start to get a bit anxious.

So I rambled on there a bit and didn’t really come to any conclusion. But part of the idea behind this blog is for me to brain dump and also for me to develop my communication skills.

So to try and wrap this up with some kind of conclusion, if your significant other is a software developer, don’t berate them for watching TV and writing code on their laptop at the same time, or staying up until 2am working on that niggley little problem. It’s an addiction and they can’t help it, to make them stop is like depriving them of sleep. They won’t feel right until they scratch that mental itch.

And if your significant other is a marks[man|woman], if they haven’t been to the range in a while and are starting to get tetchy, maybe suggest they go have a practice at the rifle range.

Posted in Development, Ramblings, Shooting | Tagged , , , , | Leave a comment

Basic web security precautions you can take to limit phishing damage

So you may have heard around 30 high profile twitter users got phished.

This is a regular occurance on may different sites and generally seem to aimed towards financial services (a.k.a. banks) and high profile online shopping (ebay, amazon and the like).

What makes this more of a big deal is that generally people have a hard time remembering passwords, so tend to use the same password for everything,  bank(s), ebay,  paypal, twitter, flickr, yahoo!, google, facebook, etc..  So if you get the username and password for one user, you may well be able to compromise that user all over the web.

However one thing that you can do to protect your web presence is NOT USE THE SAME PASSWORD EVERYWHERE!

Now I use a firefox plugin called PasswordMaker.

This creates a hash of a password of your choice with the domain name of the site you are currently browsing and will add a content menu link to your browser to allow you to easilt populate web forms when you need your password.

It has lots of options, but here’s a quick screen grab of the main page:

PassswordMaker main panel, showing generated password for this site. No not my real one, you think I'm dumb!

PasswordMaker main panel, showing generated password for this site. No not my real one, you think I'm dumb!

As you can see, using the master password, i.e. your one password you can remember, it will generate a unique password for each website you visit.

You can also cache you master password for one browser session (store master password: in memory) or permanently (store master password: on disk & in memory).

You can choose the password length, hashing algorithm, obfuscator (i.e. leet), character set to use (see below).

PasswordMaker Settings

PasswordMaker Settings

All of these can be altered for specific sites, e.g. use longer password lengths for banking sites etc..

If you’re not a fireFox user, there is a downloadable version for your desktop, or a JavaScript version you can save, or an online version (which also uses JavaScript they don’t post your details to a service! That would be nuts!).

PasswordMaker is a SourceForge project, so if you want to look under the hood, lend a hand or even get ideas for other neat ways to do something similar, you can.

I suspect we will see more of this social sites targeted for phishing as people are getting wise to the paypal, ebay, bank phishing and more browsers or browser toolbars are detecting these and blocking them. Leaving social sites that are perceived as low threat, for now, as a possible exploit vector.

So use different passwords for different sites, or you may be liable to one phish compromising your whole online life. There are tools to help!

Posted in Security, Software | Tagged , , , | Leave a comment

London Amateur Brewers

A very enjoyable evening at the LAB, cut short slightly by my need to go home and get some sleep. So I missed the tasting session at the end, which is quite often one of the most enjoyable sections.

I did however get to witness Mike E’s latest incarnation of this home brewery.

It would seem that Mike is very similar to myself with his brewing approach. For I too am a tinkerer in all things brewing (as well as photographic, software and anything else come to that matter).

One of things I’d mention that I have done differently.

A pump controller:
Similarly to Mike, my pump purchase from ebay was a slightly overrated liquid pump. I believe my pump will handle pumping a head of water to approx 8m or somewhere in the region of 400l/m. Slightly overkill for pump 25l to 50l about 1m over 10 to 20 minutes.

Rather that throttling the output of the pump with a ball value, I invested in a pump (aka ventilation fan from ebay) controller. This will control any a/c motor from idle (basically standstill) to full revs. Costing approx £10 from ebay including delivery, I deem this to be a better and safer solution to restricting the pump flow and presurising the wort.

I know that my hose clips from time to time may slip, and you only have to be vacant from the brewery for 30 seconds to have redecorated in “wort brown”, not something your better half would appreciate.

Posted in Brewing | Tagged , , | Leave a comment