PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/autobahn.php

https://github.com/soska/Autobahn
PHP | 327 lines | 275 code | 52 blank | 0 comment | 52 complexity | 7a806577d342a2e5ce46ba965b3fa727 MD5 | raw file
  1. <?php
  2. error_reporting(E_ALL);
  3. if(!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
  4. define('AUTOBAHN_ROOT', dirname(__FILE__).DS);
  5. if(!defined('AUTOBAHN_DBO')) define('AUTOBAHN_DBO', AUTOBAHN_ROOT.'dbo'.DS);
  6. if(!function_exists('getMicrotime'))
  7. {
  8. function getMicrotime()
  9. {
  10. list($usec, $sec) = explode(' ', microtime());
  11. return ((float)$usec + (float)$sec);
  12. }
  13. }
  14. if(!function_exists('pr'))
  15. {
  16. function pr($mixed)
  17. {
  18. if(PHP_SAPI != 'cli')
  19. {
  20. echo '<pre>';
  21. print_r($mixed);
  22. echo '</pre>';
  23. }
  24. else
  25. print_r($mixed);
  26. }
  27. }
  28. if(!function_exists('vd'))
  29. {
  30. function vd($mixed)
  31. {
  32. if(PHP_SAPI != 'cli')
  33. {
  34. echo '<pre>';
  35. var_dump($mixed);
  36. echo '</pre>';
  37. }
  38. else
  39. var_dump($mixed);
  40. }
  41. }
  42. if(!function_exists('camelize'))
  43. {
  44. function camelize($lowerCaseAndUnderscoredWord)
  45. {
  46. return str_replace(" ", "", ucwords(str_replace("_", " ", $lowerCaseAndUnderscoredWord)));
  47. }
  48. }
  49. if(!function_exists('underscore'))
  50. {
  51. function underscore($camelCasedWord)
  52. {
  53. return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord));
  54. }
  55. }
  56. if(!function_exists('humanize'))
  57. {
  58. function humanize($lowerCaseAndUnderscoredWord)
  59. {
  60. return ucwords(str_replace("_", " ", $lowerCaseAndUnderscoredWord));
  61. }
  62. }
  63. abstract class AutobahnManager
  64. {
  65. public $connected = false;
  66. public $debug = true;
  67. private $__logs = array();
  68. protected $_config;
  69. protected function __construct($config)
  70. {
  71. if(isset($config['prefix']))
  72. $this->_prefix = $config['prefix'];
  73. if(!isset($config['encoding']))
  74. $config['encoding'] = 'UTF8';
  75. $this->connect($config['host'], $config['user'], $config['password'], $config['database'], $config['encoding']);
  76. }
  77. private function __logQuery($sql, $time)
  78. {
  79. $this->__logs[] = array(
  80. 'sql' => $sql,
  81. 'took' => round((getMicrotime() - $time) * 1000, 0),
  82. 'affected' => $this->lastAffected(),
  83. 'error' => $this->lastError(),
  84. 'num_rows' => $this->lastNumRows(),
  85. );
  86. }
  87. public function query($sql)
  88. {
  89. $this->execute($sql);
  90. return $this->getFormatedRows();
  91. }
  92. public function execute($sql)
  93. {
  94. if($this->debug)
  95. $t = getMicrotime();
  96. $resource = $this->_execute($sql);
  97. if($this->debug)
  98. $this->__logQuery($sql, $t);
  99. return $resource;
  100. }
  101. public function getFormatedRows()
  102. {
  103. $fields = $this->getFields();
  104. $limit = $this->lastNumRows();
  105. $results = array();
  106. for($i = 0; ($i < $limit) && ($row = $this->getRow($i,'number')); $i++)
  107. {
  108. foreach($row as $index => $value)
  109. {
  110. if(!empty($fields[$index]['table']))
  111. $results[$i][$fields[$index]['table']][$fields[$index]['name']] = $value;
  112. else
  113. $results[$i][$fields[$index]['table']] = $value;
  114. }
  115. }
  116. return empty($results) ? false : $results;
  117. }
  118. public function showLogs()
  119. {
  120. if(PHP_SAPI != 'cli')
  121. {
  122. pr($this->__logs);
  123. }
  124. else
  125. print_r($this->__logs);
  126. }
  127. public function __call($method, $arguments)
  128. {
  129. if(strpos($method, 'findAll') === 0)
  130. {
  131. $magic = explode('findAll', $method);
  132. if(($magic[0] === '') && ($magic[1] !== ''))
  133. {
  134. if(strpos($magic[1], 'By') !== false)
  135. list($CamelizedTable, $CamelizedField) = explode('By', $magic[1]);
  136. else
  137. $CamelizedTable = $magic[1];
  138. if(isset($CamelizedField) && !empty($CamelizedField) && (count($arguments[0]) > 0))
  139. {
  140. $field = underscore($CamelizedField);
  141. $values = $this->_sqlEquivalentValues($arguments);
  142. $conditions = underscore($CamelizedField).' IN ('.implode(',',$values).')';
  143. }
  144. elseif(!isset($CamelizedField))
  145. $conditions = '';
  146. else
  147. return false;
  148. $query = array(
  149. 'fields' => '*',
  150. 'table' => underscore($CamelizedTable),
  151. 'conditions' => $conditions,
  152. 'group' => '',
  153. 'order' => '',
  154. 'limit' => '',
  155. );
  156. $sql = $this->renderStatement('select',$query);
  157. return $this->query($sql);
  158. }
  159. }
  160. elseif((count($arguments) === 1) && (strpos($method, 'find') === 0))
  161. {
  162. $magic = explode('find', $method);
  163. if(($magic[0] === '') && ($magic[1] !== '') && (strpos($magic[1], 'By') !== false))
  164. {
  165. list($CamelizedTable, $CamelizedField) = explode('By', $magic[1]);
  166. $value = is_numeric($arguments[0]) ? $arguments[0] : '\''.addslashes($arguments[0]).'\'';
  167. $query = array(
  168. 'fields' => '*',
  169. 'table' => underscore($CamelizedTable),
  170. 'conditions' => underscore($CamelizedField).' = '.$value,
  171. 'group' => '',
  172. 'order' => '',
  173. 'limit' => '1',
  174. );
  175. $sql = $this->renderStatement('select', $query);
  176. $result = $this->query($sql);
  177. return $result[0];
  178. }
  179. }
  180. elseif((count($arguments) === 1) && (strpos($method, 'insert') === 0))
  181. {
  182. $magic = explode('insert', $method);
  183. if(($magic[0] === '') && ($magic[1] !== ''))
  184. {
  185. $values = $this->_sqlEquivalentValues($arguments[0]);
  186. $fields = array_keys($values);
  187. $query = array(
  188. 'table' => underscore($magic[1]),
  189. 'fields' => $fields,
  190. 'values' => $values,
  191. );
  192. $sql = $this->renderStatement('insert', $query);
  193. return $this->execute($sql);
  194. }
  195. }
  196. elseif((count($arguments) === 2) && (strpos($method, 'update') === 0))
  197. {
  198. $magic = explode('update', $method);
  199. if(($magic[0] === '') && ($magic[1] !== ''))
  200. {
  201. $declarations = $this->_sqlEquivalentDeclarations($arguments[0]);
  202. $conditions = $this->_sqlEquivalentConditions($arguments[1]);
  203. $query = array(
  204. 'table' => underscore($magic[1]),
  205. 'fields' => $declarations,
  206. 'conditions' => implode(' AND ',$conditions),
  207. );
  208. $sql = $this->renderStatement('update', $query);
  209. return $this->execute($sql);
  210. }
  211. }
  212. elseif((count($arguments) > 0) && (strpos($method, 'delete') === 0))
  213. {
  214. $magic = explode('delete', $method);
  215. if(($magic[0] === '') && ($magic[1] !== ''))
  216. {
  217. if(strpos($magic[1], 'By') === false)
  218. return false;
  219. list($CamelizedTable, $CamelizedField) = explode('By', $magic[1]);
  220. $field = underscore($CamelizedField);
  221. $values = $this->_sqlEquivalentValues($arguments);
  222. $conditions = underscore($CamelizedField).' IN ('.implode(',',$values).')';
  223. $query = array(
  224. 'table' => underscore($CamelizedTable),
  225. 'conditions' => $conditions,
  226. );
  227. $sql = $this->renderStatement('delete', $query);
  228. return $this->execute($sql);
  229. }
  230. }
  231. else
  232. echo "Error. Method '$method' not found. ".count($arguments)." \n";
  233. }
  234. }
  235. class Autobahn
  236. {
  237. private static $__instances = array();
  238. private static $__configs;
  239. private static function getConfigClass()
  240. {
  241. if(!class_exists('DB_CONFIG'))
  242. {
  243. if(defined('AUTOBAHN_DB_CONFIG'))
  244. require(AUTOBAHN_DB_CONFIG);
  245. else
  246. trigger_error('No existe una base de datos configurada, tampoco un archivo de configuraciĆ³n definido.', E_ERROR);
  247. }
  248. self::$__configs = get_class_vars('DB_CONFIG');
  249. foreach (self::$__configs as $db => $config)
  250. {
  251. if(!isset($config['driver']))
  252. trigger_error('No "driver" in '.$db.' database configuration', E_ERROR);
  253. if(!isset($config['host']))
  254. trigger_error('No "host" in '.$db.' database configuration', E_ERROR);
  255. if(!isset($config['user']))
  256. trigger_error('No "user" in '.$db.' database configuration', E_ERROR);
  257. if(!isset($config['password']))
  258. trigger_error('No "password" in '.$db.' database configuration', E_ERROR);
  259. if(!isset($config['database']))
  260. trigger_error('No "database" name in '.$db.' configuration', E_ERROR);
  261. }
  262. }
  263. public static function getConnection($db = 'default')
  264. {
  265. if(self::$__configs == null)
  266. self::getConfigClass();
  267. if(isset(self::$__instances[$db]))
  268. return self::$__instances[$db];
  269. $c = 'AutobahnDbo'.ucfirst(self::$__configs[$db]['driver']);
  270. require(AUTOBAHN_DBO.'dbo_'.self::$__configs[$db]['driver'].'.php');
  271. return self::$__instances[$db] =& new $c(self::$__configs[$db]);
  272. }
  273. private function __construct() { }
  274. }
  275. ?>