1
0

Model.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. * @param ...$id_parts
  136. * @return static
  137. * @throws Exception
  138. */
  139. public static function require(...$id_parts): object {
  140. $row = static::get(...$id_parts);
  141. if(!$row) {
  142. $name = ucwords(str_replace("_", " ", static::$table));
  143. throw new RuntimeException(__("%s not found.", $name));
  144. }
  145. return $row;
  146. }
  147. /**
  148. * @return static[]
  149. * @throws Exception
  150. */
  151. public static function getAll(): array {
  152. $class = static::class;
  153. $objects = [];
  154. $table = static::$table;
  155. $sql = "SELECT * FROM `$table`";
  156. $result = Database::query($sql);
  157. while($row = Database::fetchObject($result)) {
  158. $objects[] = self::instantiateRow($class, $row);
  159. }
  160. return $objects;
  161. }
  162. /**
  163. * @param array ...$id_sets
  164. * @return static[]
  165. * @throws Exception
  166. */
  167. public static function load(...$id_sets): array {
  168. $table = static::$table;
  169. $ids = [];
  170. if($id_sets) {
  171. $ids = array_merge(...$id_sets);
  172. }
  173. if(empty($ids)) {
  174. return [];
  175. }
  176. $ids = array_unique($ids);
  177. $items = static::query([static::$idField => $ids], ["id_as_key" => true]);
  178. if(self::$repositoriesEnabled) {
  179. foreach($items as $id => $item) {
  180. self::$repositories[$table][$id] = $item;
  181. }
  182. }
  183. return $items;
  184. }
  185. /**
  186. * @param array $nvp
  187. * @return int
  188. * @throws Exception
  189. */
  190. public static function deleteMultiple(array $nvp = []): int {
  191. $table = static::$table;
  192. $vs = "1";
  193. if(!empty($nvp)) {
  194. $nvp = static::getRemappedNVP($nvp);
  195. $vs = Database::getWhereString($nvp);
  196. }
  197. $sql = "DELETE FROM `$table` WHERE $vs";
  198. $result = Database::query($sql);
  199. if(!$result) {
  200. return false;
  201. }
  202. return Database::affectedRows();
  203. }
  204. /**
  205. * @param array|string $nvp
  206. * @param array $options
  207. * @return static[]
  208. */
  209. public static function query($nvp = [], array $options = []): array {
  210. try {
  211. return is_array($nvp) ? static::findByNVP($nvp, $options) : static::findByValueString($nvp, $options);
  212. }
  213. catch(Exception $e) {
  214. return [];
  215. }
  216. }
  217. /**
  218. * @param array $nvp
  219. * @param array $options
  220. * @return static[]
  221. * @throws Exception
  222. */
  223. public static function queryFuzzy(array $nvp = [], array $options = []): array {
  224. $options["fuzzy"] = true;
  225. return static::findByNVP($nvp, $options);
  226. }
  227. /**
  228. * @param array|string $nvp
  229. * @param array $options
  230. * @return static|null
  231. * @throws Exception
  232. */
  233. public static function queryOne($nvp = [], array $options = []): ?object {
  234. $options = array_merge($options, ["limit" => 1]);
  235. if(is_array($nvp)) {
  236. $rows = static::findByNVP($nvp, $options);
  237. }
  238. else {
  239. $rows = static::findByValueString($nvp, $options);
  240. }
  241. return $rows ? $rows[0] : null;
  242. }
  243. /**
  244. * @param array $nvp
  245. * @return array
  246. */
  247. private static function getRemappedNVP(array $nvp = []): array {
  248. $mapped_nvp = [];
  249. foreach($nvp as $field => $value) {
  250. $field = static::$fieldMap[$field] ?? $field;
  251. $mapped_nvp[$field] = $value;
  252. }
  253. return $mapped_nvp;
  254. }
  255. /**
  256. * @param array $nvp
  257. * @return int
  258. * @throws Exception
  259. */
  260. public static function count(array $nvp = []): int {
  261. $table = static::$table;
  262. if(is_array($nvp)) {
  263. $vs = "1";
  264. if(!empty($nvp)) {
  265. $nvp = static::getRemappedNVP($nvp);
  266. $vs = Database::getWhereString($nvp);
  267. }
  268. }
  269. else {
  270. $vs = $nvp;
  271. }
  272. $sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
  273. $result = Database::query($sql);
  274. return Database::fetchObject($result)->count;
  275. }
  276. /**
  277. * @param $nvp
  278. * @param array $options
  279. * @return static[]
  280. * @throws Exception
  281. */
  282. public static function findByNVP($nvp, array $options = []): array {
  283. if(empty($nvp)) {
  284. $vs = "1";
  285. }
  286. else {
  287. $nvp = static::getRemappedNVP($nvp);
  288. $vs = Database::getWhereString($nvp, $options);
  289. }
  290. return static::findByValueString($vs, $options);
  291. }
  292. /**
  293. * @param string $vs
  294. * @param array $opts
  295. * @return static[]
  296. * @throws Exception
  297. */
  298. private static function findByValueString(string $vs, array $opts = []): array {
  299. $class = static::class;
  300. $table = static::$table;
  301. $options = (object) $opts;
  302. $objects = [];
  303. $sql = "SELECT * FROM `$table` WHERE $vs";
  304. if(isset($options->sort)) {
  305. if(is_array($options->sort)) {
  306. $sql .= " ORDER BY ";
  307. $order_bys = [];
  308. foreach($options->sort as $index => $field) {
  309. $field = static::$fieldMap[$field] ?? $field;
  310. $order = $options->order[$index] ?? "asc";
  311. $order_bys[] = "`$field` $order";
  312. }
  313. $sql .= implode(", ", $order_bys);
  314. }
  315. else {
  316. $sort = static::$fieldMap[$options->sort] ?? $options->sort;
  317. $sql .= " ORDER BY `$sort`";
  318. if(isset($options->order)) {
  319. $sql .= " " . strtoupper($options->order);
  320. }
  321. }
  322. }
  323. if(isset($options->limit)) {
  324. $sql .= " LIMIT";
  325. if(isset($options->offset)) {
  326. $sql .= " $options->offset,";
  327. }
  328. $sql .= " $options->limit";
  329. }
  330. $result = Database::query($sql);
  331. while($row = Database::fetchObject($result)) {
  332. $objects[] = self::instantiateRow($class, $row);
  333. }
  334. if(!empty($options->id_as_key)) {
  335. $objects = self::arrayFlipById($objects);
  336. }
  337. return $objects;
  338. }
  339. /**
  340. * @param string $class
  341. * @param object $row
  342. * @return object
  343. * @throws Exception
  344. */
  345. protected static function instantiateRow(string $class, object $row): object {
  346. $reflection = new ReflectionClass($class);
  347. $is_instantiable = $reflection->isInstantiable();
  348. if($is_instantiable) {
  349. return new $class($row);
  350. }
  351. if($reflection->hasMethod("instantiate")) {
  352. /** @noinspection PhpUndefinedMethodInspection */
  353. return $class::instantiate($row);
  354. }
  355. throw new RuntimeException(__("$class is not instantiable and no instantiate() function exists."));
  356. }
  357. /**
  358. * @param Model[] $objects
  359. * @return array
  360. */
  361. public static function arrayFlipById(array $objects): array {
  362. $array = [];
  363. foreach($objects as $object) {
  364. $id = $object->getId();
  365. $array[$id] = $object;
  366. }
  367. return $array;
  368. }
  369. // Constructor
  370. public function __construct($model_data = null) {
  371. if($model_data === null) {
  372. $model_data = (object) [];
  373. }
  374. if(is_array($model_data)) {
  375. $model_data = (object) $model_data;
  376. }
  377. $this->modelData = $model_data;
  378. $this->inDatabase = $this->getId() !== null;
  379. }
  380. // Object methods
  381. final public function isNew(): bool {
  382. return empty($this->inDatabase);
  383. }
  384. final public function isModified(): bool {
  385. return !empty($this->modifiedFields);
  386. }
  387. final public function getModifiedFields(): array {
  388. return $this->modifiedFields;
  389. }
  390. private function getIdWhere(): string {
  391. $id_field = static::$idField;
  392. $id = $this->getId();
  393. $nvp = [];
  394. if(is_array($id)) {
  395. /**
  396. * @var array $id_field
  397. */
  398. $nvp = array_combine($id_field, $id);
  399. }
  400. else {
  401. $nvp[$id_field] = $id;
  402. }
  403. return Database::getWhereString($nvp, true);
  404. }
  405. /**
  406. * Commits changes to a model to the database
  407. *
  408. * @param array $options Optional array containing one or more of the following keys:
  409. * <ul>
  410. * <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>
  411. * <li><b>suppress_exception</b>: If <i>true</i>, an exception will not be thrown if the query fails</li>
  412. * </ul>
  413. * @return bool
  414. * @throws Exception Thrown on query failure
  415. */
  416. public function commit(array $options = []) : bool {
  417. // Options
  418. $testing = $options[self::COMMIT_TESTING] ?? false;
  419. $insert_ignore = $options[self::COMMIT_INSERT_IGNORE] ?? false;
  420. $suppress_exception = $options[self::COMMIT_SUPPRESS_EXCEPTION] ?? false;
  421. $id_field = static::$idField;
  422. $table = static::$table;
  423. $blob_fields = static::$blobFields;
  424. $nvp = [];
  425. foreach($this->modifiedFields as $field) {
  426. if(in_array($field, $blob_fields, true)) {
  427. $nvp[$field] = "x'" . bin2hex($this->modelData->$field) . "'";
  428. }
  429. // NULL
  430. else if($this->modelData->$field === null) {
  431. $nvp[$field] = null;
  432. }
  433. // Value
  434. else {
  435. $nvp[$field] = Database::escape($this->modelData->$field);
  436. }
  437. }
  438. if(empty($nvp)) {
  439. return true;
  440. }
  441. $value_string = Database::getValueString($nvp);
  442. if($this->inDatabase) {
  443. // Update
  444. $where = $this->getIdWhere();
  445. $sql = "UPDATE `$table` SET $value_string WHERE $where";
  446. }
  447. else if($insert_ignore) {
  448. $sql = "INSERT IGNORE INTO `$table` SET $value_string";
  449. }
  450. else {
  451. $sql = "INSERT INTO `$table` SET $value_string";
  452. }
  453. if($testing === false) {
  454. $result = Database::query($sql);
  455. if(empty($this->inDatabase) && $result) {
  456. // Set ID
  457. $insert_id = Database::insertId();
  458. if(!empty($insert_id)) {
  459. $this->$id_field = $insert_id;
  460. }
  461. $this->inDatabase = true;
  462. }
  463. }
  464. else {
  465. Database::$lastQuery = $sql;
  466. $result = true;
  467. if(empty($this->inDatabase) && !is_array(static::$idField)) {
  468. $this->$id_field = random_int(1, 32768);
  469. }
  470. $this->inDatabase = true;
  471. }
  472. if(!$result && !$suppress_exception) {
  473. throw new RuntimeException("An unexpected error has occurred. Please try again.");
  474. }
  475. return !empty($result);
  476. }
  477. /**
  478. * Deletes a model from the database
  479. *
  480. * @param array $options Optional array containing the following key:
  481. * * `suppress_exception`: If `true`, an exception will not be thrown if the query fails
  482. *
  483. * @return bool
  484. * @throws Exception Thrown on query failure
  485. */
  486. public function delete(array $options = []): bool {
  487. // Options
  488. $suppress_exception = $options[self::COMMIT_SUPPRESS_EXCEPTION] ?? false;
  489. $table = static::$table;
  490. $id = $this->getId();
  491. if($id === null) {
  492. return false;
  493. }
  494. $where = $this->getIdWhere();
  495. $sql = "DELETE FROM `$table` WHERE $where";
  496. $result = Database::query($sql);
  497. if(!$result && !$suppress_exception) {
  498. throw new RuntimeException("An unexpected error has occurred. Please try again.");
  499. }
  500. if(!$result) {
  501. return false;
  502. }
  503. return (bool) Database::affectedRows();
  504. }
  505. /**
  506. * @return array|int|null
  507. */
  508. final public function getId() {
  509. $id_field = static::$idField;
  510. if(is_array($id_field)) {
  511. $values = [];
  512. $fields = $id_field;
  513. foreach($fields as $field) {
  514. $value = $this->modelData->$field ?? null;
  515. if($value === null) {
  516. return null;
  517. }
  518. $values[] = $this->modelData->$field;
  519. }
  520. return $values;
  521. }
  522. return $this->modelData->$id_field ?? null;
  523. }
  524. final public function getIdString(): string {
  525. $id = $this->getId();
  526. return is_array($id) ? implode("-", $id) : (string) $id;
  527. }
  528. final public function getModelData(): ?object {
  529. return clone $this->modelData;
  530. }
  531. final public function getTable(): string {
  532. return static::$table;
  533. }
  534. /**
  535. * @param Model|string $id_or_obj
  536. * @return bool
  537. */
  538. final public function is($id_or_obj): bool {
  539. $id_string = $this->getIdString();
  540. if(is_string($id_or_obj)) {
  541. return $id_string === $id_or_obj;
  542. }
  543. $model = $id_or_obj;
  544. if($model->getTable() !== $this->getTable()) {
  545. return false;
  546. }
  547. return ($id_string === $id_or_obj->getIdString());
  548. }
  549. }