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; } /** * @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: * * @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()); } }