Skip to content

Instantly share code, notes, and snippets.

@rogersguedes
Last active February 7, 2017 10:19
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 rogersguedes/b5880f371fd4f2d56f91 to your computer and use it in GitHub Desktop.
Save rogersguedes/b5880f371fd4f2d56f91 to your computer and use it in GitHub Desktop.
This script generate, for while, PHP classes files from a CSV exported from Astah Professional.
#!/usr/bin/python
import re
import sys
import getopt
import csv
import json
def to_snake_case(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
try:
opts, args = getopt.getopt(sys.argv[1:], "", ["doctrine"])
except getopt.GetoptError:
print "You must specify the path to CSV file containing the exported classes."
sys.exit(2)
myFile = []
useDoctrine = False
for option, value in opts:
if not useDoctrine and option == "--doctrine":
useDoctrine = True
try:
with open(args[0], 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
except IOError as e:
print e
sys.exit(2)
except IndexError as e:
print "You must specify the path to CSV file containing the exported classes."
sys.exit(2)
class JavaTypes():
INT = "int"
BOOLEAN = "boolean"
STRING = "String"
DOUBLE = "double"
BYTE = "byte"
SHORT = "short"
LONG = "long"
FLOAT = "float"
CHAR = "char"
javaTypesDict = [value for name, value in vars(JavaTypes).iteritems() if not name.startswith('_')]
class JavaStdClasses():
DATE = "Date"
JSONObject = "JSONObject"
UUID = "UUID"
BLOB = "Blob"
JavaStdClassesDict = [value for name, value in vars(JavaStdClasses).iteritems() if not name.startswith('_')]
class JavaTypeModifiers():
ARRAY = "[]"
php5ScalarTypes = {
JavaTypes.STRING: "string",
JavaTypes.INT: "integer",
JavaTypes.FLOAT: "float",
JavaTypes.DOUBLE: "float",
JavaTypes.BOOLEAN: "boolean",
JavaStdClasses.JSONObject: "array",
JavaTypeModifiers.ARRAY: "array",
JavaStdClasses.DATE : "DateTime"
}
doctrineClasses = {
JavaTypeModifiers.ARRAY: "ArrayCollection"
}
doctrineTypes = {
JavaTypes.STRING: "string",
JavaTypes.INT : "integer",
JavaTypes.SHORT : "smallint",
JavaTypes.LONG : "bigint",
JavaTypes.BOOLEAN : "boolean",
JavaTypes.DOUBLE : "decimal",
# JavaTypes.TIME : "time",
JavaStdClasses.DATE : "datetime",
# JavaTypes.DATETIMETZ : "datetimetz",
# JavaTypes.TEXT : "text",
# JavaTypes.OBJECT : "object",
# JavaTypeModifiers.ARRAY : "array",
# JavaTypes.SIMPLE_ARRAY : "simple_array",
JavaStdClasses.JSONObject : "json_array",
JavaTypes.FLOAT : "float",
JavaStdClasses.UUID : "guid",
JavaStdClasses.BLOB : "blob"
}
classes = {}
enums = {}
your_list = your_list[1:]
for line in your_list:
#get current class sign
classe = {}
classe["fullSign"] = line[1]#get the attribute class full sign
#get current attr sign
attr = {}
attr["fullSign"] = line[0]#get the current attribute full sign
result = re.search(r'(\w*)$', classe["fullSign"]);
classe["name"] = result.group(1)
if not classes.has_key(classe["name"]):
classes[classe["name"]] = []
result = re.search(r'(\w*)[\s:]*(<<)*([\w\s]+)*(>>)*[\s:]*(\w*)[\s:]*(\w*)([\[\]]*)', attr["fullSign"])
attrToInsert = {}
attrToInsert["visibility"] = result.group(1)
if result.group(2) is not None and result.group(3) != '' and result.group(4) is not None:
attrToInsert["stereotype"] = result.group(3)
attrToInsert["name"] = result.group(5)
attrToInsert["type"] = result.group(6)
else:
attrToInsert["name"] = result.group(3).strip()
attrToInsert["type"] = result.group(5)
if result.group(7) == "[]":
attrToInsert["isArray"] = True
if len(line[2]) > 0:
try:
rules = json.loads(line[2])
attrToInsert["defs"] = rules
print rules
except ValueError as e:
print line[2]
print "Malformed JSON"
classes[classe["name"]].append(attrToInsert)
if len(classes) == 0:
print "voce nao possui classes nesse arquivo"
tabs = "\t"
for classeDaVez in classes.keys():
try:
myFile = open(classeDaVez+".php", "w");
except IOError as e:
print e
myFile.write("<?php\n")
if useDoctrine:
myFile.write("/**\n * @Entity\n * @Table(name=\"{0}\", options={{\"collate\"=\"utf8_general_ci\"}})\n */\n".format(classeDaVez))
# Class header
## Consts
myFile.write("class {0}{{\n".format(classeDaVez))
for atrib in classes[classeDaVez]:
attrName = atrib["name"]
attrSnakeCasedName = to_snake_case(attrName).upper()
myFile.write("{0}const ATTR_{1} = \"{2}\";\n".format(tabs, attrSnakeCasedName, attrName))
if useDoctrine:
myFile.write("{0}const EM_{1} = {2};\n".format(tabs, attrSnakeCasedName, "self::ATTR_{0}".format(attrName)))
myFile.write(tabs+"\n")
## Attrs
for atrib in classes[classeDaVez]:
attrName = atrib["name"]
attrType = atrib["type"]
if useDoctrine:
comment = "{0}/**\n".format(tabs)
colAnnot = ""
varAnnot = ""
if attrType in javaTypesDict:
if doctrineTypes.has_key(attrType) and php5ScalarTypes.has_key(attrType):
colAnnot = "{0}{1} * @Column(type=\"{2}\")\n".format(colAnnot, tabs, doctrineTypes[attrType])
varAnnot = "{0}{1} * @var {2}\n".format(varAnnot, tabs, php5ScalarTypes[attrType])
else:
print "unknow doctrineType or php5ScalarTypes {0}".format(attrType)
exit(2)
elif attrType in JavaStdClassesDict:
if doctrineTypes.has_key(attrType):
colAnnot = "{0}{1} * @Column(type=\"{2}\")\n".format(colAnnot, tabs, doctrineTypes[attrType])
else:
print "There is not doctrineType for JavaStdClasses {0}".format(attrType)
if php5ScalarTypes.has_key(attrType):
varAnnot = "{0}{1} * @var {2}\n".format(varAnnot, tabs, php5ScalarTypes[attrType])
else:
print "There is not php5ScalarTypes for JavaStdClasses {0}".format(attrType)
else:
if classes.has_key(attrType):
colAnnot = "{0}{1} * @Relation >>> {2} <<<\n".format(colAnnot, tabs, attrType)
print colAnnot
else:
print "unknow DataType {0} in Class {1}. Maybe a not implemented Class...".format(attrType, classeDaVez)
if len(colAnnot) > 0:
comment = comment + colAnnot
else:
print "There is no colAnnot for {0} in Class {1}".format(attrType, classeDaVez)
if len(varAnnot) > 0:
comment = comment + varAnnot
else:
if not classes.has_key(attrType):
print "There is no valAnnot for {0} in Class {1}".format(attrType, classeDaVez)
comment = "{0}{1} */\n".format(comment, tabs)
myFile.write(comment)
myFile.write("{0}{1} ${2};\n".format(tabs, atrib["visibility"], attrName))
myFile.write(tabs+"\n")
## Class constructor
signature = tabs+"public function __construct("
quantParams = len(classes[classeDaVez])
i = 0
for atrib in classes[classeDaVez]:
#if atrib["type"] == classeDaVez:
# signature += "self "
#elif atrib["type"] in php7Types:
# signature += php7Types[atrib["type"]]+" "
#else:
# signature += atrib["type"]+" "
signature += "$"+atrib["name"]+"=null, "
#for i in range(quantParams - 1):
# myFile.write("$param"+str(i)+", ")
signature = signature[:-2]
signature += "){\n"
myFile.write(signature)
# attributes initilization
for atrib in classes[classeDaVez]:
myFile.write(str(tabs+tabs+"$this->%s = %s" % (atrib["name"], "$"+atrib["name"]+";\n")))
# getters and setters
myFile.write(tabs+"}\n")
myFile.write(tabs+"\n")
for atrib in classes[classeDaVez]:
if atrib["visibility"] != "public":
# get
myFile.write(str(tabs+"public function get"+atrib["name"][0].upper()+atrib["name"][1:]+"()"))
#if atrib["type"] != "":
# if atrib["type"] == classeDaVez:
# myFile.write(":self")
# elif atrib["type"] in php7Types:
# myFile.write(":"+php7Types[atrib["type"]])
# else:
# myFile.write(":"+atrib["type"])
myFile.write("{\n")
myFile.write(str(tabs*2+"return $this->"+atrib["name"]+";\n"))
myFile.write(str(tabs+"}\n\n"))
# set
#myFile.write(str(tabs+"public function set"+atrib["name"].capitalize()+"($param){\n"))
myFile.write(str(tabs+"public function set"+ atrib["name"][0].upper()+atrib["name"][1:]+"("))
#if atrib["type"] != "":
# if atrib["type"] == classeDaVez:
# myFile.write("self ")
# elif atrib["type"] in php7Types:
# myFile.write(php7Types[atrib["type"]]+" ")
# else:
# myFile.write(atrib["type"]+" ")
myFile.write(str("$param){\n"))
myFile.write(str(tabs*2+"$this->"+atrib["name"]+" = $param;\n"))
myFile.write("{0}return $this;\n".format(tabs*2))
myFile.write(str(tabs+"}\n\n"))
myFile.write("}\n")
myFile.write("?>\n")
myFile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment