Skip to content

Instantly share code, notes, and snippets.

@harto
Created August 13, 2013 00:13
Show Gist options
  • Save harto/6216623 to your computer and use it in GitHub Desktop.
Save harto/6216623 to your computer and use it in GitHub Desktop.
Hack to convert PHP code from `Quasi_Namespaced_Style` to `Properly\Namespaced\Style`
#!/usr/bin/env python
import re
import sys
CLASSNAME = re.compile(r'^(?:(?:abstract )?class|interface) ([\w_]+)', re.MULTILINE)
CLASSES = re.compile(r'\b([A-Z][a-z]\w+([_\\][A-Z][a-z]\w)+)')
def find_classname(body):
match = CLASSNAME.search(body)
if not match: raise Exception("Couldn't find classname")
return match.group(1)
def insert_namespace_stanza(body, ns):
return body.replace('<?php\n', '<?php\n\nnamespace %s;\n' % ns, 1)
def nsify(body):
fqn = find_classname(body)
segments = fqn.split('_')
ns = '\\'.join(segments[0:-1])
name = segments[-1]
body = insert_namespace_stanza(body, ns)
body = body.replace(fqn, name, 1)
body = re.sub(r'(OneToOne_[\w_]+)', lambda m: m.group(1).replace('_', '\\'), body)
body = CLASSES.sub(r'\\\1', body)
return body
def nsify_file(path):
# with open(path) as f: print nsify(f.read())
with open(path, 'r+') as f:
contents = nsify(f.read())
f.seek(0)
f.write(contents)
if __name__ == '__main__':
for path in sys.argv[1:]:
nsify_file(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment