1
0

Model.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. <?php
  2. namespace App;
  3. use Exception;
  4. use ReflectionClass;
  5. use RuntimeException;
  6. abstract class Model {
  7. // Query Option Keys
  8. public const OPTION_SORT = "sort";
  9. public const OPTION_ORDER = "order";
  10. public const OPTION_LIMIT = "limit";
  11. public const OPTION_OFFSET = "offset";
  12. public const OPTION_ID_AS_KEY = "id_as_key";
  13. public const COMMIT_TESTING = "testing";
  14. public const COMMIT_INSERT_IGNORE = "insert_ignore";
  15. public const COMMIT_SUPPRESS_EXCEPTION = "suppress_exception";
  16. protected static $table = "";
  17. protected static $idField = "";
  18. protected static $fillableFields = [];
  19. protected static $enforceFieldCheck = true;
  20. protected static $fieldMap = []; // Used for field name aliases
  21. protected static $blobFields = [];
  22. protected static $repositoriesEnabled = true;
  23. protected static $repositories = [];
  24. // Object variables
  25. protected $modelData;
  26. protected $modifiedFields = [];
  27. protected $inDatabase;
  28. // Magic methods
  29. public function getMappedFieldName(string $name): string {
  30. if(isset(static::$fieldMap[$name])) {
  31. $name = static::$fieldMap[$name];
  32. }
  33. return $name;
  34. }
  35. /**
  36. * @param string $name
  37. * @return mixed|null
  38. */
  39. public function __get(string $name) {
  40. $name = $this->getMappedFieldName($name);
  41. return $this->modelData->$name ?? null;
  42. }
  43. /**
  44. * @param string $name
  45. * @param $value
  46. * @throws Exception
  47. */
  48. public function __set(string $name, $value) {
  49. $name = $this->getMappedFieldName($name);
  50. $id_field = static::$idField;
  51. if($name === "model_data") {
  52. $this->modelData = $value;
  53. }
  54. else if(in_array($name, static::$fillableFields, true)) {
  55. if($value !== null) {
  56. if(is_scalar($value) || is_object($value)) {
  57. $value = (string) $value;
  58. }
  59. if(is_array($value)) {
  60. $value = json_encode($value);
  61. }
  62. }
  63. $old_value = $this->modelData->$name ?? null;
  64. if($old_value !== $value) {
  65. $this->modelData->$name = $value;
  66. $this->modifiedFields[] = $name;
  67. }
  68. }
  69. else if($name === $id_field && empty($this->modelData->$id_field)) {
  70. $this->modelData->$id_field = $value;
  71. }
  72. else if(static::$enforceFieldCheck) {
  73. throw new RuntimeException("Attempt to set an unfillable field $name");
  74. }
  75. else {
  76. $this->modelData->$name = $value;
  77. }
  78. }
  79. public function __isset($name) {
  80. $name = static::$fieldMap[$name] ?? $name;
  81. return isset($this->modelData->$name);
  82. }
  83. // Static methods
  84. public static function setRepositoriesEnabled(bool $enabled): void {
  85. self::$repositoriesEnabled = $enabled;
  86. }
  87. public static function clearRepositories(): void {
  88. self::$repositories = [];
  89. }
  90. public static function clearRepository(string $table): void {
  91. self::$repositories[$table] = [];
  92. }
  93. /**
  94. * @param $id
  95. * @return static|null
  96. * @throws Exception
  97. */
  98. public static function get($id): ?object {
  99. $table = static::$table;
  100. $is_compound_key = is_array(static::$idField);
  101. $repositories_enabled = static::$repositoriesEnabled;
  102. // Check repo for item
  103. if(!$is_compound_key && isset(self::$repositories[$table][$id]) && $repositories_enabled) {
  104. return self::$repositories[$table][$id];
  105. }
  106. $id_field = static::$idField;
  107. $class = static::class;
  108. $nvp = [];
  109. if($is_compound_key && is_array($id_field)) { // Compound key
  110. $args = func_get_args();
  111. $fields = $id_field;
  112. if(count($args) !== count($fields)) {
  113. throw new RuntimeException(__("Number of arguments in get() method call does not match with $class definition."));
  114. }
  115. foreach($fields as $index => $field) {
  116. $nvp[$field] = $args[$index];
  117. }
  118. }
  119. else {
  120. $nvp[$id_field] = $id;
  121. }
  122. $where = Database::getWhereString($nvp, true);
  123. $sql = "SELECT * FROM `$table` WHERE $where";
  124. $result = Database::query($sql);
  125. $object = Database::objectOrNull($result);
  126. if($object) {
  127. $object = self::instantiateRow($class, $object);
  128. if(!$is_compound_key && self::$repositoriesEnabled) {
  129. self::$repositories[$table][$id] = $object;
  130. }
  131. }
  132. return $object;
  133. }
  134. /**
  135. * @return static[]
  136. * @throws Exception
  137. */
  138. public static function getAll(): array {
  139. $class = static::class;
  140. $objects = [];
  141. $table = static::$table;
  142. $sql = "SELECT * FROM `$table`";
  143. $result = Database::query($sql);
  144. while($row = Database::fetchObject($result)) {
  145. $objects[] = self::instantiateRow($class, $row);
  146. }
  147. return $objects;
  148. }
  149. /**
  150. * @param array ...$id_sets
  151. * @return static[]
  152. * @throws Exception
  153. */
  154. public static function load(...$id_sets): array {
  155. $table = static::$table;
  156. $ids = [];
  157. if($id_sets) {
  158. $ids = array_merge(...$id_sets);
  159. }
  160. if(empty($ids)) {
  161. return [];
  162. }
  163. $ids = array_unique($ids);
  164. $items = static::query([static::$idField => $ids], ["id_as_key" => true]);
  165. if(self::$repositoriesEnabled) {
  166. foreach($items as $id => $item) {
  167. self::$repositories[$table][$id] = $item;
  168. }
  169. }
  170. return $items;
  171. }
  172. /**
  173. * @param array $nvp
  174. * @return int
  175. * @throws Exception
  176. */
  177. public static function deleteMultiple(array $nvp = []): int {
  178. $table = static::$table;
  179. $vs = "1";
  180. if(!empty($nvp)) {
  181. $nvp = static::getRemappedNVP($nvp);
  182. $vs = Database::getWhereString($nvp);
  183. }
  184. $sql = "DELETE FROM `$table` WHERE $vs";
  185. $result = Database::query($sql);
  186. if(!$result) {
  187. return false;
  188. }
  189. return Database::affectedRows();
  190. }
  191. /**
  192. * @param array|string $nvp
  193. * @param array $options
  194. * @return static[]
  195. */
  196. public static function query($nvp = [], array $options = []): array {
  197. try {
  198. return is_array($nvp) ? static::findByNVP($nvp, $options) : static::findByValueString($nvp, $options);
  199. }
  200. catch(Exception $e) {
  201. return [];
  202. }
  203. }
  204. /**
  205. * @param array $nvp
  206. * @param array $options
  207. * @return static[]
  208. * @throws Exception
  209. */
  210. public static function queryFuzzy(array $nvp = [], array $options = []): array {
  211. $options["fuzzy"] = true;
  212. return static::findByNVP($nvp, $options);
  213. }
  214. /**
  215. * @param array|string $nvp
  216. * @param array $options
  217. * @return static|null
  218. * @throws Exception
  219. */
  220. public static function queryOne($nvp = [], array $options = []): ?object {
  221. $options = array_merge($options, ["limit" => 1]);
  222. if(is_array($nvp)) {
  223. $rows = static::findByNVP($nvp, $options);
  224. }
  225. else {
  226. $rows = static::findByValueString($nvp, $options);
  227. }
  228. return $rows ? $rows[0] : null;
  229. }
  230. /**
  231. * @param array $nvp
  232. * @return array
  233. */
  234. private static function getRemappedNVP(array $nvp = []): array {
  235. $mapped_nvp = [];
  236. foreach($nvp as $field => $value) {
  237. $field = static::$fieldMap[$field] ?? $field;
  238. $mapped_nvp[$field] = $value;
  239. }
  240. return $mapped_nvp;
  241. }
  242. /**
  243. * @param array $nvp
  244. * @return int
  245. * @throws Exception
  246. */
  247. public static function count(array $nvp = []): int {
  248. $table = static::$table;
  249. if(is_array($nvp)) {
  250. $vs = "1";
  251. if(!empty($nvp)) {
  252. $nvp = static::getRemappedNVP($nvp);
  253. $vs = Database::getWhereString($nvp);
  254. }
  255. }
  256. else {
  257. $vs = $nvp;
  258. }
  259. $sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
  260. $result = Database::query($sql);
  261. return Database::fetchObject($result)->count;
  262. }
  263. /**
  264. * @param $nvp
  265. * @param array $options
  266. * @return static[]
  267. * @throws Exception
  268. */
  269. public static function findByNVP($nvp, array $options = []): array {
  270. if(empty($nvp)) {
  271. $vs = "1";
  272. }
  273. else {
  274. $nvp = static::getRemappedNVP($nvp);
  275. $vs = Database::getWhereString($nvp, $options);
  276. }
  277. return static::findByValueString($vs, $options);
  278. }
  279. /**
  280. * @param string $vs
  281. * @param array $opts
  282. * @return static[]
  283. * @throws Exception
  284. */
  285. private static function findByValueString(string $vs, array $opts = []): array {
  286. $class = static::class;
  287. $table = static::$table;
  288. $options = (object) $opts;
  289. $objects = [];
  290. $sql = "SELECT * FROM `$table` WHERE $vs";
  291. if(isset($options->sort)) {
  292. if(is_array($options->sort)) {
  293. $sql .= " ORDER BY ";
  294. $order_bys = [];
  295. foreach($options->sort as $index => $field) {
  296. $field = static::$fieldMap[$field] ?? $field;
  297. $order = $options->order[$index] ?? "asc";
  298. $order_bys[] = "`$field` $order";
  299. }
  300. $sql .= implode(", ", $order_bys);
  301. }
  302. else {
  303. $sort = static::$fieldMap[$options->sort] ?? $options->sort;
  304. $sql .= " ORDER BY `$sort`";
  305. if(isset($options->order)) {
  306. $sql .= " " . strtoupper($options->order);
  307. }
  308. }
  309. }
  310. if(isset($options->limit)) {
  311. $sql .= " LIMIT";
  312. if(isset($options->offset)) {
  313. $sql .= " $options->offset,";
  314. }
  315. $sql .= " $options->limit";
  316. }
  317. $result = Database::query($sql);
  318. while($row = Database::fetchObject($result)) {
  319. $objects[] = self::instantiateRow($class, $row);
  320. }
  321. if(!empty($options->id_as_key)) {
  322. $objects = self::arrayFlipById($objects);
  323. }
  324. return $objects;
  325. }
  326. /**
  327. * @param string $class
  328. * @param object $row
  329. * @return object
  330. * @throws Exception
  331. */
  332. protected static function instantiateRow(string $class, object $row): object {
  333. $reflection = new ReflectionClass($class);
  334. $is_instantiable = $reflection->isInstantiable();
  335. if($is_instantiable) {
  336. return new $class($row);
  337. }
  338. if($reflection->hasMethod("instantiate")) {
  339. /** @noinspection PhpUndefinedMethodInspection */
  340. return $class::instantiate($row);
  341. }
  342. throw new RuntimeException(__("$class is not instantiable and no instantiate() function exists."));
  343. }
  344. /**
  345. * @param Model[] $objects
  346. * @return array
  347. */
  348. public static function arrayFlipById(array $objects): array {
  349. $array = [];
  350. foreach($objects as $object) {
  351. $id = $object->getId();
  352. $array[$id] = $object;
  353. }
  354. return $array;
  355. }
  356. // Constructor
  357. public function __construct($model_data = null) {
  358. if($model_data === null) {
  359. $model_data = (object) [];
  360. }
  361. if(is_array($model_data)) {
  362. $model_data = (object) $model_data;
  363. }
  364. $this->modelData = $model_data;
  365. $this->inDatabase = $this->getId() !== null;
  366. }
  367. // Object methods
  368. final public function isNew(): bool {
  369. return empty($this->inDatabase);
  370. }
  371. final public function isModified(): bool {
  372. return !empty($this->modifiedFields);
  373. }
  374. final public function getModifiedFields(): array {
  375. return $this->modifiedFields;
  376. }
  377. private function getIdWhere(): string {
  378. $id_field = static::$idField;
  379. $id = $this->getId();
  380. $nvp = [];
  381. if(is_array($id)) {
  382. /**
  383. * @var array $id_field
  384. */
  385. $nvp = array_combine($id_field, $id);
  386. }
  387. else {
  388. $nvp[$id_field] = $id;
  389. }
  390. return Database::getWhereString($nvp, true);
  391. }
  392. /**
  393. * Commits changes to a model to the database
  394. *
  395. * @param array $options Optional array containing one or more of the following keys:
  396. * <ul>
  397. * <li><b>testing</b>: If <i>true</i>, the changes will not be written to the database. If the object is not in the database, it will be assigned a random ID will be generated in the range of 1-32768</li>
  398. * <li><b>suppress_exception</b>: If <i>true</i>, an exception will not be thrown if the query fails</li>
  399. * </ul>
  400. * @return bool
  401. * @throws Exception Thrown on query failure
  402. */
  403. public function commit(array $options = []) : bool {
  404. // Options
  405. $testing = $options[self::COMMIT_TESTING] ?? false;
  406. $insert_ignore = $options[self::COMMIT_INSERT_IGNORE] ?? false;
  407. $suppress_exception = $options[self::COMMIT_SUPPRESS_EXCEPTION] ?? false;
  408. $id_field = static::$idField;
  409. $table = static::$table;
  410. $blob_fields = static::$blobFields;
  411. $nvp = [];
  412. foreach($this->modifiedFields as $field) {
  413. if(in_array($field, $blob_fields, true)) {
  414. $nvp[$field] = "x'" . bin2hex($this->modelData->$field) . "'";
  415. }
  416. // NULL
  417. else if($this->modelData->$field === null) {
  418. $nvp[$field] = null;
  419. }
  420. // Value
  421. else {
  422. $nvp[$field] = Database::escape($this->modelData->$field);
  423. }
  424. }
  425. if(empty($nvp)) {
  426. return true;
  427. }
  428. $value_string = Database::getValueString($nvp);
  429. if($this->inDatabase) {
  430. // Update
  431. $where = $this->getIdWhere();
  432. $sql = "UPDATE `$table` SET $value_string WHERE $where";
  433. }
  434. else if($insert_ignore) {
  435. $sql = "INSERT IGNORE INTO `$table` SET $value_string";
  436. }
  437. else {
  438. $sql = "INSERT INTO `$table` SET $value_string";
  439. }
  440. if($testing === false) {
  441. $result = Database::query($sql);
  442. if(empty($this->inDatabase) && $result) {
  443. // Set ID
  444. $insert_id = Database::insertId();
  445. if(!empty($insert_id)) {
  446. $this->$id_field = $insert_id;
  447. }
  448. $this->inDatabase = true;
  449. }
  450. }
  451. else {
  452. Database::$lastQuery = $sql;
  453. $result = true;
  454. if(empty($this->inDatabase) && !is_array(static::$idField)) {
  455. $this->$id_field = random_int(1, 32768);
  456. }
  457. $this->inDatabase = true;
  458. }
  459. if(!$result && !$suppress_exception) {
  460. throw new RuntimeException("An unexpected error has occurred. Please try again.");
  461. }
  462. return !empty($result);
  463. }
  464. /**
  465. * Deletes a model from the database
  466. *
  467. * @param array $options Optional array containing the following key:
  468. * * `suppress_exception`: If `true`, an exception will not be thrown if the query fails
  469. *
  470. * @return bool
  471. * @throws Exception Thrown on query failure
  472. */
  473. public function delete(array $options = []): bool {
  474. // Options
  475. $suppress_exception = $options[self::COMMIT_SUPPRESS_EXCEPTION] ?? false;
  476. $table = static::$table;
  477. $id = $this->getId();
  478. if($id === null) {
  479. return false;
  480. }
  481. $where = $this->getIdWhere();
  482. $sql = "DELETE FROM `$table` WHERE $where";
  483. $result = Database::query($sql);
  484. if(!$result && !$suppress_exception) {
  485. throw new RuntimeException("An unexpected error has occurred. Please try again.");
  486. }
  487. if(!$result) {
  488. return false;
  489. }
  490. return (bool) Database::affectedRows();
  491. }
  492. /**
  493. * @return array|int|null
  494. */
  495. final public function getId() {
  496. $id_field = static::$idField;
  497. if(is_array($id_field)) {
  498. $values = [];
  499. $fields = $id_field;
  500. foreach($fields as $field) {
  501. $value = $this->modelData->$field ?? null;
  502. if($value === null) {
  503. return null;
  504. }
  505. $values[] = $this->modelData->$field;
  506. }
  507. return $values;
  508. }
  509. return $this->modelData->$id_field ?? null;
  510. }
  511. final public function getIdString(): string {
  512. $id = $this->getId();
  513. return is_array($id) ? implode("-", $id) : (string) $id;
  514. }
  515. final public function getModelData(): ?object {
  516. return clone $this->modelData;
  517. }
  518. /**
  519. * @param Model|string $id_or_obj
  520. * @return bool
  521. */
  522. final public function is($id_or_obj): bool {
  523. $id_string = $this->getIdString();
  524. if(is_string($id_or_obj)) {
  525. return $id_string === $id_or_obj;
  526. }
  527. return ($id_string === $id_or_obj->getIdString());
  528. }
  529. }