Skip to content

Instantly share code, notes, and snippets.

@JonTheWhite
Created March 4, 2012 19:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JonTheWhite/1974368 to your computer and use it in GitHub Desktop.
Save JonTheWhite/1974368 to your computer and use it in GitHub Desktop.
Laravel Entity Generator
require 'ruble'
command 'Generate Entity Getter/Setters' do |cmd|
cmd.key_binding = 'M1+M2+G'
cmd.scope = 'source.php'
cmd.output = :replace_document
cmd.input = :document
cmd.invoke do |context|
file = context.TM_SELECTED_FILES.match(/([a-zA-Z0-9]+)\.php/)[1]
line = STDIN.read
columns = line.scan(/@Column\(name="([^"]+)", type="([^"]+)"/)
associations = line.scan(/@(ManyToMany|OneToMany|ManyToOne)\(targetEntity="([^"]+)"(?=.*?protected \$([a-zA-Z0-9_]+))/m)
columns.concat(associations)
getset = '
/**
* Get %s.
*
* @return %s
*/
public function get%s()
{
return $this->%s;
}
/**
* Sets the %s.
*
* @param %s $%s
* @return Entities\%s $this.
*/
public function set%s(%s$%s)
{
$this->%s = $%s;
return $this;
}
'
getsetmany = '
/**
* Get %s.
*
* @return Doctrine\Common\Collections\Collection
*/
public function get%s()
{
return $this->%s;
}
/**
* Add %s.
*
* @param %s $%s
* @return Entities\%s $this.
*/
public function add%s(%s$%s)
{
$this->%s[] = $%s;
return $this;
}
'
construct = '
/**
* Initializes the entity.
*
* @return void
*/
public function __construct()
{%s
}
'
collection = "\n $this->%s = new \\Doctrine\\Common\\Collections\\ArrayCollection();"
collections = ''
output = ''
columns.each do |match|
many = false
if match[2]
param = match[2]
cast = '\Entity '
if match[0] == 'OneToMany' || match[0] == 'ManyToMany'
many = true
end
else
param = match[0]
cast = ''
end
method = param.gsub(/((^)|_)([a-z])/) {|s| $2.to_s + $3.to_s.capitalize}
single = method.gsub(/s$/, '')
type = match[1]
if type == 'datetime'
cast = '\DateTime '
type = 'DateTime'
elsif type == 'text'
type = 'string'
end
if many
single_param = param.gsub(/s$/, '')
single_method = method.gsub(/s$/, '')
output = output + getsetmany % [param, method, param, single_param, type, single_param, file, single_method, cast, single_param, single_param, single_param]
collections = collections + collection % [param];
else
output = output + getset % [param, type, method, param, param, type, param, file, method, cast, param, param, param]
end
end
if collections
output = (construct % collections) + output
end
line = line.gsub(/\}\s*\z/, '')
line + output + "}\n"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment