-
-
Save LoreleiAurora/dac07baf2cf2552a2635 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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