Skip to content

Instantly share code, notes, and snippets.

@rheinardkorf
Created June 30, 2014 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rheinardkorf/56078b6907ddb6c041e9 to your computer and use it in GitHub Desktop.
Save rheinardkorf/56078b6907ddb6c041e9 to your computer and use it in GitHub Desktop.
A Ruby script for TextMate to cleanup your project's PHP according to WordPress PHP Coding Guidelines.
#!/usr/bin/env ruby
# Author: Rheinard Korf
# Usage:
# Needs to be added to a TextMate bundle as a new 'Command'
# Set command's input to 'None' and output to 'Show in Tool Tip'
# What it does:
# - Adds whitespace inside parentheses.
# - Adds whitespace after commas. Note: If you're using commas for comparing strings, just double check those.
# - Adds whitespace around =, ==, ===, =>
# - Adds whitespace before ! operator
# - Removes all trailing spaces
# - Replaces <? with <?php
# Todo:
# - Boolean operators (&&, ||)
# - Mathematical operators (+,-,*,%)
# - Compound assignment operators (+=, -=, etc)
# - Bitwise operator
path = ENV['TM_PROJECT_DIRECTORY'] ? ENV['TM_PROJECT_DIRECTORY'] : '.'
file_names = Dir.glob( "#{path}/**/*" )
count = 0
file_names.each do |file_name|
if ( ! File.directory?(file_name) ) then
text = File.read(file_name)
allowed_extensions = [ '.php' ]
if allowed_extensions.include? File.extname(file_name) then
# Parentheses
textx = text.gsub(/(\S)(?=\))/, '\1 ')
textx = textx.gsub(/\((?=\S)/, '( ')
textx = textx.gsub('( )', '()')
# Commas
textx = textx.gsub(/,(?=\S)/, ', \1')
# = operators
textx = textx.gsub(/=(?=[^\r\n\t\f=\>\W\ ])/, '= ')
textx = textx.gsub(/([^\r\n\t\f=\W\ ])(?=\=)/, '\1 ')
# ! not operator
textx = textx.gsub(/\!(?=[^\r\n\t\f=\ ])/, '! ')
# Remove trailing spaces
textx = textx.gsub(/[ \t]+$/, '')
# Remove PHP short tags
textx = textx.gsub(/<\?(?=\W)/, '<?php')
if text != textx then
File.open( file_name, "w") { |file| file.puts textx }
count += 1
puts "#{file_name} updated."
end
end
end
end
puts "Project cleaned. #{count} files updated."
@rheinardkorf
Copy link
Author

Still a work in progress, but already pretty useful I believe.

Note, limited it to .php, but should work ok for .js. Haven't tested. But please make sure you don't run it against all files. At least keep .php in there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment