Skip to content

Instantly share code, notes, and snippets.

@77web
Created May 28, 2011 06:35
Show Gist options
  • Save 77web/996668 to your computer and use it in GitHub Desktop.
Save 77web/996668 to your computer and use it in GitHub Desktop.
symfony1.xとdoctrineでテーブル定義書の雛型を自動生成させるタスク
<?php
/**
* @auther Hiromi Hishida<info@77-web.com>
*/
class tableDefineTask extends sfDoctrineBaseTask
{
protected function configure()
{
$this->namespace = 'table';
$this->name = 'define';
$this->briefDescription = 'Output table definition';
$this->detailedDescription = <<<EOF
The [table:define] task outputs table definition in csv format.
Call it with:
[./symfony table:definition]
EOF;
}
protected function execute($arguments = array(), $options = array())
{
//config/doctrine/schema.ymlを退避
$this->getFilesystem()->copy(sfConfig::get('sf_config_dir').'/doctrine/schema.yml', sfConfig::get('sf_data_dir').'/schema.yml.backup');
//build-schemaを実行
$this->runTask('doctrine:build-schema');
//yamlを読んでcsv化、data/table.csvに書き出す
$yaml = sfYaml::load(sfConfig::get('sf_config_dir').'/doctrine/schema.yml');
$rows = array();
$tables = array_keys($yaml);
foreach($tables as $no => $table)
{
$tables[$no] = sfInflector::tableize($table);
}
foreach($yaml as $table => $define)
{
$row = array(sfInflector::tableize($table));
$rows[] = $row;
foreach($define['columns'] as $name => $options)
{
//type
$type = isset($options['type']) ? $options['type'] : '-';
//desc
$comment = '';
if(isset($options['comment']))
{
$comment = $options['comment'];
}
elseif('id' === $name)
{
$comment = 'primary key';
}
elseif('_id' === substr($name, -3))
{
$_name = str_replace('_id', '', $name);
$comment = in_array($_name, $tables) ? 'foreign key of '.$_name : $name;
}
elseif('updated_at' === $name)
{
$comment = 'timestamp of data last update';
}
elseif('created_at' === $name)
{
$comment = 'timestamp of data created';
}
$row = array($name, $type, $comment);
$rows[] = $row;
}
}
$lines = array();
foreach($rows as $row)
{
$lines[] = '"'.implode('","', $row).'"';
}
$csv = implode("\r\n", $lines);
file_put_contents(sfConfig::get('sf_data_dir').'/table.csv', $csv);
//config/doctrine/schema.ymlを戻す
$this->getFilesystem()->remove(sfConfig::get('sf_config_dir').'/doctrine/schema.yml');
$this->getFilesystem()->copy(sfConfig::get('sf_data_dir').'/schema.yml.backup', sfConfig::get('sf_config_dir').'/doctrine/schema.yml');
//backupを削除
$this->getFilesystem()->remove(sfConfig::get('sf_data_dir').'/schema.yml.backup');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment