model.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. <?php /** @noinspection PhpUnused */
  2. abstract class Model {
  3. protected static $table = "";
  4. protected static $id_field = "";
  5. protected static $fillable_fields = [];
  6. protected static $enforce_field_check = true;
  7. protected static $field_map = []; // Used for field name aliases
  8. protected static $object_fields = [];
  9. protected static $blob_fields = [];
  10. protected static $repositories = [];
  11. // Object variables
  12. protected $model_data;
  13. protected $modified_fields = [];
  14. protected $in_db;
  15. // Magic methods
  16. /**
  17. * @param string $name
  18. * @return mixed
  19. */
  20. public function __get(string $name) {
  21. if(in_array($name, static::$object_fields)) {
  22. return $this->$name ?? null;
  23. }
  24. if(isset(static::$field_map[$name])) {
  25. $name = static::$field_map[$name];
  26. }
  27. return isset($this->model_data->$name) ? $this->model_data->$name : null;
  28. }
  29. /**
  30. * @param string $name
  31. * @param string $value
  32. * @throws Exception
  33. */
  34. public function __set(string $name, string $value): void {
  35. if(in_array($name, static::$object_fields)) {
  36. $this->$name = $value;
  37. return;
  38. }
  39. if(isset(static::$field_map[$name])) {
  40. $name = static::$field_map[$name];
  41. }
  42. $id_field = static::$id_field;
  43. if($name == "model_data") {
  44. $this->model_data = $value;
  45. }
  46. else if(in_array($name, static::$fillable_fields)) {
  47. if(!is_null($value)) {
  48. $value = strval($value);
  49. }
  50. if(!isset($this->model_data->$name) || ($this->model_data->$name !== $value)) {
  51. $this->model_data->$name = $value;
  52. $this->modified_fields[] = $name;
  53. }
  54. }
  55. else if($name == $id_field && empty($this->model_data->$id_field)) {
  56. $this->model_data->$id_field = $value;
  57. }
  58. else if(static::$enforce_field_check) {
  59. throw new Exception("Attempt to set an unfillable field $name");
  60. }
  61. else {
  62. $this->model_data->$name = $value;
  63. }
  64. }
  65. /**
  66. * @param string $name
  67. * @return bool
  68. */
  69. public function __isset(string $name) {
  70. $value = $this->$name;
  71. return !is_null($value);
  72. }
  73. // Static method
  74. /**
  75. * @param $id
  76. * @return static|null
  77. * @throws Exception
  78. */
  79. public static function get($id): ?object {
  80. $table = static::$table;
  81. $is_compound_key = is_array(static::$id_field);
  82. // Check repo for item
  83. if(!$is_compound_key && isset(static::$repositories[$table][$id])) {
  84. return static::$repositories[$table][$id];
  85. }
  86. $id_field = static::$id_field;
  87. $nvp = [];
  88. if($is_compound_key && is_array($id_field)) { // Compound key
  89. $args = func_get_args();
  90. $fields = $id_field;
  91. if(count($args) != count($fields)) return null;
  92. foreach($fields as $index => $field) {
  93. $nvp[$field] = $args[$index];
  94. }
  95. }
  96. else {
  97. $nvp[$id_field] = $id;
  98. }
  99. $where = db::get_where_string($nvp, true);
  100. $sql = "SELECT * FROM `$table` WHERE $where";
  101. $result = db::query($sql);
  102. $object = db::object_or_null($result);
  103. if($object) {
  104. $object = new static($object);
  105. if(!$is_compound_key) {
  106. static::$repositories[$table][$id] = $object;
  107. }
  108. }
  109. return $object;
  110. }
  111. /**
  112. * @param int $id
  113. * @param bool $exception_message
  114. * @return static|null
  115. * @throws Exception
  116. */
  117. public static function getOrException(int $id, bool $exception_message = false): ?object {
  118. if(!$exception_message) $exception_message = get_called_class() . " not found.";
  119. $object = static::get($id);
  120. if(!$object) throw new Exception($exception_message);
  121. return $object;
  122. }
  123. /**
  124. * @return static[]
  125. * @throws Exception
  126. */
  127. public static function getAll(): array {
  128. $objects = [];
  129. $table = static::$table;
  130. $sql = "SELECT * FROM `$table`";
  131. $result = db::query($sql);
  132. while($row = db::fetch_object($result)) {
  133. $objects[] = new static($row);
  134. }
  135. return $objects;
  136. }
  137. /**
  138. * @param array ...$id_sets
  139. * @return static[]
  140. * @throws Exception
  141. */
  142. public static function load(...$id_sets): array {
  143. $table = static::$table;
  144. $ids = [];
  145. foreach($id_sets as $set) {
  146. $ids = array_merge($ids, $set);
  147. }
  148. if(empty($ids)) return [];
  149. $ids = array_unique($ids);
  150. $items = static::query([static::$id_field => $ids], ["id_as_key" => true]);
  151. foreach($items as $id => $item) {
  152. static::$repositories[$table][$id] = $item;
  153. }
  154. return $items;
  155. }
  156. /**
  157. * @return static[]
  158. * @throws Exception
  159. */
  160. public static function loadAll(): array {
  161. $table = static::$table;
  162. $items = static::query([], ["id_as_key" => true]);
  163. foreach($items as $id => $item) {
  164. static::$repositories[$table][$id] = $item;
  165. }
  166. return $items;
  167. }
  168. /**
  169. * @param array $nvp
  170. * @return int
  171. * @throws Exception
  172. */
  173. public static function deleteMultiple($nvp = []): int {
  174. $table = static::$table;
  175. $vs = "1";
  176. if(!empty($nvp)) {
  177. $nvp = static::getRemappedNVP($nvp);
  178. $vs = db::get_where_string($nvp);
  179. }
  180. $sql = "DELETE FROM `$table` WHERE $vs";
  181. $result = db::query($sql);
  182. if(!$result) return false;
  183. return db::affected_rows();
  184. }
  185. /**
  186. * @param string|array $nvp
  187. * @param array $options
  188. * @return static[]
  189. * @throws Exception
  190. */
  191. public static function query($nvp = [], $options = []): array {
  192. if(is_array($nvp)) {
  193. return static::findByNVP($nvp, $options);
  194. }
  195. else {
  196. return static::findByValueString($nvp, $options);
  197. }
  198. }
  199. /**
  200. * @param array $nvp
  201. * @param array $options
  202. * @return static[]
  203. * @throws Exception
  204. */
  205. public static function queryFuzzy($nvp = [], $options = []): array {
  206. $options["fuzzy"] = true;
  207. return static::findByNVP($nvp, $options);
  208. }
  209. /**
  210. * @param array $nvp
  211. * @param array $options
  212. * @return static|null
  213. * @throws Exception
  214. */
  215. public static function queryOne($nvp = [], $options = []): ?object {
  216. $rows = static::findByNVP($nvp, $options);
  217. return $rows ? $rows[0] : null;
  218. }
  219. /**
  220. * @param array $nvp
  221. * @return array
  222. */
  223. private static function getRemappedNVP($nvp = []): array {
  224. $mapped_nvp = [];
  225. foreach($nvp as $field => $value) {
  226. $field = static::$field_map[$field] ?? $field;
  227. $mapped_nvp[$field] = $value;
  228. }
  229. return $mapped_nvp;
  230. }
  231. /**
  232. * @param array $nvp
  233. * @return int
  234. * @throws Exception
  235. */
  236. public static function count($nvp = []): int {
  237. $table = static::$table;
  238. $vs = "1";
  239. if(!empty($nvp)) {
  240. $nvp = static::getRemappedNVP($nvp);
  241. $vs = db::get_where_string($nvp);
  242. }
  243. $sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
  244. $result = db::query($sql);
  245. $row = db::fetch_object($result);
  246. return $row->count;
  247. }
  248. /**
  249. * @param array $nvp
  250. * @param array $options
  251. * @return static[]
  252. * @throws Exception
  253. */
  254. public static function findByNVP(array $nvp, array $options = []): array {
  255. if(empty($nvp)) {
  256. $vs = "1";
  257. }
  258. else {
  259. $nvp = static::getRemappedNVP($nvp);
  260. $vs = db::get_where_string($nvp, $options);
  261. }
  262. return static::findByValueString($vs, $options);
  263. }
  264. /**
  265. * @param string $vs
  266. * @param array $options
  267. * @return static[]
  268. * @throws Exception
  269. */
  270. private static function findByValueString(string $vs, array $options = []): array {
  271. $table = static::$table;
  272. $options = (object) $options;
  273. $objects = [];
  274. $sql = "SELECT * FROM `$table` WHERE $vs";
  275. if(isset($options->sort)) {
  276. $sort = static::$field_map[$options->sort] ?? $options->sort;
  277. $sql .= " ORDER BY `$sort`";
  278. if(isset($options->order)) {
  279. $sql .= " " . strtoupper($options->order);
  280. }
  281. }
  282. if(isset($options->limit)) {
  283. $sql .= " LIMIT";
  284. if(isset($options->offset)) {
  285. $sql .= " $options->offset,";
  286. }
  287. $sql .= " $options->limit";
  288. }
  289. $result = db::query($sql);
  290. while($row = db::fetch_object($result)) {
  291. $objects[] = new static($row);
  292. }
  293. if(!empty($options->id_as_key)) {
  294. $objects = Util::arrayFlipByID($objects);
  295. }
  296. return $objects;
  297. }
  298. // Constructor
  299. public function __construct($model_data = null) {
  300. if(is_null($model_data)) {
  301. $model_data = (object) [];
  302. }
  303. if(is_array($model_data)) {
  304. $model_data = (object) $model_data;
  305. }
  306. $this->model_data = $model_data;
  307. $this->in_db = !is_null($this->getID());
  308. }
  309. // Object methods
  310. public final function isModified() {
  311. return !empty($this->modified_fields);
  312. }
  313. public final function getModifiedFields() {
  314. return $this->modified_fields;
  315. }
  316. private function preCommit() {
  317. }
  318. private final function getIDWhere() {
  319. $id_field = static::$id_field;
  320. $id = $this->getID();
  321. $nvp = [];
  322. if(is_array($id) && is_array($id_field)) {
  323. $nvp = array_combine($id_field, $id);
  324. }
  325. else {
  326. $nvp[$id_field] = $id;
  327. }
  328. $where = db::get_where_string($nvp, true);
  329. return $where;
  330. }
  331. /**
  332. * @param bool $testing
  333. * @return bool
  334. * @throws Exception
  335. */
  336. public final function commit($testing = false) {
  337. $this->preCommit();
  338. $id_field = static::$id_field;
  339. $table = static::$table;
  340. $blob_fields = static::$blob_fields;
  341. $nvp = [];
  342. foreach($this->modified_fields as $field) {
  343. if(in_array($field, $blob_fields)) {
  344. $nvp[$field] = "x'" . bin2hex($this->model_data->$field) . "'";
  345. }
  346. // NULL
  347. else if(is_null($this->model_data->$field)) {
  348. $nvp[$field] = null;
  349. }
  350. // Value
  351. else {
  352. $nvp[$field] = db::escape($this->model_data->$field);
  353. }
  354. }
  355. if(empty($nvp)) return true;
  356. $value_string = db::get_value_string($nvp);
  357. if($this->in_db) {
  358. // Update
  359. $where = $this->getIDWhere();
  360. $sql = "UPDATE `$table` SET $value_string WHERE $where";
  361. }
  362. else {
  363. // Insert
  364. $sql = "INSERT INTO `$table` SET $value_string";
  365. }
  366. if($testing == false) {
  367. $result = db::query($sql);
  368. if(empty($this->in_db) && $result) {
  369. // Set ID
  370. $insert_id = db::insert_id();
  371. if(!empty($insert_id)) {
  372. $this->$id_field = $insert_id;
  373. }
  374. $this->in_db = true;
  375. }
  376. }
  377. else {
  378. db::$last_query = $sql;
  379. $result = true;
  380. if(empty($this->in_db) && !is_array(static::$id_field)) {
  381. $this->$id_field = mt_rand(1, 32768);
  382. }
  383. $this->in_db = true;
  384. }
  385. if($result) {
  386. $this->modified_fields = [];
  387. }
  388. return !empty($result);
  389. }
  390. /**
  391. * @return bool
  392. * @throws Exception
  393. */
  394. public function testCommit() {
  395. return $this->commit(true);
  396. }
  397. /**
  398. * @param bool $testing
  399. * @return bool
  400. * @throws Exception
  401. */
  402. public final function commitOrException($testing = false) {
  403. $success = $this->commit($testing);
  404. if(!$success) throw new Exception("Database error.");
  405. return $success;
  406. }
  407. /**
  408. * @return bool
  409. * @throws Exception
  410. */
  411. public function delete() {
  412. $table = static::$table;
  413. $id = $this->getID();
  414. if(is_null($id)) return false;
  415. $where = $this->getIDWhere();
  416. $sql = "DELETE FROM `$table` WHERE $where";
  417. $result = db::query($sql);
  418. return empty($result) ? false : (db::affected_rows() ? true : false);
  419. }
  420. /**
  421. * @return bool
  422. * @throws Exception
  423. */
  424. public final function deleteOrException() {
  425. $success = $this->delete();
  426. if(!$success) throw new Exception("Database error.");
  427. return $success;
  428. }
  429. public final function getID() {
  430. $id_field = static::$id_field;
  431. if(is_array($id_field)) {
  432. $values = [];
  433. $fields = $id_field;
  434. foreach($fields as $field) {
  435. $value = $this->model_data->$field ?? null;
  436. if(is_null($value)) return null;
  437. $values[] = $this->model_data->$field;
  438. }
  439. return $values;
  440. }
  441. else {
  442. return $this->model_data->$id_field ?? null;
  443. }
  444. }
  445. public final function getModelData() {
  446. return clone $this->model_data;
  447. }
  448. }