Skip to content

Instantly share code, notes, and snippets.

@rheinardkorf
Last active August 29, 2015 14:03
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/772018146faab814cf0d to your computer and use it in GitHub Desktop.
Save rheinardkorf/772018146faab814cf0d to your computer and use it in GitHub Desktop.
A Ruby command line script to cleanup your project's PHP according to WordPress PHP Coding Guidelines.
#!/usr/bin/env ruby
# Author: Rheinard Korf
# Usage:
# Run from command line by passing the path as an argument (add a trailing slash).
# If path is not set it will use the current directory. (Not recommended)
# Examples:
# ruby wp-cleanup.rb /my/project/path/
# (OR set as executable "chmod +x wp-cleanup.rb")
# ./wp-cleanup.rb /my/project/path/
# 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 = ARGV[0] ? ARGV[0] : './'
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
# Parenthesis
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."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment