| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672 |
- <?php
- namespace App;
- use Exception;
- use ReflectionClass;
- use RuntimeException;
- abstract class Model {
- // Query Option Keys
- public const OPTION_SORT = "sort";
- public const OPTION_ORDER = "order";
- public const OPTION_LIMIT = "limit";
- public const OPTION_OFFSET = "offset";
- public const OPTION_ID_AS_KEY = "id_as_key";
- public const COMMIT_TESTING = "testing";
- public const COMMIT_INSERT_IGNORE = "insert_ignore";
- public const COMMIT_SUPPRESS_EXCEPTION = "suppress_exception";
- protected static $table = "";
- protected static $idField = "";
- protected static $fillableFields = [];
- protected static $enforceFieldCheck = true;
- protected static $fieldMap = []; // Used for field name aliases
- protected static $blobFields = [];
- protected static $repositoriesEnabled = true;
- protected static $repositories = [];
- // Object variables
- protected $modelData;
- protected $modifiedFields = [];
- protected $inDatabase;
- // Magic methods
- public function getMappedFieldName(string $name): string {
- if(isset(static::$fieldMap[$name])) {
- $name = static::$fieldMap[$name];
- }
- return $name;
- }
- /**
- * @param string $name
- * @return mixed|null
- */
- public function __get(string $name) {
- $name = $this->getMappedFieldName($name);
- return $this->modelData->$name ?? null;
- }
- /**
- * @param string $name
- * @param $value
- * @throws Exception
- */
- public function __set(string $name, $value) {
- $name = $this->getMappedFieldName($name);
- $id_field = static::$idField;
- if($name === "model_data") {
- $this->modelData = $value;
- }
- else if(in_array($name, static::$fillableFields, true)) {
- if($value !== null) {
- if(is_scalar($value) || is_object($value)) {
- $value = (string) $value;
- }
- if(is_array($value)) {
- $value = json_encode($value);
- }
- }
- $old_value = $this->modelData->$name ?? null;
- if($old_value !== $value) {
- $this->modelData->$name = $value;
- $this->modifiedFields[] = $name;
- }
- }
- else if($name === $id_field && empty($this->modelData->$id_field)) {
- $this->modelData->$id_field = $value;
- }
- else if(static::$enforceFieldCheck) {
- throw new RuntimeException("Attempt to set an unfillable field $name");
- }
- else {
- $this->modelData->$name = $value;
- }
- }
- public function __isset($name) {
- $name = static::$fieldMap[$name] ?? $name;
- return isset($this->modelData->$name);
- }
- // Static methods
- public static function setRepositoriesEnabled(bool $enabled): void {
- self::$repositoriesEnabled = $enabled;
- }
- public static function clearRepositories(): void {
- self::$repositories = [];
- }
- public static function clearRepository(string $table): void {
- self::$repositories[$table] = [];
- }
- /**
- * @param $id
- * @return static|null
- * @throws Exception
- */
- public static function get($id): ?object {
- $table = static::$table;
- $is_compound_key = is_array(static::$idField);
- $repositories_enabled = static::$repositoriesEnabled;
- // Check repo for item
- if(!$is_compound_key && isset(self::$repositories[$table][$id]) && $repositories_enabled) {
- return self::$repositories[$table][$id];
- }
- $id_field = static::$idField;
- $class = static::class;
- $nvp = [];
- if($is_compound_key && is_array($id_field)) { // Compound key
- $args = func_get_args();
- $fields = $id_field;
- if(count($args) !== count($fields)) {
- throw new RuntimeException(__("Number of arguments in get() method call does not match with $class definition."));
- }
- foreach($fields as $index => $field) {
- $nvp[$field] = $args[$index];
- }
- }
- else {
- $nvp[$id_field] = $id;
- }
- $where = Database::getWhereString($nvp, true);
- $sql = "SELECT * FROM `$table` WHERE $where";
- $result = Database::query($sql);
- $object = Database::objectOrNull($result);
- if($object) {
- $object = self::instantiateRow($class, $object);
- if(!$is_compound_key && self::$repositoriesEnabled) {
- self::$repositories[$table][$id] = $object;
- }
- }
- return $object;
- }
- /**
- * @param ...$id_parts
- * @return static
- * @throws Exception
- */
- public static function require(...$id_parts): object {
- $row = static::get(...$id_parts);
- if(!$row) {
- $name = ucwords(str_replace("_", " ", static::$table));
- throw new RuntimeException(__("%s not found.", $name));
- }
- return $row;
- }
- /**
- * @return static[]
- * @throws Exception
- */
- public static function getAll(): array {
- $class = static::class;
- $objects = [];
- $table = static::$table;
- $sql = "SELECT * FROM `$table`";
- $result = Database::query($sql);
- while($row = Database::fetchObject($result)) {
- $objects[] = self::instantiateRow($class, $row);
- }
- return $objects;
- }
- /**
- * @param array ...$id_sets
- * @return static[]
- * @throws Exception
- */
- public static function load(...$id_sets): array {
- $table = static::$table;
- $ids = [];
- if($id_sets) {
- $ids = array_merge(...$id_sets);
- }
- if(empty($ids)) {
- return [];
- }
- $ids = array_unique($ids);
- $items = static::query([static::$idField => $ids], ["id_as_key" => true]);
- if(self::$repositoriesEnabled) {
- foreach($items as $id => $item) {
- self::$repositories[$table][$id] = $item;
- }
- }
- return $items;
- }
- /**
- * @param array $nvp
- * @return int
- * @throws Exception
- */
- public static function deleteMultiple(array $nvp = []): int {
- $table = static::$table;
- $vs = "1";
- if(!empty($nvp)) {
- $nvp = static::getRemappedNVP($nvp);
- $vs = Database::getWhereString($nvp);
- }
- $sql = "DELETE FROM `$table` WHERE $vs";
- $result = Database::query($sql);
- if(!$result) {
- return false;
- }
- return Database::affectedRows();
- }
- /**
- * @param array|string $nvp
- * @param array $options
- * @return static[]
- */
- public static function query($nvp = [], array $options = []): array {
- try {
- return is_array($nvp) ? static::findByNVP($nvp, $options) : static::findByValueString($nvp, $options);
- }
- catch(Exception $e) {
- return [];
- }
- }
- /**
- * @param array $nvp
- * @param array $options
- * @return static[]
- * @throws Exception
- */
- public static function queryFuzzy(array $nvp = [], array $options = []): array {
- $options["fuzzy"] = true;
- return static::findByNVP($nvp, $options);
- }
- /**
- * @param array|string $nvp
- * @param array $options
- * @return static|null
- * @throws Exception
- */
- public static function queryOne($nvp = [], array $options = []): ?object {
- $options = array_merge($options, ["limit" => 1]);
- if(is_array($nvp)) {
- $rows = static::findByNVP($nvp, $options);
- }
- else {
- $rows = static::findByValueString($nvp, $options);
- }
- return $rows ? $rows[0] : null;
- }
- /**
- * @param array $nvp
- * @return array
- */
- private static function getRemappedNVP(array $nvp = []): array {
- $mapped_nvp = [];
- foreach($nvp as $field => $value) {
- $field = static::$fieldMap[$field] ?? $field;
- $mapped_nvp[$field] = $value;
- }
- return $mapped_nvp;
- }
- /**
- * @param array $nvp
- * @return int
- * @throws Exception
- */
- public static function count(array $nvp = []): int {
- $table = static::$table;
- if(is_array($nvp)) {
- $vs = "1";
- if(!empty($nvp)) {
- $nvp = static::getRemappedNVP($nvp);
- $vs = Database::getWhereString($nvp);
- }
- }
- else {
- $vs = $nvp;
- }
- $sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
- $result = Database::query($sql);
- return Database::fetchObject($result)->count;
- }
- /**
- * @param $nvp
- * @param array $options
- * @return static[]
- * @throws Exception
- */
- public static function findByNVP($nvp, array $options = []): array {
- if(empty($nvp)) {
- $vs = "1";
- }
- else {
- $nvp = static::getRemappedNVP($nvp);
- $vs = Database::getWhereString($nvp, $options);
- }
- return static::findByValueString($vs, $options);
- }
- /**
- * @param string $vs
- * @param array $opts
- * @return static[]
- * @throws Exception
- */
- private static function findByValueString(string $vs, array $opts = []): array {
- $class = static::class;
- $table = static::$table;
- $options = (object) $opts;
- $objects = [];
- $sql = "SELECT * FROM `$table` WHERE $vs";
- if(isset($options->sort)) {
- if(is_array($options->sort)) {
- $sql .= " ORDER BY ";
- $order_bys = [];
- foreach($options->sort as $index => $field) {
- $field = static::$fieldMap[$field] ?? $field;
- $order = $options->order[$index] ?? "asc";
- $order_bys[] = "`$field` $order";
- }
- $sql .= implode(", ", $order_bys);
- }
- else {
- $sort = static::$fieldMap[$options->sort] ?? $options->sort;
- $sql .= " ORDER BY `$sort`";
- if(isset($options->order)) {
- $sql .= " " . strtoupper($options->order);
- }
- }
- }
- if(isset($options->limit)) {
- $sql .= " LIMIT";
- if(isset($options->offset)) {
- $sql .= " $options->offset,";
- }
- $sql .= " $options->limit";
- }
- $result = Database::query($sql);
- while($row = Database::fetchObject($result)) {
- $objects[] = self::instantiateRow($class, $row);
- }
- if(!empty($options->id_as_key)) {
- $objects = self::arrayFlipById($objects);
- }
- return $objects;
- }
- /**
- * @param string $class
- * @param object $row
- * @return object
- * @throws Exception
- */
- protected static function instantiateRow(string $class, object $row): object {
- $reflection = new ReflectionClass($class);
- $is_instantiable = $reflection->isInstantiable();
- if($is_instantiable) {
- return new $class($row);
- }
- if($reflection->hasMethod("instantiate")) {
- /** @noinspection PhpUndefinedMethodInspection */
- return $class::instantiate($row);
- }
- throw new RuntimeException(__("$class is not instantiable and no instantiate() function exists."));
- }
- /**
- * @param Model[] $objects
- * @return array
- */
- public static function arrayFlipById(array $objects): array {
- $array = [];
- foreach($objects as $object) {
- $id = $object->getId();
- $array[$id] = $object;
- }
- return $array;
- }
- // Constructor
- public function __construct($model_data = null) {
- if($model_data === null) {
- $model_data = (object) [];
- }
- if(is_array($model_data)) {
- $model_data = (object) $model_data;
- }
- $this->modelData = $model_data;
- $this->inDatabase = $this->getId() !== null;
- }
- // Object methods
- final public function isNew(): bool {
- return empty($this->inDatabase);
- }
- final public function isModified(): bool {
- return !empty($this->modifiedFields);
- }
- final public function getModifiedFields(): array {
- return $this->modifiedFields;
- }
- private function getIdWhere(): string {
- $id_field = static::$idField;
- $id = $this->getId();
- $nvp = [];
- if(is_array($id)) {
- /**
- * @var array $id_field
- */
- $nvp = array_combine($id_field, $id);
- }
- else {
- $nvp[$id_field] = $id;
- }
- return Database::getWhereString($nvp, true);
- }
- /**
- * Commits changes to a model to the database
- *
- * @param array $options Optional array containing one or more of the following keys:
- * <ul>
- * <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>
- * <li><b>suppress_exception</b>: If <i>true</i>, an exception will not be thrown if the query fails</li>
- * </ul>
- * @return bool
- * @throws Exception Thrown on query failure
- */
- public function commit(array $options = []) : bool {
- // Options
- $testing = $options[self::COMMIT_TESTING] ?? false;
- $insert_ignore = $options[self::COMMIT_INSERT_IGNORE] ?? false;
- $suppress_exception = $options[self::COMMIT_SUPPRESS_EXCEPTION] ?? false;
- $id_field = static::$idField;
- $table = static::$table;
- $blob_fields = static::$blobFields;
- $nvp = [];
- foreach($this->modifiedFields as $field) {
- if(in_array($field, $blob_fields, true)) {
- $nvp[$field] = "x'" . bin2hex($this->modelData->$field) . "'";
- }
- // NULL
- else if($this->modelData->$field === null) {
- $nvp[$field] = null;
- }
- // Value
- else {
- $nvp[$field] = Database::escape($this->modelData->$field);
- }
- }
- if(empty($nvp)) {
- return true;
- }
- $value_string = Database::getValueString($nvp);
- if($this->inDatabase) {
- // Update
- $where = $this->getIdWhere();
- $sql = "UPDATE `$table` SET $value_string WHERE $where";
- }
- else if($insert_ignore) {
- $sql = "INSERT IGNORE INTO `$table` SET $value_string";
- }
- else {
- $sql = "INSERT INTO `$table` SET $value_string";
- }
- if($testing === false) {
- $result = Database::query($sql);
- if(empty($this->inDatabase) && $result) {
- // Set ID
- $insert_id = Database::insertId();
- if(!empty($insert_id)) {
- $this->$id_field = $insert_id;
- }
- $this->inDatabase = true;
- }
- }
- else {
- Database::$lastQuery = $sql;
- $result = true;
- if(empty($this->inDatabase) && !is_array(static::$idField)) {
- $this->$id_field = random_int(1, 32768);
- }
- $this->inDatabase = true;
- }
- if(!$result && !$suppress_exception) {
- throw new RuntimeException("An unexpected error has occurred. Please try again.");
- }
- return !empty($result);
- }
- /**
- * Deletes a model from the database
- *
- * @param array $options Optional array containing the following key:
- * * `suppress_exception`: If `true`, an exception will not be thrown if the query fails
- *
- * @return bool
- * @throws Exception Thrown on query failure
- */
- public function delete(array $options = []): bool {
- // Options
- $suppress_exception = $options[self::COMMIT_SUPPRESS_EXCEPTION] ?? false;
- $table = static::$table;
- $id = $this->getId();
- if($id === null) {
- return false;
- }
- $where = $this->getIdWhere();
- $sql = "DELETE FROM `$table` WHERE $where";
- $result = Database::query($sql);
- if(!$result && !$suppress_exception) {
- throw new RuntimeException("An unexpected error has occurred. Please try again.");
- }
- if(!$result) {
- return false;
- }
- return (bool) Database::affectedRows();
- }
- /**
- * @return array|int|null
- */
- final public function getId() {
- $id_field = static::$idField;
- if(is_array($id_field)) {
- $values = [];
- $fields = $id_field;
- foreach($fields as $field) {
- $value = $this->modelData->$field ?? null;
- if($value === null) {
- return null;
- }
- $values[] = $this->modelData->$field;
- }
- return $values;
- }
- return $this->modelData->$id_field ?? null;
- }
- final public function getIdString(): string {
- $id = $this->getId();
- return is_array($id) ? implode("-", $id) : (string) $id;
- }
- final public function getModelData(): ?object {
- return clone $this->modelData;
- }
- /**
- * @param Model|string $id_or_obj
- * @return bool
- */
- final public function is($id_or_obj): bool {
- $id_string = $this->getIdString();
- if(is_string($id_or_obj)) {
- return $id_string === $id_or_obj;
- }
- return ($id_string === $id_or_obj->getIdString());
- }
- }
|