$name ?? null; } if(isset(static::$field_map[$name])) { $name = static::$field_map[$name]; } return $this->modelData->$name ?? null; } /** * @param string $name * @param string|null $value * @throws Exception */ public function __set(string $name, ?string $value): void { if(in_array($name, static::$object_fields, true)) { $this->$name = $value; return; } if(isset(static::$field_map[$name])) { $name = static::$field_map[$name]; } $id_field = static::$id_field; if($name === "model_data") { $this->modelData = $value; } else if(in_array($name, static::$fillable_fields, true)) { if(!isset($this->modelData->$name) || ($this->modelData->$name !== $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::$enforce_field_check) { throw new Exception("Attempt to set an unfillable field $name"); } else { $this->modelData->$name = $value; } } /** * @param string $name * @return bool */ public function __isset(string $name) { $value = $this->$name; return !is_null($value); } // Static method /** * @param $id * @return static|null * @throws Exception */ public static function get($id): ?object { $table = static::$table; $is_compound_key = is_array(static::$id_field); // Check repo for item if(!$is_compound_key && isset(static::$repositories[$table][$id])) { return static::$repositories[$table][$id]; } $id_field = static::$id_field; $nvp = []; if($is_compound_key && is_array($id_field)) { // Compound key $args = func_get_args(); $fields = $id_field; if(count($args) !== count($fields)) return null; foreach($fields as $index => $field) { $nvp[$field] = $args[$index]; } } else { $nvp[$id_field] = $id; } $where = DB::getWhereString($nvp, true); $sql = "SELECT * FROM `$table` WHERE $where"; $result = DB::query($sql); $object = DB::objectOrNull($result); if($object) { $object = new static($object); if(!$is_compound_key) { static::$repositories[$table][$id] = $object; } } return $object; } /** * @param int $id * @param string|null $exception_message * @return static|null * @throws Exception */ public static function getOrException(int $id, string $exception_message = null): ?object { if(!$exception_message) $exception_message = static::class . " not found."; $object = static::get($id); if(!$object) throw new Exception($exception_message); return $object; } /** * @return static[] * @throws Exception */ public static function getAll(): array { $objects = []; $table = static::$table; $sql = "SELECT * FROM `$table`"; $result = DB::query($sql); while($row = DB::fetchObject($result)) { $objects[] = new static($row); } return $objects; } /** * @param int[] ...$id_sets * @return static[] * @throws Exception */ public static function load(...$id_sets): array { $table = static::$table; $ids = array_merge(...$id_sets); if(empty($ids)) return []; $ids = array_unique($ids); $items = static::query([static::$id_field => $ids], ["id_as_key" => true]); foreach($items as $id => $item) { static::$repositories[$table][$id] = $item; } return $items; } /** * @return static[] * @throws Exception */ public static function loadAll(): array { $table = static::$table; $items = static::query([], ["id_as_key" => true]); foreach($items as $id => $item) { static::$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 = DB::getWhereString($nvp); } $sql = "DELETE FROM `$table` WHERE $vs"; $result = DB::query($sql); if(!$result) return false; return DB::affectedRows(); } /** * @param string|array $nvp * @param array $options * @return static[] * @throws Exception */ public static function query($nvp = [], array $options = []): array { if(is_array($nvp)) { return static::findByNVP($nvp, $options); } return static::findByValueString($nvp, $options); } /** * @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 $nvp * @param array $options * @return static|null * @throws Exception */ public static function queryOne(array $nvp = [], array $options = []): ?object { $rows = static::findByNVP($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::$field_map[$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; $vs = "1"; if(!empty($nvp)) { $nvp = static::getRemappedNVP($nvp); $vs = DB::getWhereString($nvp); } $sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs"; $result = DB::query($sql); return DB::fetchObject($result)->count; } /** * @param array $nvp * @param array $options * @return static[] * @throws Exception */ public static function findByNVP(array $nvp, array $options = []): array { if(empty($nvp)) { $vs = "1"; } else { $nvp = static::getRemappedNVP($nvp); $vs = DB::getWhereString($nvp, $options); } return static::findByValueString($vs, $options); } /** * @param string $sql * @return static[] * @throws Exception */ public static function findBySql(string $sql): array { $objects = []; $result = DB::query($sql); while($row = DB::fetchObject($result)) { $objects[] = new static($row); } return $objects; } /** * @param string $vs * @param array $options_array * @return static[] * @throws Exception */ private static function findByValueString(string $vs, array $options_array = []): array { $table = static::$table; $options = (object) $options_array; $objects = []; $sql = "SELECT * FROM `$table` WHERE $vs"; if(isset($options->sort)) { $sort = static::$field_map[$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 = DB::query($sql); while($row = DB::fetchObject($result)) { $objects[] = new static($row); } if(!empty($options->id_as_key)) { $objects = Util::arrayFlipByID($objects); } return $objects; } // Constructor public function __construct($model_data = null) { if(is_null($model_data)) { $model_data = (object) []; } if(is_array($model_data)) { $model_data = (object) $model_data; } $this->modelData = $model_data; $this->inDatabase = !is_null($this->getId()); } // Object methods final public function isModified(): bool { return !empty($this->modifiedFields); } final public function getModifiedFields(): array { return $this->modifiedFields; } private function preCommit(): void { } private function getIDWhere(): string { $id_field = static::$id_field; $id = $this->getId(); $nvp = []; if(is_array($id) && is_array($id_field)) { $nvp = array_combine($id_field, $id); } else { $nvp[$id_field] = $id; } return DB::getWhereString($nvp, true); } /** * @param bool $testing * @return bool * @throws Exception */ final public function commit(bool $testing = false): bool { $this->preCommit(); $id_field = static::$id_field; $table = static::$table; $blob_fields = static::$blob_fields; $nvp = []; foreach($this->modifiedFields as $field) { if(in_array($field, $blob_fields, true)) { $nvp[$field] = "x'" . bin2hex($this->modelData->$field) . "'"; } // NULL else if(is_null($this->modelData->$field)) { $nvp[$field] = null; } // Value else { $nvp[$field] = DB::escape($this->modelData->$field); } } if(empty($nvp)) return true; $value_string = DB::getValueString($nvp); if($this->inDatabase) { // Update $where = $this->getIDWhere(); $sql = "UPDATE `$table` SET $value_string WHERE $where"; } else { // Insert $sql = "INSERT INTO `$table` SET $value_string"; } if($testing === false) { $result = DB::query($sql); if(empty($this->inDatabase) && $result) { // Set ID $insert_id = DB::insertId(); if(!empty($insert_id)) { $this->$id_field = $insert_id; } $this->inDatabase = true; } } else { DB::$lastQuery = $sql; $result = true; if(empty($this->inDatabase) && !is_array(static::$id_field)) { $this->$id_field = random_int(1, 32768); } $this->inDatabase = true; } if($result) { $this->modifiedFields = []; } return !empty($result); } /** * @return bool * @throws Exception */ public function testCommit(): bool { return $this->commit(true); } /** * @param bool $testing * @return bool * @throws Exception */ final public function commitOrException(bool $testing = false): bool { $success = $this->commit($testing); if(!$success) throw new Exception("Database error."); return true; } /** * @return bool * @throws Exception */ public function delete(): bool { $table = static::$table; $id = $this->getId(); if(is_null($id)) return false; $where = $this->getIDWhere(); $sql = "DELETE FROM `$table` WHERE $where"; $result = DB::query($sql); return !empty($result) && DB::affectedRows(); } /** * @return bool * @throws Exception */ final public function deleteOrException(): bool { $success = $this->delete(); if(!$success) throw new Exception("Database error."); return true; } final public function getId() { $id_field = static::$id_field; 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() { return clone $this->modelData; } final public function is($id_or_model): bool { if($id_or_model instanceof self) { $model = $id_or_model; return $model->getIdString() === $this->getIdString(); } return $this->getIdString() === $id_or_model; } }