PageRenderTime 37ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Includes/Utils/Database.php

https://github.com/ckdimka/core
PHP | 419 lines | 155 code | 56 blank | 208 comment | 21 complexity | 8e7983a56688090ac451863dc3ea1965 MD5 | raw file
  1. <?php
  2. // vim: set ts=4 sw=4 sts=4 et:
  3. /**
  4. * LiteCommerce
  5. *
  6. * NOTICE OF LICENSE
  7. *
  8. * This source file is subject to the Open Software License (OSL 3.0)
  9. * that is bundled with this package in the file LICENSE.txt.
  10. * It is also available through the world-wide-web at this URL:
  11. * http://opensource.org/licenses/osl-3.0.php
  12. * If you did not receive a copy of the license and are unable to
  13. * obtain it through the world-wide-web, please send an email
  14. * to licensing@litecommerce.com so we can send you a copy immediately.
  15. *
  16. * PHP version 5.3.0
  17. *
  18. * @category LiteCommerce
  19. * @author Creative Development LLC <info@cdev.ru>
  20. * @copyright Copyright (c) 2011 Creative Development LLC <info@cdev.ru>. All rights reserved
  21. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  22. * @link http://www.litecommerce.com/
  23. * @see ____file_see____
  24. * @since 1.0.0
  25. */
  26. namespace Includes\Utils;
  27. /**
  28. * Database
  29. *
  30. * @see ____class_see____
  31. * @since 1.0.0
  32. */
  33. abstract class Database extends \Includes\Utils\AUtils
  34. {
  35. /**
  36. * DB handler
  37. *
  38. * @var \PDO
  39. * @access protected
  40. * @see ____var_see____
  41. * @since 1.0.0
  42. */
  43. protected static $handler;
  44. /**
  45. * Database connection options
  46. *
  47. * @var array
  48. * @access protected
  49. * @see ____var_see____
  50. * @since 1.0.0
  51. */
  52. protected static $dbOptions;
  53. /**
  54. * Setter method for $dbOptions. Once tries to connect and return connection object
  55. *
  56. * @return \PDO
  57. * @access public
  58. * @see ____func_see____
  59. * @since 1.0.0
  60. */
  61. public static function setDbOptions($options)
  62. {
  63. static::$dbOptions = $options;
  64. return static::getHandler();
  65. }
  66. /**
  67. * Reset method for $this->dbOptions
  68. *
  69. * @return void
  70. * @access public
  71. * @see ____func_see____
  72. * @since 1.0.0
  73. */
  74. public static function resetDbOptions()
  75. {
  76. static::$dbOptions = null;
  77. }
  78. /**
  79. * Return array of credentials to connect to DB
  80. *
  81. * @param bool $fullList add or not the additional fields
  82. *
  83. * @return array
  84. * @access public
  85. * @see ____func_see____
  86. * @since 1.0.0
  87. */
  88. public static function getConnectionParams($fullList = false)
  89. {
  90. $options = static::getDbOptions();
  91. $dsnFields = array(
  92. 'host' => 'hostspec',
  93. 'port' => 'port',
  94. 'unix_socket' => 'socket',
  95. 'dbname' => 'database',
  96. );
  97. foreach ($dsnFields as $pdoOption => $lcOption) {
  98. if (!empty($options[$lcOption])) {
  99. $dsnFields[$pdoOption] = $options[$lcOption];
  100. } else {
  101. unset($dsnFields[$pdoOption]);
  102. }
  103. }
  104. if ($fullList) {
  105. $dsnFields['username'] = static::getUsername();
  106. $dsnFields['password'] = static::getPassword();
  107. }
  108. return $dsnFields;
  109. }
  110. /**
  111. * Prepare MySQL connection string
  112. *
  113. * @return string
  114. * @access public
  115. * @see ____func_see____
  116. * @since 1.0.0
  117. */
  118. public static function getConnectionString()
  119. {
  120. return 'mysql:' . \Includes\Utils\Converter::buildQuery(static::getConnectionParams(), '=', ';');
  121. }
  122. /**
  123. * Getter method for $this->dbOptions
  124. *
  125. * @return array
  126. * @access protected
  127. * @see ____func_see____
  128. * @since 1.0.0
  129. */
  130. protected static function getDbOptions($name = null)
  131. {
  132. return \Includes\Utils\ArrayManager::getIndex(
  133. static::$dbOptions ?: \Includes\Utils\ConfigParser::getOptions(array('database_details')),
  134. $name
  135. );
  136. }
  137. /**
  138. * Return name of database user
  139. *
  140. * @return string
  141. * @access protected
  142. * @see ____func_see____
  143. * @since 1.0.0
  144. */
  145. protected static function getUsername()
  146. {
  147. return static::getDbOptions('username');
  148. }
  149. /**
  150. * Return password of database user
  151. *
  152. * @return string
  153. * @access protected
  154. * @see ____func_see____
  155. * @since 1.0.0
  156. */
  157. protected static function getPassword()
  158. {
  159. return static::getDbOptions('password');
  160. }
  161. /**
  162. * Return list of the \PDO connection options
  163. *
  164. * @return array
  165. * @access protected
  166. * @see ____func_see____
  167. * @since 1.0.0
  168. */
  169. protected static function getConnectionFlags()
  170. {
  171. return array(
  172. \PDO::ATTR_AUTOCOMMIT => true,
  173. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  174. \PDO::ATTR_PERSISTENT => false,
  175. );
  176. }
  177. /**
  178. * Connect to database
  179. *
  180. * @return \PDO
  181. * @access protected
  182. * @see ____func_see____
  183. * @since 1.0.0
  184. */
  185. protected static function connectToDb()
  186. {
  187. return new \PDO(
  188. static::getConnectionString(),
  189. static::getUsername(),
  190. static::getPassword(),
  191. static::getConnectionFlags()
  192. );
  193. }
  194. /**
  195. * Return \PDO database handler
  196. *
  197. * @return \PDO
  198. * @access protected
  199. * @see ____func_see____
  200. * @since 1.0.0
  201. */
  202. protected static function getHandler()
  203. {
  204. if (!isset(static::$handler)) {
  205. static::$handler = static::connectToDb();
  206. }
  207. return static::$handler;
  208. }
  209. /**
  210. * Execute SQL query and return the PDO statement object
  211. *
  212. * @param string $sql SQL query to execute
  213. * @param array $params Query params
  214. *
  215. * @return \PDOStatement
  216. * @access public
  217. * @see ____func_see____
  218. * @since 1.0.0
  219. */
  220. public static function executeStatement($sql, array $params = array())
  221. {
  222. $statement = static::getHandler()->prepare($sql);
  223. $statement->execute($params);
  224. return $statement;
  225. }
  226. /**
  227. * Perform SQL query (return araay of records)
  228. *
  229. * @param string $sql SQL query to execute
  230. * @param array $params Query params
  231. * @param integer $flags \PDO fetch option
  232. *
  233. * @return array
  234. * @access public
  235. * @see ____func_see____
  236. * @since 1.0.0
  237. */
  238. public static function fetchAll($sql, array $params = array(), $flags = \PDO::FETCH_ASSOC)
  239. {
  240. return static::executeStatement($sql, $params)->fetchAll($flags);
  241. }
  242. /**
  243. * Perform SQL query (single value)
  244. *
  245. * @param string $sql SQL query to execute
  246. * @param array $params Query params
  247. *
  248. * @return string
  249. * @access public
  250. * @see ____func_see____
  251. * @since 1.0.0
  252. */
  253. public static function fetchColumn($sql, array $params = array())
  254. {
  255. return static::executeStatement($sql, $params)->fetchColumn();
  256. }
  257. /**
  258. * Perform parameterized SQL query and return the flag (success or not)
  259. *
  260. * @param string $sql SQL query to execute
  261. * @param array $params Query params
  262. *
  263. * @return void
  264. * @access public
  265. * @see ____func_see____
  266. * @since 1.0.0
  267. */
  268. public static function execute($sql, array $params = array())
  269. {
  270. static::executeStatement($sql, $params);
  271. }
  272. /**
  273. * Perform SQL query
  274. *
  275. * @param string $sql SQL query to execute
  276. * @param array $params query params
  277. *
  278. * @return bool
  279. * @access public
  280. * @see ____func_see____
  281. * @since 1.0.0
  282. */
  283. public static function exec($sql)
  284. {
  285. return static::getHandler()->exec($sql);
  286. }
  287. /**
  288. * Get the database version
  289. *
  290. * @return void
  291. * @access public
  292. * @see ____func_see____
  293. * @since 1.0.0
  294. */
  295. public static function getDbVersion()
  296. {
  297. return static::getHandler()->getAttribute(\PDO::ATTR_SERVER_VERSION);
  298. }
  299. /**
  300. * Execute a set of SQL queries from file
  301. *
  302. * :FIXME: must be completely revised
  303. *
  304. * @param string $fileName Name of SQL-file
  305. * @param boolean $verbose Display uploading progress flag OPTIONAL
  306. *
  307. * @return boolean
  308. * @see ____func_see____
  309. * @since 1.0.0
  310. */
  311. public static function uploadSQLFromFile($fileName, $verbose = false)
  312. {
  313. $result = false;
  314. if (false == \Includes\Utils\FileManager::isFileReadable($fileName)) {
  315. throw new \InvalidArgumentException(
  316. sprintf('SQL file \'%s\' not found or is not readable', $fileName)
  317. );
  318. } else {
  319. $fp = fopen($fileName, 'rb');
  320. $sql = '';
  321. $result = true;
  322. while ($result && !feof($fp)) {
  323. $c = '';
  324. // Read SQL statement from file
  325. do {
  326. $c .= fgets($fp, 1024);
  327. $endPos = strlen($c) - 1;
  328. } while (substr($c, $endPos) != PHP_EOL && !feof($fp));
  329. $c = rtrim($c);
  330. // Skip comments
  331. if (substr($c, 0, 1) == '#' || substr($c, 0, 2) == '--') {
  332. continue;
  333. }
  334. // Parse SQL statement
  335. $sql .= $c;
  336. if (substr($sql, -1) == ';') {
  337. $sql = substr($sql, 0, strlen($sql) - 1);
  338. // Execute SQL query
  339. try {
  340. static::getHandler()->beginTransaction();
  341. $result = (false !== static::exec($sql));
  342. if ($result) {
  343. static::getHandler()->commit();
  344. } else {
  345. static::getHandler()->rollBack();
  346. }
  347. if ($verbose) {
  348. echo ('.');
  349. flush();
  350. }
  351. } catch (\PDOException $e) {
  352. static::getHandler()->rollBack();
  353. $result = false;
  354. echo ('<br />' . $e->getMessage());
  355. }
  356. $sql = '';
  357. }
  358. }
  359. fclose($fp);
  360. }
  361. return $result;
  362. }
  363. }