Guest User

Untitled

a guest
May 1st, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.72 KB | None | 0 0
  1. <?php
  2. require_once(dirname( __FILE__ ).'/../vendor/phpDataMapper/Model.php');
  3. require_once(dirname( __FILE__ ).'/../vendor/phpDataMapper/Database/Adapter/Mysql.php');
  4. require_once(dirname( __FILE__ ).'/../vendor/spyc.php');
  5.  
  6. $__database_yaml__ = dirname(__FILE__).'/../config/database.yaml';
  7.  
  8. /*
  9. *database.yaml format
  10. *
  11. *db:
  12. * {env}:
  13. * host: {host}
  14. * port: {port}
  15. * database: {database}
  16. * user: {user}
  17. * password: {password}
  18. *schema:
  19. * {class_name}: <- called 'Mapper class' in PHP DataMapper
  20. * table: {table_name}
  21. * fields:
  22. * {field_name}:
  23. * {attr}: {value} <- if {type} not defined
  24. * relations:
  25. * {relation_name}: <- when HasMany, pluralize e.g) post -> posts
  26. * relation: {relation_type} <- 'HasOne' or 'HasMany'
  27. * mapper: {mapper_class}
  28. * foreign_keys:
  29. * {my_pkey}: {foreign_key}
  30. */
  31.  
  32. class Model extends phpDataMapper_Model {
  33.  
  34. public static function datetime_now(){
  35. return date('Y/m/d H:i:s', strtotime('now'));
  36. }
  37.  
  38. public static function _make($attributes, $adapter=null, $klass){
  39. if(is_null($adapter)) $adapter = DB::proxy();
  40. $model = new $klass($adapter);
  41. if(is_null($attributes)) return $model->get();
  42. $pkey_name = $model->getPrimaryKeyField();
  43. $is_update = array_key_exists($pkey_name, $attributes);
  44. $model_row = $is_update?$model->get($attributes[$pkey_name]):$model->get();
  45. $related = array();
  46. foreach($attributes as $attr => $value){
  47. if(array_key_exists($attr, $model->fields)){
  48. $model_row->{$attr} = $value;
  49. }elseif(is_array($value) && !is_null($model->relations[$attr])){
  50. $related[] = $attr;
  51. }
  52. }
  53. if(!$is_update && !array_key_exists('created_at', $attributes) && array_key_exists('created_at', $model->fields))
  54. $model_row->created_at = self::datetime_now();
  55. if(!array_key_exists('updated_at', $attributes) && array_key_exists('updated_at', $model->fields))
  56. $model_row->updated_at = self::datetime_now();
  57. $last_id = $is_update?$model->update($model_row):$model->insert($model_row);
  58. $saved = $model->get((int)$last_id);
  59. foreach($related as $rel){
  60. $rattributes = $attributes[$rel];
  61. $fkeys = array();
  62. foreach($model->relations[$rel]['foreign_keys'] as $pkey => $fkey){
  63. $fkeys[$fkey] = $saved->{$pkey};
  64. }
  65. $rklass = $model->relations[$rel]['mapper'];
  66. switch($model->relations[$rel]['relation']){
  67. case 'HasOne':
  68. self::_make(array_merge($rattributes, $fkeys), $adapter, $rklass);
  69. brake;
  70. case 'HasMany':
  71. foreach($rattributes as $rattr) self::_make(array_merge($rattr, $fkeys), $adapter, $rklass);
  72. brake;
  73. }
  74. }
  75. return $saved;
  76. }
  77.  
  78. public static function _is($conditions, $orderby, $adapter=null, $klass){
  79. if(is_null($adapter)) $adapter = DB::proxy();
  80. $model = new $klass($adapter);
  81. return (!is_array($conditions)) ? $model->get($conditions) : $model->first($conditions, $orderby);
  82. }
  83.  
  84. public static function _are($conditions, $orderby, $adapter=null, $klass){
  85. if(is_null($adapter)) $adapter = DB::proxy();
  86. $model = new $klass($adapter);
  87. return $model->all($conditions, $orderby);
  88. }
  89.  
  90. }
  91.  
  92. class DBConfigration{
  93. public static function generateCode($config){
  94. if(is_null($config)) trigger_error("no configuration for generate database-classes code. please check '{$__database_yaml__}'", E_USER_ERROR);
  95. $code .= '
  96. class DB {
  97. public static $env = "development";
  98. public static function proxy($env=null){
  99. if(!is_null($env) && is_callable("self::{$env}")) self::$env = $env;
  100. $env = self::$env;
  101. if(is_callable("self::{$env}")){
  102. return self::$env();
  103. }else{
  104. trigger_error("cannot find database definition of \'{$env}\'. please check database.yaml.", E_USER_ERROR);
  105. }
  106. }
  107. ';
  108. foreach($config['db'] as $db_name => $info){
  109. $code .= "
  110. public static function {$db_name}(){
  111. return new phpDataMapper_Database_Adapter_Mysql('{$info['host']}', '{$info['database']}', '{$info['user']}', '{$info['password']}');
  112. }
  113. ";
  114. }
  115. $code .= '
  116. }
  117. ';
  118. foreach($config['schema'] as $class => $schema){
  119. $code .= '
  120. class '.$class.' extends Model {
  121. public $table = "'.$schema['table'].'";
  122. public $fields =
  123. array(
  124. ';
  125. foreach($schema['fields'] as $key => $value){
  126. $attributes ='';
  127. if(!is_array($value)){
  128. $attributes = "'type' => '{$value}'";
  129. if ($key == 'id') $attributes .= ",'primary' => true";
  130. }else{
  131. foreach($value as $k => $v){
  132. $attributes .= ($v == 'true') ? "'{$k}' => true,": "'{$k}' => '{$v}',";
  133. }
  134. }
  135. if($key == 'timestamps'){
  136. $code .= "
  137. 'created_{$value}' => array('type' => 'datetime'),
  138. 'updated_{$value}' => array('type' => 'datetime'),
  139. ";
  140. }else{
  141. $code .= "
  142. '{$key}' => array({$attributes}),
  143. ";
  144. }
  145. }
  146. $code .= '
  147. );
  148. ';
  149. if($schema['relations']){
  150. $code .= '
  151. public $relations =
  152. array(
  153. ';
  154.  
  155. foreach($schema['relations'] as $key => $value){
  156. foreach($value['foreign_keys'] as $k => $v){ $fkeys .= ($v == 'true') ? "'{$k}' => true," : "'{$k}' => '{$v}',"; }
  157. $code .= "
  158. '{$key}' =>
  159. array(
  160. 'relation' => '{$value['relation']}',
  161. 'mapper' => '{$value['mapper']}',
  162. 'foreign_keys' => array({$fkeys})
  163. ),
  164. ";
  165. }
  166. $code .= '
  167. );
  168. ';
  169. }
  170. $code .= '
  171. public static function make($attributes, $adapter=null){ return parent::_make($attributes, $adapter, get_class());}
  172. public static function is($conditions=array(), $orderby=array(), $adapter=null){ return parent::_is($conditions, $orderby, $adapter, get_class());}
  173. public static function are($conditions=array(), $orderby=array(), $adapter=null){ return parent::_are($conditions, $orderby, $adapter, get_class());}
  174. }
  175. ';
  176. }
  177. return $code;
  178. }
  179. }
  180.  
  181. eval(DBConfigration::generateCode(Spyc::YAMLLoad($__database_yaml__)));
  182. ?>
Add Comment
Please, Sign In to add comment