ModelBase.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 if ($value === null)
  92. $this->changed[$key] = "NULL";
  93. else
  94. $this->changed[$key] = self::$dbo->quote($value);
  95. return $value;
  96. }
  97. public function save()
  98. {
  99. \Tools\Hooks::trigger("onBeforeEntitySave");
  100. \Tools\Hooks::trigger("onBeforeEntitySave".$this->getTableName());
  101. if ($this->id === null)
  102. {
  103. if (empty ($this->changed))
  104. {
  105. $query = "INSERT INTO `{$this->getTableName()}` () VALUES ()";
  106. $result = self::$dbo->exec($query);
  107. if (!$result)
  108. throw new \Exception(self::$dbo->errorInfo()[2]);
  109. }
  110. else
  111. {
  112. $query = "INSERT INTO `{$this->getTableName()}` (`" .implode("`,`", array_keys($this->changed)) . "`) VALUES (" . implode(",", $this->changed) . ")";
  113. $result = self::$dbo->exec($query);
  114. if (!$result)
  115. throw new \Exception(self::$dbo->errorInfo()[2]);
  116. $this->changed = array();
  117. }
  118. $this->id = self::$dbo->lastInsertId();
  119. }
  120. else
  121. {
  122. if (!empty($this->changed))
  123. {
  124. if ($this->id === false)
  125. throw new \Exception("Cannot update private row");
  126. $query = "UPDATE {$this->getTableName()} SET ";
  127. $newValues = array();
  128. foreach ($this->changed as $i => $j)
  129. $newValues[] = "`{$i}`=" . $j;
  130. $query .= implode(",",$newValues)." WHERE id={$this->id}";
  131. $result = self::$dbo->exec($query);
  132. if (!$result)
  133. throw new \Exception(self::$dbo->errorInfo()[2]);
  134. $this->changed = array();
  135. }
  136. }
  137. \Tools\Hooks::trigger("onAfterEntitySave");
  138. \Tools\Hooks::trigger("onAfterEntitySave".$this->getTableName());
  139. }
  140. public function selects($criteria = null, $orderBy = null)
  141. {
  142. $query = "SELECT * FROM {$this->getTableName()}";
  143. if (!empty($criteria))
  144. {
  145. $subQuery = array();
  146. foreach ($criteria as $i => $j)
  147. {
  148. if ($j == null)
  149. $subQuery[] = "`{$i}` IS NULL";
  150. else if (is_array($j))
  151. {
  152. $inArray = [];
  153. foreach ($j as $k)
  154. $inArray[] = self::$dbo->quote($k);
  155. $subQuery[] = "`{$i}` IN (".implode(",", $inArray).")";
  156. }
  157. else
  158. $subQuery[] = "`{$i}`=".self::$dbo->quote($j);
  159. }
  160. $query .= " WHERE ".implode(" AND ", $subQuery);
  161. }
  162. if (!empty($orderBy))
  163. {
  164. $_orderBy = array();
  165. foreach ($orderBy as $i => $j)
  166. {
  167. if (is_numeric($i))
  168. $_orderBy[] = "`{$j}` ASC";
  169. else
  170. {
  171. $orderType = "ASC";
  172. if (strtoupper($j == "DESC"))
  173. $orderType = "DESC";
  174. $_orderBy[] = "`{$i}` {$orderType}";
  175. }
  176. }
  177. $query .= " ORDER BY ".implode(",", $_orderBy);
  178. }
  179. $result = self::$dbo->query($query, \PDO::FETCH_ASSOC);
  180. if ($result === false)
  181. throw new \Exception(self::$dbo->errorInfo()[2]);
  182. $resultObj = array();
  183. $className = get_class($this);
  184. foreach ($result as $i)
  185. {
  186. $iObj = new $className();
  187. $iObj->populate($i);
  188. $resultObj[] = $iObj;
  189. }
  190. return $resultObj;
  191. }
  192. public function selectById($id)
  193. {
  194. $query = "SELECT * FROM {$this->getTableName()} WHERE id=".(int)$id." LIMIT 1";
  195. $result = self::$dbo->query($query, \PDO::FETCH_ASSOC);
  196. if ($result === false || empty($result))
  197. throw new \Exception("Cannot fetch data: ".self::$dbo->errorInfo()[2]);
  198. $this->populate($result->fetch());
  199. }
  200. private function populate($data)
  201. {
  202. $this->id = FALSE;
  203. foreach ($data as $i => $j)
  204. $this->fieldsValues[$i] = $j;
  205. if (isset($this->fieldsValues["id"]))
  206. $this->id = (int) $this->fieldsValues["id"];
  207. $this->changed = array();
  208. }
  209. }