Преглед изворни кода

Tidy up DB and Model classes

Alan Lam пре 5 година
родитељ
комит
4ff190ee92
2 измењених фајлова са 140 додато и 156 уклоњено
  1. 56 57
      engine/db.php
  2. 84 99
      engine/model.php

+ 56 - 57
engine/db.php

@@ -1,16 +1,16 @@
 <?php /** @noinspection PhpUnused */
 
-class db {
+class DB {
 
-	public static $last_query = "";
+	public static $lastQuery = "";
 
 	public static $queries = [];
-	public static $query_count = 0;
+	public static $queryCount = 0;
 
-	public static $DB = null;
+	public static $DB;
 
-	public static function affected_rows(mysqli $link = null): int {
-		if(empty($link)) $link = db::$DB;
+	public static function affectedRows(mysqli $link = null): int {
+		if($link === null) $link = self::$DB;
 		return mysqli_affected_rows($link);
 	}
 
@@ -25,12 +25,12 @@ class db {
 	 */
 	public static function connect(string $host, string $username, string $password, string $database = "", int $port = 3306): mysqli {
 		$link = @new mysqli($host, $username, $password, $database, $port);
-		db::$DB = $link;
+		self::$DB = $link;
 
 		if(!is_null($link->connect_error)) {
 			throw new Exception("Connect Error: " . $link->connect_error);
 		}
-		db::query("SET NAMES utf8mb4");
+		self::query("SET NAMES utf8mb4");
 		return $link;
 	}
 
@@ -39,7 +39,7 @@ class db {
 	 * @param int $row_number
 	 * @return bool
 	 */
-	public static function data_seek(mysqli_result $result, int $row_number): bool {
+	public static function dataSeek(mysqli_result $result, int $row_number): bool {
 		return mysqli_data_seek($result, $row_number);
 	}
 
@@ -48,12 +48,12 @@ class db {
 	 * @return string
 	 */
 	public static function escape($value): string {
-		return mysqli_real_escape_string(db::$DB, $value);
+		return mysqli_real_escape_string(self::$DB, $value);
 	}
 
-	public static function escape_nvp(array $nvp): array {
+	public static function escapeNvp(array $nvp): array {
 		foreach($nvp as $name => $value) {
-			$nvp[$name] = db::escape($value);
+			$nvp[$name] = self::escape($value);
 		}
 		return $nvp;
 	}
@@ -62,14 +62,14 @@ class db {
 	 * @return string
 	 */
 	public static function error(): string {
-		return mysqli_error(db::$DB);
+		return mysqli_error(self::$DB);
 	}
 
 	/**
 	 * @param mysqli_result $result
 	 * @return array|null
 	 */
-	public static function fetch_array(mysqli_result $result): ?array {
+	public static function fetchArray(mysqli_result $result): ?array {
 		return mysqli_fetch_array($result);
 	}
 
@@ -77,7 +77,7 @@ class db {
 	 * @param mysqli_result $result
 	 * @return array|null
 	 */
-	public static function fetch_assoc(mysqli_result $result): ?array {
+	public static function fetchAssoc(mysqli_result $result): ?array {
 		return mysqli_fetch_assoc($result);
 	}
 
@@ -85,7 +85,7 @@ class db {
 	 * @param mysqli_result $result
 	 * @return object|null
 	 */
-	public static function fetch_object(mysqli_result $result): ?object {
+	public static function fetchObject(mysqli_result $result): ?object {
 		return mysqli_fetch_object($result);
 	}
 
@@ -93,11 +93,11 @@ class db {
 	 * @param mysqli_result $result
 	 * @return array|null
 	 */
-	public static function fetch_row(mysqli_result $result): ?array {
+	public static function fetchRow(mysqli_result $result): ?array {
 		return mysqli_fetch_row($result);
 	}
 
-	public static function free_result(mysqli_result $result): void {
+	public static function freeResult(mysqli_result $result): void {
 		mysqli_free_result($result);
 	}
 
@@ -106,10 +106,10 @@ class db {
 	 * @param bool $escape
 	 * @return string
 	 */
-	public static function get_value_string(array $nvp, bool $escape = false): string {
+	public static function getValueString(array $nvp, bool $escape = false): string {
 
 		if($escape) {
-			$nvp = db::escape_nvp($nvp);
+			$nvp = self::escapeNvp($nvp);
 		}
 
 		$string_array = [];
@@ -133,7 +133,7 @@ class db {
 	 * @param array|bool $options
 	 * @return string
 	 */
-	public static function get_where_string(array $nvp, $options = []): string {
+	public static function getWhereString(array $nvp, $options = []): string {
 
 		$escape = false;
 		$fuzzy = false;
@@ -148,7 +148,7 @@ class db {
 		}
 
 		if($escape) {
-			$nvp = db::escape_nvp($nvp);
+			$nvp = self::escapeNvp($nvp);
 		}
 
 		$string_array = [];
@@ -158,14 +158,10 @@ class db {
 				$string_array[] = "`$field` IS NULL";
 			}
 			else if(is_array($value)) {
-				$values = array_map(function($str) {
-					return "'$str'";
-				}, $value);
-
 				if(empty($value)) $string_array[] = "0"; // Empty array
-				else $string_array[] = "`$field` IN (" . implode(", ", $values) . ")";
+				else $string_array[] = "`$field` IN (" . implode(", ", self::quoteValues($value)) . ")";
 			}
-			else if(is_a($value, "Constraint")) {
+			else if($value instanceof Constraint) {
 				$string_array[] = "`$field` " . $value->getConstraintString();
 			}
 			else {
@@ -181,29 +177,24 @@ class db {
 	 * @return bool
 	 * @throws Exception
 	 */
-	public static function has_index(string $table, string $index_name): bool {
+	public static function hasIndex(string $table, string $index_name): bool {
 		$sql = "SHOW INDEX FROM `$table` WHERE `Key_name`='$index_name'";
-		$result = db::query($sql);
-		return db::num_rows($result)==1;
+		$result = self::query($sql);
+		return self::numRows($result) === 1;
 	}
 
 	/**
 	 * @return int
 	 */
-	public static function insert_id(): int {
-		return mysqli_insert_id(db::$DB);
+	public static function insertId(): int {
+		return mysqli_insert_id(self::$DB);
 	}
 
 	/**
 	 * @param mysqli_result $result
 	 * @return int
 	 */
-	public static function num_rows(mysqli_result $result): int {
-
-		if(is_bool($result)) {
-			return 0;
-		}
-
+	public static function numRows(mysqli_result $result): int {
 		return mysqli_num_rows($result);
 	}
 
@@ -211,8 +202,8 @@ class db {
 	 * @param mysqli_result $result
 	 * @return object|null
 	 */
-	public static function object_or_null(mysqli_result $result): ?object {
-		return mysqli_num_rows($result)>0 ? db::fetch_object($result) : null;
+	public static function objectOrNull(mysqli_result $result): ?object {
+		return mysqli_num_rows($result)>0 ? self::fetchObject($result) : null;
 	}
 
 	/**
@@ -222,32 +213,33 @@ class db {
 	 * @return object|null
 	 * @throws Exception
 	 */
-	public static function object_with_id(string $table, string $field, int $id): ?object {
+	public static function objectWithId(string $table, string $field, int $id): ?object {
 		$sql = "SELECT * FROM `$table` WHERE `$field`='$id'";
-		$result = db::query($sql);
-		return db::object_or_null($result);
+		$result = self::query($sql);
+		return self::objectOrNull($result);
 	}
 
 	/**
 	 * @return bool
 	 */
 	public static function ping(): bool {
-		return mysqli_ping(db::$DB);
+		return mysqli_ping(self::$DB);
 	}
 
 	/**
 	 * @param string $sql
 	 * @return bool|mysqli_result
 	 * @throws Exception
+	 * @noinspection ForgottenDebugOutputInspection
 	 */
 	public static function query(string $sql) {
 		if(!is_string($sql)) return false;
 
-		self::$last_query = $sql;
+		self::$lastQuery = $sql;
 
-		$result = mysqli_query(db::$DB, $sql);
+		$result = mysqli_query(self::$DB, $sql);
 		if(!$result) {
-			$error = mysqli_error(db::$DB);
+			$error = mysqli_error(self::$DB);
 
 			error_log("Query failed: $sql\n");
 			error_log("Error: $error\n");
@@ -261,7 +253,7 @@ class db {
 		}
 
 		self::$queries[] = $sql;
-		self::$query_count++;
+		self::$queryCount++;
 
 		return $result;
 	}
@@ -271,23 +263,30 @@ class db {
 	 * @param mysqli|null $link_identifier
 	 * @return bool
 	 */
-	public static function select_db(string $name, mysqli $link_identifier = null): bool {
-		if(is_null($link_identifier)) {
-			return mysqli_select_db(db::$DB, $name);
-		}
-		else {
-			return mysqli_select_db($link_identifier, $name);
+	public static function selectDb(string $name, mysqli $link_identifier = null): bool {
+		if($link_identifier === null) {
+			return mysqli_select_db(self::$DB, $name);
 		}
+
+		return mysqli_select_db($link_identifier, $name);
 	}
 
 	/**
 	 * @return int
 	 */
-	public static function thread_id(): int {
-		return mysqli_thread_id(db::$DB);
+	public static function threadId(): int {
+		return mysqli_thread_id(self::$DB);
 	}
 
 	public static function dts(): string {
 		return gmdate("Y-m-d H:i:s");
 	}
+
+	public static function quoteValue($value): string {
+		return "'{$value}'";
+	}
+
+	public static function quoteValues(array $values): array {
+		return array_map("self::quoteValue", $values);
+	}
 }

+ 84 - 99
engine/model.php

@@ -12,9 +12,9 @@ abstract class Model {
 	protected static $repositories = [];
 
 	// Object variables
-	protected $model_data;
-	protected $modified_fields = [];
-	protected $in_db;
+	protected $modelData;
+	protected $modifiedFields = [];
+	protected $inDatabase;
 
 	// Magic methods
 
@@ -23,8 +23,7 @@ abstract class Model {
 	 * @return mixed
 	 */
 	public function __get(string $name) {
-
-		if(in_array($name, static::$object_fields)) {
+		if(in_array($name, static::$object_fields, true)) {
 			return $this->$name ?? null;
 		}
 
@@ -32,17 +31,17 @@ abstract class Model {
 			$name = static::$field_map[$name];
 		}
 
-		return isset($this->model_data->$name) ? $this->model_data->$name : null;
+		return $this->modelData->$name ?? null;
 	}
 
 	/**
 	 * @param string $name
-	 * @param string $value
+	 * @param string|null $value
 	 * @throws Exception
 	 */
-	public function __set(string $name, $value): void {
+	public function __set(string $name, ?string $value): void {
 
-		if(in_array($name, static::$object_fields)) {
+		if(in_array($name, static::$object_fields, true)) {
 			$this->$name = $value;
 			return;
 		}
@@ -53,28 +52,23 @@ abstract class Model {
 
 		$id_field = static::$id_field;
 
-		if($name == "model_data") {
-			$this->model_data = $value;
+		if($name === "model_data") {
+			$this->modelData = $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(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->model_data->$id_field)) {
-			$this->model_data->$id_field = $value;
+		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->model_data->$name = $value;
+			$this->modelData->$name = $value;
 		}
 	}
 
@@ -111,7 +105,7 @@ abstract class Model {
 			$args = func_get_args();
 			$fields = $id_field;
 
-			if(count($args) != count($fields)) return null;
+			if(count($args) !== count($fields)) return null;
 
 			foreach($fields as $index => $field) {
 				$nvp[$field] = $args[$index];
@@ -121,11 +115,11 @@ abstract class Model {
 			$nvp[$id_field] = $id;
 		}
 
-		$where = db::get_where_string($nvp, true);
+		$where = DB::getWhereString($nvp, true);
 
 		$sql = "SELECT * FROM `$table` WHERE $where";
-		$result = db::query($sql);
-		$object = db::object_or_null($result);
+		$result = DB::query($sql);
+		$object = DB::objectOrNull($result);
 
 		if($object) {
 			$object = new static($object);
@@ -139,13 +133,12 @@ abstract class Model {
 
 	/**
 	 * @param int $id
-	 * @param bool $exception_message
+	 * @param string|null $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.";
+	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);
@@ -162,8 +155,8 @@ abstract class Model {
 		$table = static::$table;
 
 		$sql = "SELECT * FROM `$table`";
-		$result = db::query($sql);
-		while($row = db::fetch_object($result)) {
+		$result = DB::query($sql);
+		while($row = DB::fetchObject($result)) {
 			$objects[] = new static($row);
 		}
 
@@ -171,7 +164,7 @@ abstract class Model {
 	}
 
 	/**
-	 * @param array ...$id_sets
+	 * @param int[] ...$id_sets
 	 * @return static[]
 	 * @throws Exception
 	 */
@@ -179,10 +172,7 @@ abstract class Model {
 
 		$table = static::$table;
 
-		$ids = [];
-		foreach($id_sets as $set) {
-			$ids = array_merge($ids, $set);
-		}
+		$ids = array_merge(...$id_sets);
 
 		if(empty($ids)) return [];
 
@@ -216,20 +206,20 @@ abstract class Model {
 	 * @return int
 	 * @throws Exception
 	 */
-	public static function deleteMultiple($nvp = []): int {
+	public static function deleteMultiple(array $nvp = []): int {
 		$table = static::$table;
 
 		$vs = "1";
 		if(!empty($nvp)) {
 			$nvp = static::getRemappedNVP($nvp);
-			$vs = db::get_where_string($nvp);
+			$vs = DB::getWhereString($nvp);
 		}
 
 		$sql = "DELETE FROM `$table` WHERE $vs";
-		$result = db::query($sql);
+		$result = DB::query($sql);
 		if(!$result) return false;
 
-		return db::affected_rows();
+		return DB::affectedRows();
 	}
 
 	/**
@@ -238,13 +228,12 @@ abstract class Model {
 	 * @return static[]
 	 * @throws Exception
 	 */
-	public static function query($nvp = [], $options = []): array {
+	public static function query($nvp = [], array $options = []): array {
 		if(is_array($nvp)) {
 			return static::findByNVP($nvp, $options);
 		}
-		else {
-			return static::findByValueString($nvp, $options);
-		}
+
+		return static::findByValueString($nvp, $options);
 	}
 
 	/**
@@ -253,7 +242,7 @@ abstract class Model {
 	 * @return static[]
 	 * @throws Exception
 	 */
-	public static function queryFuzzy($nvp = [], $options = []): array {
+	public static function queryFuzzy(array $nvp = [], array $options = []): array {
 		$options["fuzzy"] = true;
 		return static::findByNVP($nvp, $options);
 	}
@@ -264,7 +253,7 @@ abstract class Model {
 	 * @return static|null
 	 * @throws Exception
 	 */
-	public static function queryOne($nvp = [], $options = []): ?object {
+	public static function queryOne(array $nvp = [], array $options = []): ?object {
 		$rows = static::findByNVP($nvp, $options);
 		return $rows ? $rows[0] : null;
 	}
@@ -273,7 +262,7 @@ abstract class Model {
 	 * @param array $nvp
 	 * @return array
 	 */
-	private static function getRemappedNVP($nvp = []): array {
+	private static function getRemappedNVP(array $nvp = []): array {
 		$mapped_nvp = [];
 		foreach($nvp as $field => $value) {
 			$field = static::$field_map[$field] ?? $field;
@@ -287,20 +276,18 @@ abstract class Model {
 	 * @return int
 	 * @throws Exception
 	 */
-	public static function count($nvp = []): int {
+	public static function count(array $nvp = []): int {
 		$table = static::$table;
 
 		$vs = "1";
 		if(!empty($nvp)) {
 			$nvp = static::getRemappedNVP($nvp);
-			$vs = db::get_where_string($nvp);
+			$vs = DB::getWhereString($nvp);
 		}
 
 		$sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
-		$result = db::query($sql);
-		$row = db::fetch_object($result);
-
-		return $row->count;
+		$result = DB::query($sql);
+		return DB::fetchObject($result)->count;
 	}
 
 	/**
@@ -316,7 +303,7 @@ abstract class Model {
 		}
 		else {
 			$nvp = static::getRemappedNVP($nvp);
-			$vs = db::get_where_string($nvp, $options);
+			$vs = DB::getWhereString($nvp, $options);
 		}
 
 		return static::findByValueString($vs, $options);
@@ -324,14 +311,14 @@ abstract class Model {
 
 	/**
 	 * @param string $vs
-	 * @param array $options
+	 * @param array $options_array
 	 * @return static[]
 	 * @throws Exception
 	 */
-	private static function findByValueString(string $vs, array $options = []): array {
+	private static function findByValueString(string $vs, array $options_array = []): array {
 		$table = static::$table;
 
-		$options = (object) $options;
+		$options = (object) $options_array;
 
 		$objects = [];
 
@@ -354,8 +341,8 @@ abstract class Model {
 			$sql .= " $options->limit";
 		}
 
-		$result = db::query($sql);
-		while($row = db::fetch_object($result)) {
+		$result = DB::query($sql);
+		while($row = DB::fetchObject($result)) {
 			$objects[] = new static($row);
 		}
 
@@ -376,25 +363,25 @@ abstract class Model {
 			$model_data = (object) $model_data;
 		}
 
-		$this->model_data = $model_data;
+		$this->modelData = $model_data;
 
-		$this->in_db = !is_null($this->getId());
+		$this->inDatabase = !is_null($this->getId());
 
 	}
 
 	// Object methods
-	public final function isModified() {
-		return !empty($this->modified_fields);
+	final public function isModified(): bool {
+		return !empty($this->modifiedFields);
 	}
 
-	public final function getModifiedFields() {
-		return $this->modified_fields;
+	final public function getModifiedFields(): array {
+		return $this->modifiedFields;
 	}
 
-	private function preCommit() {
+	private function preCommit(): void {
 	}
 
-	private final function getIDWhere() {
+	private function getIDWhere(): string {
 
 		$id_field = static::$id_field;
 		$id = $this->getId();
@@ -407,9 +394,7 @@ abstract class Model {
 			$nvp[$id_field] = $id;
 		}
 
-		$where = db::get_where_string($nvp, true);
-
-		return $where;
+		return DB::getWhereString($nvp, true);
 	}
 
 	/**
@@ -417,7 +402,7 @@ abstract class Model {
 	 * @return bool
 	 * @throws Exception
 	 */
-	public final function commit($testing = false) {
+	final public function commit(bool $testing = false): bool {
 
 		$this->preCommit();
 
@@ -427,25 +412,25 @@ abstract class Model {
 
 		$nvp = [];
 
-		foreach($this->modified_fields as $field) {
-			if(in_array($field, $blob_fields)) {
-				$nvp[$field] = "x'" . bin2hex($this->model_data->$field) . "'";
+		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->model_data->$field)) {
+			else if(is_null($this->modelData->$field)) {
 				$nvp[$field] = null;
 			}
 			// Value
 			else {
-				$nvp[$field] = db::escape($this->model_data->$field);
+				$nvp[$field] = DB::escape($this->modelData->$field);
 			}
 		}
 
 		if(empty($nvp)) return true;
 
-		$value_string = db::get_value_string($nvp);
+		$value_string = DB::getValueString($nvp);
 
-		if($this->in_db) {
+		if($this->inDatabase) {
 			// Update
 			$where = $this->getIDWhere();
 			$sql = "UPDATE `$table` SET $value_string WHERE $where";
@@ -455,30 +440,30 @@ abstract class Model {
 			$sql = "INSERT INTO `$table` SET $value_string";
 		}
 
-		if($testing == false) {
-			$result = db::query($sql);
+		if($testing === false) {
+			$result = DB::query($sql);
 
-			if(empty($this->in_db) && $result) {
+			if(empty($this->inDatabase) && $result) {
 				// Set ID
-				$insert_id = db::insert_id();
+				$insert_id = DB::insertId();
 				if(!empty($insert_id)) {
 					$this->$id_field = $insert_id;
 				}
-				$this->in_db = true;
+				$this->inDatabase = true;
 			}
 		}
 		else {
-			db::$last_query = $sql;
+			DB::$lastQuery = $sql;
 
 			$result = true;
-			if(empty($this->in_db) && !is_array(static::$id_field)) {
-				$this->$id_field = mt_rand(1, 32768);
+			if(empty($this->inDatabase) && !is_array(static::$id_field)) {
+				$this->$id_field = random_int(1, 32768);
 			}
-			$this->in_db = true;
+			$this->inDatabase = true;
 		}
 
 		if($result) {
-			$this->modified_fields = [];
+			$this->modifiedFields = [];
 		}
 
 		return !empty($result);
@@ -488,7 +473,7 @@ abstract class Model {
 	 * @return bool
 	 * @throws Exception
 	 */
-	public function testCommit() {
+	public function testCommit(): bool {
 		return $this->commit(true);
 	}
 
@@ -497,10 +482,10 @@ abstract class Model {
 	 * @return bool
 	 * @throws Exception
 	 */
-	public final function commitOrException($testing = false) {
+	final public function commitOrException(bool $testing = false): bool {
 		$success = $this->commit($testing);
 		if(!$success) throw new Exception("Database error.");
-		return $success;
+		return true;
 	}
 
 	/**
@@ -517,9 +502,9 @@ abstract class Model {
 		$where = $this->getIDWhere();
 
 		$sql = "DELETE FROM `$table` WHERE $where";
-		$result = db::query($sql);
+		$result = DB::query($sql);
 
-		return !empty($result) && db::affected_rows();
+		return !empty($result) && DB::affectedRows();
 	}
 
 	/**
@@ -538,18 +523,18 @@ abstract class Model {
 			$values = [];
 			$fields = $id_field;
 			foreach($fields as $field) {
-				$value = $this->model_data->$field ?? null;
+				$value = $this->modelData->$field ?? null;
 				if($value === null) return null;
-				$values[] = $this->model_data->$field;
+				$values[] = $this->modelData->$field;
 			}
 			return $values;
 		}
 
-		return $this->model_data->$id_field ?? null;
+		return $this->modelData->$id_field ?? null;
 	}
 
 	final public function getModelData() {
-		return clone $this->model_data;
+		return clone $this->modelData;
 	}
 
 }