| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555 |
- <?php /** @noinspection PhpUnused */
- abstract class Model {
- protected static $table = "";
- protected static $id_field = "";
- protected static $fillable_fields = [];
- protected static $enforce_field_check = true;
- protected static $field_map = []; // Used for field name aliases
- protected static $object_fields = [];
- protected static $blob_fields = [];
- protected static $repositories = [];
- // Object variables
- protected $model_data;
- protected $modified_fields = [];
- protected $in_db;
- // Magic methods
- /**
- * @param string $name
- * @return mixed
- */
- public function __get(string $name) {
- if(in_array($name, static::$object_fields)) {
- return $this->$name ?? null;
- }
- if(isset(static::$field_map[$name])) {
- $name = static::$field_map[$name];
- }
- return isset($this->model_data->$name) ? $this->model_data->$name : null;
- }
- /**
- * @param string $name
- * @param string $value
- * @throws Exception
- */
- public function __set(string $name, $value): void {
- if(in_array($name, static::$object_fields)) {
- $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->model_data = $value;
- }
- else if(in_array($name, static::$fillable_fields)) {
- if(!is_null($value)) {
- $value = strval($value);
- }
- if(!isset($this->model_data->$name) || ($this->model_data->$name !== $value)) {
- $this->model_data->$name = $value;
- $this->modified_fields[] = $name;
- }
- }
- else if($name == $id_field && empty($this->model_data->$id_field)) {
- $this->model_data->$id_field = $value;
- }
- else if(static::$enforce_field_check) {
- throw new Exception("Attempt to set an unfillable field $name");
- }
- else {
- $this->model_data->$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::get_where_string($nvp, true);
- $sql = "SELECT * FROM `$table` WHERE $where";
- $result = db::query($sql);
- $object = db::object_or_null($result);
- if($object) {
- $object = new static($object);
- if(!$is_compound_key) {
- static::$repositories[$table][$id] = $object;
- }
- }
- return $object;
- }
- /**
- * @param int $id
- * @param bool $exception_message
- * @return static|null
- * @throws Exception
- */
- public static function getOrException(int $id, bool $exception_message = false): ?object {
- if(!$exception_message) $exception_message = get_called_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::fetch_object($result)) {
- $objects[] = new static($row);
- }
- return $objects;
- }
- /**
- * @param array ...$id_sets
- * @return static[]
- * @throws Exception
- */
- public static function load(...$id_sets): array {
- $table = static::$table;
- $ids = [];
- foreach($id_sets as $set) {
- $ids = array_merge($ids, $set);
- }
- 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($nvp = []): int {
- $table = static::$table;
- $vs = "1";
- if(!empty($nvp)) {
- $nvp = static::getRemappedNVP($nvp);
- $vs = db::get_where_string($nvp);
- }
- $sql = "DELETE FROM `$table` WHERE $vs";
- $result = db::query($sql);
- if(!$result) return false;
- return db::affected_rows();
- }
- /**
- * @param string|array $nvp
- * @param array $options
- * @return static[]
- * @throws Exception
- */
- public static function query($nvp = [], $options = []): array {
- if(is_array($nvp)) {
- return static::findByNVP($nvp, $options);
- }
- else {
- return static::findByValueString($nvp, $options);
- }
- }
- /**
- * @param array $nvp
- * @param array $options
- * @return static[]
- * @throws Exception
- */
- public static function queryFuzzy($nvp = [], $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($nvp = [], $options = []): ?object {
- $rows = static::findByNVP($nvp, $options);
- return $rows ? $rows[0] : null;
- }
- /**
- * @param array $nvp
- * @return array
- */
- private static function getRemappedNVP($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($nvp = []): int {
- $table = static::$table;
- $vs = "1";
- if(!empty($nvp)) {
- $nvp = static::getRemappedNVP($nvp);
- $vs = db::get_where_string($nvp);
- }
- $sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
- $result = db::query($sql);
- $row = db::fetch_object($result);
- return $row->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::get_where_string($nvp, $options);
- }
- return static::findByValueString($vs, $options);
- }
- /**
- * @param string $vs
- * @param array $options
- * @return static[]
- * @throws Exception
- */
- private static function findByValueString(string $vs, array $options = []): array {
- $table = static::$table;
- $options = (object) $options;
- $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::fetch_object($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->model_data = $model_data;
- $this->in_db = !is_null($this->getId());
- }
- // Object methods
- public final function isModified() {
- return !empty($this->modified_fields);
- }
- public final function getModifiedFields() {
- return $this->modified_fields;
- }
- private function preCommit() {
- }
- private final function getIDWhere() {
- $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;
- }
- $where = db::get_where_string($nvp, true);
- return $where;
- }
- /**
- * @param bool $testing
- * @return bool
- * @throws Exception
- */
- public final function commit($testing = false) {
- $this->preCommit();
- $id_field = static::$id_field;
- $table = static::$table;
- $blob_fields = static::$blob_fields;
- $nvp = [];
- foreach($this->modified_fields as $field) {
- if(in_array($field, $blob_fields)) {
- $nvp[$field] = "x'" . bin2hex($this->model_data->$field) . "'";
- }
- // NULL
- else if(is_null($this->model_data->$field)) {
- $nvp[$field] = null;
- }
- // Value
- else {
- $nvp[$field] = db::escape($this->model_data->$field);
- }
- }
- if(empty($nvp)) return true;
- $value_string = db::get_value_string($nvp);
- if($this->in_db) {
- // 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->in_db) && $result) {
- // Set ID
- $insert_id = db::insert_id();
- if(!empty($insert_id)) {
- $this->$id_field = $insert_id;
- }
- $this->in_db = true;
- }
- }
- else {
- db::$last_query = $sql;
- $result = true;
- if(empty($this->in_db) && !is_array(static::$id_field)) {
- $this->$id_field = mt_rand(1, 32768);
- }
- $this->in_db = true;
- }
- if($result) {
- $this->modified_fields = [];
- }
- return !empty($result);
- }
- /**
- * @return bool
- * @throws Exception
- */
- public function testCommit() {
- return $this->commit(true);
- }
- /**
- * @param bool $testing
- * @return bool
- * @throws Exception
- */
- public final function commitOrException($testing = false) {
- $success = $this->commit($testing);
- if(!$success) throw new Exception("Database error.");
- return $success;
- }
- /**
- * @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::affected_rows();
- }
- /**
- * @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->model_data->$field ?? null;
- if($value === null) return null;
- $values[] = $this->model_data->$field;
- }
- return $values;
- }
- return $this->model_data->$id_field ?? null;
- }
- final public function getModelData() {
- return clone $this->model_data;
- }
- }
|