Skip to content

Instantly share code, notes, and snippets.

@scribu
Created June 8, 2013 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save scribu/5735050 to your computer and use it in GitHub Desktop.
Save scribu/5735050 to your computer and use it in GitHub Desktop.
WordPress code formatting utility
#!/usr/bin/php
<?php
/**
* Takes some code from STDIN, fixes whitespace according to the WordPress Coding Standards and outputs it to STDOUT
* Usage example: wpformat < some-file.php > some-file.php
*/
// Read file from standard input
$file = '';
while (!feof(STDIN)) {
$file .= fread(STDIN, 8192);
}
// put placeholders on lines that have preg_*() functions
global $pregs;
$pregs = array();
$file = preg_replace_callback( "#preg_.*?\n#", function($match) {
global $pregs;
$match = reset( $match );
$key = "[--wp-format-" . md5( $match ) . "--]\n";
$pregs[$key] = $match;
return $key;
}, $file );
// add spaces after language constructs
$file = preg_replace('#(if|else|elseif|switch|for|foreach|while)\s*\(#', '\1 (', $file);
// add spaces between function arguments
$file = preg_replace('#\( *#', '( ', $file);
$file = preg_replace('# *\)#', ' )', $file);
$file = preg_replace('#\(\ +\)#', '()', $file);
// strip spaces around casts
$file = preg_replace('#\( *(bool|int|float|string|array|object) *\) *#', '(\1) ', $file);
// strip spaces when parantheses are at the beginning of the line
$file = preg_replace('#(\n\t*) +([\(\)])#m', '\1\2', $file);
// strip trailing whitespace
$file = preg_replace('#[\t ]+\n#m', "\n", $file);
// remove preg_* placeholders
$file = str_replace( array_keys( $pregs ), array_values( $pregs ), $file );
// Write to standard output
echo $file;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment