1
0

model.php 11 KB

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