ModelBase.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. <?php
  2. namespace Entity;
  3. abstract class ModelBase
  4. {
  5. private $fieldsValues = array();
  6. protected static $dbo = null;
  7. private $changed = array();
  8. private static $config = null;
  9. private $id;
  10. protected abstract function install();
  11. public function __construct($id = null)
  12. {
  13. self::init();
  14. $this->id = null;
  15. if ($id !== null && is_numeric($id))
  16. $this->selectById($id);
  17. }
  18. public static function init($config = null)
  19. {
  20. if (self::$dbo !== null)
  21. return true;
  22. // @codeCoverageIgnoreStart
  23. // Load config from written file; this file is created from setup script
  24. if ($config === null && self::$config === null)
  25. {
  26. self::$config = @include("core/config.inc.php");
  27. if (empty(self::$config))
  28. return false;
  29. }
  30. // @codeCoverageIgnoreEnd
  31. else
  32. self::$config = $config;
  33. self::$dbo = new \PDO(self::$config[0], self::$config[1], self::$config[2]);
  34. return true;
  35. }
  36. public static function getDbPrefix()
  37. {
  38. return self::$config[3];
  39. }
  40. public function getTableName()
  41. {
  42. $className = new \ReflectionClass($this);
  43. return $this->getDbPrefix().strtolower($className->getShortName());
  44. }
  45. public static function setup()
  46. {
  47. $tables = array("Admin", "User", "Address", "Cart", "Category", "Product", "CartProduct", "Meta", "Cms", "Config", "Module", "ModuleHook");
  48. self::init();
  49. self::$dbo->beginTransaction();
  50. try
  51. {
  52. foreach ($tables as $i)
  53. {
  54. $i = "Entity\\".$i;
  55. $table = new $i();
  56. if ($table->install() != true)
  57. throw new \Exception("{$i}: Cannot table setup failure");
  58. }
  59. }
  60. catch (\Exception $e)
  61. {
  62. self::$dbo->rollBack();
  63. error_log($e->getMessage());
  64. return false;
  65. }
  66. self::$dbo->commit();
  67. return true;
  68. }
  69. public function getMeta($lang=null)
  70. {
  71. $fetcher = new \Entity\Meta();
  72. return $fetcher->query(array("type" => get_class($this)));
  73. }
  74. public function __get($key)
  75. {
  76. if ($key == "meta")
  77. return $this->getMeta();
  78. if ($key == "id")
  79. return $this->id === null ? null : (int) $this->id;
  80. if (!isset($this->fieldsValues[$key]))
  81. return null;
  82. return $this->fieldsValues[$key];
  83. }
  84. public function __set($key, $value)
  85. {
  86. if ($value instanceof \DateTime)
  87. $value = $value->format("Y-m-d");
  88. $this->fieldsValues[$key] = $value;
  89. if (is_bool($value))
  90. $this->changed[$key] = $value ? 1 : 0;
  91. else
  92. $this->changed[$key] = self::$dbo->quote($value);
  93. return $value;
  94. }
  95. public function save()
  96. {
  97. \Tools\Hooks::trigger("onBeforeEntitySave");
  98. \Tools\Hooks::trigger("onBeforeEntitySave".$this->getTableName());
  99. if ($this->id === null)
  100. {
  101. if (empty ($this->changed))
  102. {
  103. $query = "INSERT INTO `{$this->getTableName()}` () VALUES ()";
  104. $result = self::$dbo->exec($query);
  105. if (!$result)
  106. throw new \Exception(self::$dbo->errorInfo()[2]);
  107. }
  108. else
  109. {
  110. $query = "INSERT INTO `{$this->getTableName()}` (`" .implode("`,`", array_keys($this->changed)) . "`) VALUES (" . implode(",", $this->changed) . ")";
  111. $result = self::$dbo->exec($query);
  112. if (!$result)
  113. throw new \Exception(self::$dbo->errorInfo()[2]);
  114. $this->changed = array();
  115. }
  116. $this->id = self::$dbo->lastInsertId();
  117. }
  118. else
  119. {
  120. if (!empty($this->changed))
  121. {
  122. if ($this->id === false)
  123. throw new \Exception("Cannot update private row");
  124. $query = "UPDATE {$this->getTableName()} SET ";
  125. $newValues = array();
  126. foreach ($this->changed as $i => $j)
  127. $newValues[] = "`{$i}`=" . $j;
  128. $query .= implode(",",$newValues)." WHERE id={$this->id}";
  129. $result = self::$dbo->exec($query);
  130. if (!$result)
  131. throw new \Exception(self::$dbo->errorInfo()[2]);
  132. $this->changed = array();
  133. }
  134. }
  135. \Tools\Hooks::trigger("onAfterEntitySave");
  136. \Tools\Hooks::trigger("onAfterEntitySave".$this->getTableName());
  137. }
  138. public function selects($criteria = null, $orderBy = null)
  139. {
  140. $query = "SELECT * FROM {$this->getTableName()}";
  141. if (!empty($criteria))
  142. {
  143. $subQuery = array();
  144. foreach ($criteria as $i => $j)
  145. {
  146. if ($j == null)
  147. $subQuery[] = "`{$i}` IS NULL";
  148. else if (is_array($j))
  149. {
  150. $inArray = [];
  151. foreach ($j as $k)
  152. $inArray[] = self::$dbo->quote($k);
  153. $subQuery[] = "`{$i}` IN (".implode(",", $inArray).")";
  154. }
  155. else
  156. $subQuery[] = "`{$i}`=".self::$dbo->quote($j);
  157. }
  158. $query .= " WHERE ".implode(" AND ", $subQuery);
  159. }
  160. if (!empty($orderBy))
  161. {
  162. $_orderBy = array();
  163. foreach ($orderBy as $i => $j)
  164. {
  165. if (is_numeric($i))
  166. $_orderBy[] = "`{$j}` ASC";
  167. else
  168. {
  169. $orderType = "ASC";
  170. if (strtoupper($j == "DESC"))
  171. $orderType = "DESC";
  172. $_orderBy[] = "`{$i}` {$orderType}";
  173. }
  174. }
  175. $query .= " ORDER BY ".implode(",", $_orderBy);
  176. }
  177. $result = self::$dbo->query($query, \PDO::FETCH_ASSOC);
  178. if ($result === false)
  179. throw new \Exception(self::$dbo->errorInfo()[2]);
  180. $resultObj = array();
  181. $className = get_class($this);
  182. foreach ($result as $i)
  183. {
  184. $iObj = new $className();
  185. $iObj->populate($i);
  186. $resultObj[] = $iObj;
  187. }
  188. return $resultObj;
  189. }
  190. public function selectById($id)
  191. {
  192. $query = "SELECT * FROM {$this->getTableName()} WHERE id=".(int)$id." LIMIT 1";
  193. $result = self::$dbo->query($query, \PDO::FETCH_ASSOC);
  194. if ($result === false || empty($result))
  195. throw new \Exception("Cannot fetch data: ".self::$dbo->errorInfo()[2]);
  196. $this->populate($result->fetch());
  197. }
  198. private function populate($data)
  199. {
  200. $this->id = FALSE;
  201. foreach ($data as $i => $j)
  202. $this->fieldsValues[$i] = $j;
  203. if (isset($this->fieldsValues["id"]))
  204. $this->id = (int) $this->fieldsValues["id"];
  205. $this->changed = array();
  206. }
  207. }