Source for file EntityGenerator.php

Documentation is available at EntityGenerator.php

  1. <?php
  2. /**
  3.  * Teeple2 - PHP5 Web Application Framework inspired by Seasar2
  4.  *
  5.  * PHP versions 5
  6.  *
  7.  * LICENSE: This source file is subject to version 3.0 of the PHP license
  8.  * that is available through the world-wide-web at the following URI:
  9.  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
  10.  * the PHP License and are unable to obtain it through the web, please
  11.  * send a note to license@php.net so we can mail you a copy immediately.
  12.  *
  13.  * @package     teeple
  14.  * @author      Mitsutaka Sato <miztaka@gmail.com>
  15.  * @license     http://www.php.net/license/3_0.txt  PHP License 3.0
  16.  */
  17.  
  18. require_once 'creole/Creole.php';
  19.  
  20. /**
  21.  * Entityを自動生成するロジックです。
  22.  *
  23.  * @package teeple
  24.  */
  25.  
  26.     /**
  27.      * @var Logger 
  28.      */
  29.     protected $log;
  30.  
  31.     /**
  32.      * @var Teeple_DataSource 
  33.      */
  34.     protected $dataSource;
  35.     public function setComponent_Teeple_DataSource($c{
  36.         $this->dataSource = $c;
  37.     }
  38.  
  39.     /**
  40.      * コンストラクタです。
  41.      */
  42.     public function __construct({
  43.         $this->log = LoggerManager::getLogger(get_class($this));
  44.     }
  45.  
  46.     /**
  47.      * Entityを生成します。
  48.      * 
  49.      */
  50.     public function execute({
  51.         $config $this->dataSource->getDataSourceConfig();
  52.         foreach ($config as $name => $dsn{
  53.             $this->generate($name$this->convertDSN($dsn));
  54.         }
  55.     }
  56.  
  57.     private function generate($name$dsn{
  58.  
  59.         $datasource $name;
  60.         $outputdir dirname(__FILE__)."/../../../components/entity";
  61.  
  62.         /*
  63.          * start.
  64.          */
  65.         $conn Creole::getConnection($dsn);
  66.         $dbinfo $conn->getDatabaseInfo();
  67.  
  68.         $base_dir $outputdir .'/''base';
  69.         if (file_exists($base_dir&& mkdir($base_dir)) {
  70.             print "could not make directory for base: {$outputdir}";
  71.             exit;
  72.         }
  73.  
  74.         foreach($dbinfo->getTables(as $tbl{
  75.             $classname "";
  76.             $tablename "";
  77.             $capName "";
  78.             $pkdef "";
  79.             $coldef "";
  80.             $joindef "";
  81.             $aliasesdef "";
  82.  
  83.             $tablename strtolower($tbl->getName());
  84.             $capName $this->camelize($tablename);
  85.             $classname "Entity_{$capName}";
  86.             $baseclassname "Entity_Base_{$capName}";
  87.  
  88.             // columns
  89.             $cols array();
  90.             foreach($tbl->getColumns(as $col{
  91.                 $cols[strtolower($col->getName());
  92.             }
  93.  
  94.             // primary key
  95.             $pks array();
  96.             $pk $tbl->getPrimaryKey();
  97.             if (is_object($pk)) {
  98.                 foreach($pk->getColumns(as $pkcol{
  99.                     $pks[strtolower($pkcol->getName());
  100.                 }
  101.             }
  102.  
  103.             // join
  104.             $aliases array();
  105.             $joindef_buf array();
  106.             $fks $tbl->getForeignKeys();
  107.             if (is_array($fks)) {
  108.                 foreach($fks as $fk{
  109.                     $alias "";
  110.                     $entity "";
  111.                     $refdef array();
  112.  
  113.                     $refs $fk->getReferences();
  114.                     if (is_array($refs)) {
  115.                         //$alias = strtolower($fk->getName());
  116.                         $alias strtolower($refs[0][1]->getTable()->getName());
  117.                         $entity 'Entity_'$this->camelize($refs[0][1]->getTable()->getName());
  118.                         $aliases[array(
  119.                     'name' => $alias,
  120.                     'entity' => $entity
  121.                         );
  122.  
  123.                         foreach($refs as $ref{
  124.                             $p strtolower($ref[0]->getName());
  125.                             $c strtolower($ref[1]->getName());
  126.                             $refdef["                '{$p}' => '{$c}'";
  127.                         }
  128.  
  129.                         $buf "";
  130.                         $buf .= "        '{$alias}' => array(\n";
  131.                         $buf .= "            'entity' => '{$entity}',\n";
  132.                         $buf .= "            'type' => 'INNER JOIN',\n";
  133.                         $buf .= "            'relation' => array(\n";
  134.                         $buf .= implode(",\n"$refdef);
  135.                         $buf .= "\n";
  136.                         $buf .= "            )\n";
  137.                         $buf .= "        )";
  138.  
  139.                         $joindef_buf[$buf;
  140.                     }
  141.                 }
  142.             }
  143.             if (count($joindef_buf)) {
  144.                 $joindef implode(",\n"$joindef_buf);
  145.             }
  146.  
  147.             if (count($aliases)) {
  148.                 foreach ($aliases as $alias{
  149.                     $aliasesdef .= <<<EOT
  150.     /**
  151.      * @var {$alias['entity']
  152.      */
  153.     public \${$alias['name']};
  154.  
  155.  
  156. EOT;
  157.                 }
  158.             }
  159.  
  160.             //$cols = array_diff($cols, $pks);
  161.             foreach ($cols as $col{
  162.                 $coldef .= "    public \$".$col.";\n";
  163.             }
  164.  
  165.             //$coldef = "'". implode("',\n        '", $cols) ."'";
  166.             $pkdef "'"implode("',\n'"$pks."'";
  167.  
  168.             // ベースクラスの作成
  169.             $filepath $outputdir ."/base/{$capName}.php";
  170.             if (file_exists($filepath)) {
  171.                 print "{$tablename}: base class already exists. \n";
  172.                 continue;
  173.             }
  174.             if (!$handle fopen($filepath'wb')) {
  175.                 print "{$filepath}: could not open file. \n";
  176.                 continue;
  177.             }
  178.  
  179.             $contents = <<<EOT
  180. class {$baseclassname} extends Teeple_ActiveRecord
  181. {
  182.  
  183.     /**
  184.      * 使用するデータソース名を指定します。
  185.      * 指定が無い場合は、DEFAULT_DATASOURCE で設定されているDataSource名が使用されます。
  186.      *
  187.      * @var string
  188.      */
  189.     public static \$_DATASOURCE = '{$datasource}';
  190.     
  191.     /**
  192.      * このエンティティのテーブル名を設定します。
  193.      * 
  194.      * <pre>
  195.      * スキーマを設定する場合は、"スキーマ.テーブル名"とします。
  196.      * 子クラスにて必ずセットする必要があります。
  197.      * </pre>
  198.      *
  199.      * @var string
  200.      */
  201.     public static \$_TABLENAME = '{$tablename}';
  202.     
  203.     /**
  204.      * プライマリキー列を設定します。
  205.      * 
  206.      * <pre>
  207.      * プライマリキーとなるカラム名を配列で指定します。
  208.      * 子クラスにて必ずセットする必要があります。
  209.      * </pre>
  210.      * 
  211.      * @var array 
  212.      */
  213.     public static \$_PK = array(
  214.         {$pkdef}
  215.     );
  216.     
  217.     /**
  218.      * このテーブルのカラム名をpublicプロパティとして設定します。(プライマリキーを除く)
  219.      * <pre>
  220.      * 子クラスにて必ずセットする必要があります。
  221.      * </pre>
  222.      */
  223. {$coldef}
  224.     
  225.     /**
  226.      * プライマリキーが自動セット(auto increment)かどうかを設定します。
  227.      * 
  228.      * <pre>
  229.      * 子クラスにて必ずセットする必要があります。
  230.      * </pre>
  231.      * 
  232.      * @var bool 
  233.      */
  234.     public static \$_AUTO = TRUE;
  235.  
  236. }
  237. EOT;
  238.  
  239.             $contents "<?php \n\n"$contents ."\n\n?>";
  240.             if (fwrite($handle$contents=== FALSE{
  241.                 print "{$filepath}: failed to write to the file. \n";
  242.                 continue;
  243.             }
  244.  
  245.             print "{$tablename}: entity base class created . \n";
  246.             fclose($handle);
  247.  
  248.             // エンティティクラスの作成
  249.             $filepath $outputdir ."/{$capName}.php";
  250.             if (file_exists($filepath)) {
  251.                 print "{$tablename}: entity class already exists. \n";
  252.                 continue;
  253.             }
  254.             if (!$handle fopen($filepath'wb')) {
  255.                 print "{$filepath}: could not open file. \n";
  256.                 continue;
  257.             }
  258.  
  259.             $contents = <<<EOT
  260. /**
  261.  * Entity Class for {$tablename}
  262.  *
  263.  * エンティティに関するロジック等はここに実装します。
  264.  * @package entity
  265.  */
  266. class {$classname} extends {$baseclassname}
  267. {
  268.     /**
  269.      * インスタンスを取得します。
  270.      * @return {$classname}
  271.      */
  272.     public static function get() {
  273.         return Teeple_Container::getInstance()->getEntity('{$classname}');
  274.     }
  275.     
  276.     /**
  277.      * 単一行の検索を実行します。
  278.      * @param \$id
  279.      * @return {$classname}
  280.      */
  281.     public function find(\$id=null) {
  282.         return parent::find(\$id);
  283.     }
  284.     
  285.     /**
  286.      * JOINするテーブルを設定します。
  287.      * ※generatorが吐き出した雛形を修正してください。
  288.      * 
  289.      * ここに設定してある定義は、\$this->join('aliasname') で利用できる。<br/>
  290.      * ※ここに設定しただけではJOINされない。
  291.      * 
  292.      * <pre>
  293.      * 指定方法: 'アクセスするための別名' => 設定値の配列
  294.      * 設定値の配列:
  295.      *   'entity' => エンティティのクラス名
  296.      *  'columns' => 取得するカラム文字列(SQLにセットするのと同じ形式)
  297.      *   'type' => JOINのタイプ(SQLに書く形式と同じ)(省略した場合はINNER JOIN)
  298.      *   'relation' => JOINするためのリレーション設定
  299.      *      「本クラスのキー名 => 対象クラスのキー名」となります。
  300.      *   'condition' => JOINするための設定だがリテラルで指定するもの
  301.      * 
  302.      * 値の例:
  303.      * 
  304.      * \$join_config = array(
  305.      *     'aliasname' => array(
  306.      *         'entity' => 'Entity_Fuga',
  307.      *         'columns' => 'foo, bar, hoge',
  308.      *         'type' => 'LEFT JOIN',
  309.      *         'relation' => array(
  310.      *             'foo_id' => 'bar_id'
  311.      *         ),
  312.      *         'condition' => 'aliasname.status = 1 AND parent.status = 1'
  313.      *     )
  314.      * );
  315.      * </pre>
  316.      * 
  317.      * @var array
  318.      */
  319.     public static \$_JOINCONFIG = array(
  320. {$joindef}
  321.     );
  322.     
  323. {$aliasesdef}
  324.  
  325. }
  326. EOT;
  327.  
  328.             $contents "<?php \n\n"$contents ."\n\n?>";
  329.             if (fwrite($handle$contents=== FALSE{
  330.                 print "{$filepath}: failed to write to the file. \n";
  331.                 continue;
  332.             }
  333.  
  334.             print "{$tablename}: entity class created . \n";
  335.             fclose($handle);
  336.         // end of foreach
  337.     }
  338.  
  339.     private function convertDSN($dsn{
  340.  
  341.         $username $dsn['user'];
  342.         $password $dsn['pass'];
  343.         list($phptype$confexplode(':'$dsn['dsn']);
  344.         $buff explode(';'$conf);
  345.         foreach ($buff as $item{
  346.             list($key$valexplode('='$item);
  347.             switch($key{
  348.                 case 'host':
  349.                     $hostspec $val;
  350.                     break;
  351.                 case 'dbname':
  352.                     $database $val;
  353.                     break;
  354.             }
  355.         }
  356.  
  357.         return array(
  358.             'phptype' => $phptype,
  359.             'hostspec' => $hostspec,
  360.             'username' => $username,
  361.             'password' => $password,
  362.             'database' => $database
  363.         );
  364.     }
  365.     
  366.     private function camelize($str{
  367.         
  368.         $tablename strtolower($str);
  369.         $ar split('_'$tablename);
  370.         $capName '';
  371.         foreach($ar as $val{
  372.             $capName .= ucfirst($val);
  373.         }
  374.         return $capName;
  375.     }
  376.  
  377. }
  378.  
  379. ?>

Documentation generated on Mon, 26 Apr 2010 08:59:44 +0900 by phpDocumentor 1.4.3