From dff20440fe3889c5bff1ca9b483c7a9806bb0fbf Mon Sep 17 00:00:00 2001 From: Hossein Hosni Date: Tue, 2 Apr 2024 17:27:51 +0330 Subject: [PATCH] Resolve PHPStan errors --- .gitignore | 2 + .../CannotStartProcessException.php | 16 + .../Exceptions/InterruptedException.php | 7 + .../Exceptions/NotSavedProcessException.php | 10 + .../Exceptions/NotShellAccessException.php | 7 + .../Exceptions/NotStartedProcessException.php | 16 + .../background/InterruptedException.php | 6 +- .../libraries/background/NotShellAccess.php | 5 +- .../base/libraries/background/Process.php | 30 +- packages/base/libraries/background/cli.php | 1 + packages/base/libraries/date/Date.php | 8 +- packages/base/libraries/date/hdate.php | 10 +- packages/base/libraries/date/jdate.php | 21 +- packages/base/libraries/db/MysqliDb.php | 10 +- packages/base/libraries/db/db.php | 815 ++---------------- packages/base/libraries/db/dbObject.php | 9 +- packages/base/libraries/frontend/Source.php | 37 +- packages/base/libraries/frontend/theme.php | 2 + packages/base/libraries/http/Client.php | 1 + packages/base/libraries/io/directory/ftp.php | 24 +- packages/base/libraries/io/directory/sftp.php | 23 +- packages/base/libraries/mvc/FormError.php | 2 +- .../base/libraries/router/PathException.php | 12 +- .../base/libraries/router/RuleException.php | 15 +- packages/base/libraries/router/exceptions.php | 10 +- packages/base/libraries/router/rule.php | 6 +- .../base/libraries/translator/translator.php | 2 +- packages/base/libraries/utility/password.php | 8 +- 28 files changed, 252 insertions(+), 863 deletions(-) create mode 100644 packages/base/libraries/background/Exceptions/CannotStartProcessException.php create mode 100644 packages/base/libraries/background/Exceptions/InterruptedException.php create mode 100644 packages/base/libraries/background/Exceptions/NotSavedProcessException.php create mode 100644 packages/base/libraries/background/Exceptions/NotShellAccessException.php create mode 100644 packages/base/libraries/background/Exceptions/NotStartedProcessException.php diff --git a/.gitignore b/.gitignore index 17dcca0..9c58320 100644 --- a/.gitignore +++ b/.gitignore @@ -6,8 +6,10 @@ /packages/base/storage/public/frontend/* /packages/base/storage/private/frontend/* /packages/base/storage/private/sessions/* +/packages/base/storage/private/http_client_cookies/* !/packages/base/storage/private/cache/.gitkeep !/packages/base/storage/private/sessions/.gitkeep !/packages/base/storage/protected/logs/.gitkeep !/packages/base/storage/public/frontend/.gitkeep +!/packages/base/storage/private/http_client_cookies/.gitkeep !/packages/base/storage/private/frontend/webpack.config.js \ No newline at end of file diff --git a/packages/base/libraries/background/Exceptions/CannotStartProcessException.php b/packages/base/libraries/background/Exceptions/CannotStartProcessException.php new file mode 100644 index 0000000..619f215 --- /dev/null +++ b/packages/base/libraries/background/Exceptions/CannotStartProcessException.php @@ -0,0 +1,16 @@ +process; + } +} diff --git a/packages/base/libraries/background/Exceptions/InterruptedException.php b/packages/base/libraries/background/Exceptions/InterruptedException.php new file mode 100644 index 0000000..777e34b --- /dev/null +++ b/packages/base/libraries/background/Exceptions/InterruptedException.php @@ -0,0 +1,7 @@ +process; + } +} diff --git a/packages/base/libraries/background/InterruptedException.php b/packages/base/libraries/background/InterruptedException.php index 76de0de..cc715f6 100644 --- a/packages/base/libraries/background/InterruptedException.php +++ b/packages/base/libraries/background/InterruptedException.php @@ -1,4 +1,8 @@ checkOS()){ - throw new notShellAccess(); + throw new Process\Exceptions\NotShellAccessException(); } if(!function_exists('shell_exec')){ - throw new notShellAccess(); + throw new Process\Exceptions\NotShellAccessException(); } if(!$this->id){ - throw new notSavedProcess(); + throw new Process\Exceptions\NotSavedProcessException(); } $root_directory = options::get('root_directory'); $php = options::get('packages.base.process.php-bin'); @@ -90,7 +91,7 @@ public function background_run(){ $this->save(); return true; }else{ - throw new cannotStartProcess(); + throw new Process\Exceptions\CannotStartProcessException($this); } } public function setPID(){ @@ -180,9 +181,10 @@ public function isRunning(){ if($this->pid){ return file_exists('/proc/'.$this->pid); }else{ - throw new notStartedProcess(); + throw new Process\Exceptions\NotStartedProcessException($this); } } + return false; } /** * Returns if the process interrupted by anthor process. @@ -191,7 +193,7 @@ public function isRunning(){ */ protected function isInterrupted(): bool { if (!$this->pid) { - throw new notStartedProcess(); + throw new Process\Exceptions\NotStartedProcessException($this); } return cache::get("packages.base.process.".$this->pid.".interrupt") == 1; } @@ -203,7 +205,7 @@ protected function isInterrupted(): bool { */ protected function checkInterruption() { if ($this->isInterrupted()) { - throw new InterruptedException(); + throw new Process\Exceptions\InterruptedException(); } } /** @@ -213,7 +215,7 @@ protected function checkInterruption() { */ public function interrupt() { if (!$this->pid) { - throw new notStartedProcess(); + throw new Process\Exceptions\NotStartedProcessException($this); } cache::set("packages.base.process.".$this->pid.".interrupt", 1); } @@ -231,13 +233,13 @@ public function stop($signal = self::SIGTERM, $timeout = 10) { return !$this->isRunning(); } }else{ - throw new notStartedProcess(); + throw new Process\Exceptions\NotStartedProcessException($this); } return false; } protected function checkOS(){ if(self::getOS() != self::OS_NIX){ - throw new OSSupport(); + throw new Process\Exceptions\NotShellAccessException(); } return true; } diff --git a/packages/base/libraries/background/cli.php b/packages/base/libraries/background/cli.php index 79c642e..d77a337 100644 --- a/packages/base/libraries/background/cli.php +++ b/packages/base/libraries/background/cli.php @@ -18,6 +18,7 @@ static function getParameter($name){ * @return array */ public static function getParameters($params){ + $params = $params ?? []; $return = array(); for($x = 0;$x!=count($params);$x++){ if($x == 0)continue; diff --git a/packages/base/libraries/date/Date.php b/packages/base/libraries/date/Date.php index 7120f3a..bf90950 100644 --- a/packages/base/libraries/date/Date.php +++ b/packages/base/libraries/date/Date.php @@ -46,7 +46,7 @@ public static function setTimeZone(string $timezone) { $log->debug("check given timezone (" . $timezone . ") is valid?"); if (!in_array($timezone, DateTimeZone::listIdentifiers(DateTimeZone::ALL))) { $log->reply()->fatal("is not valid"); - throw new TimeZoneInvalidException($timezone); + throw new Date\TimeZoneNotValid($timezone); } else { $log->reply("is valid"); } @@ -131,8 +131,8 @@ public static function setDefaultcalendar(){ if (($option = options::load('packages.base.date')) !== false) { $log->reply($option); $defaultOption = array_replace_recursive($defaultOption, $option); - $log->debug("set calendar to",$foption['calendar']); - self::setCanlenderName($foption['calendar']); + $log->debug("set calendar to",$defaultOption['calendar']); + self::setCanlenderName($defaultOption['calendar']); } else{ $log->reply("Not defined"); } @@ -213,7 +213,7 @@ public static function init() { self::setDefaultcalendar(); } if(!self::$calendar){ - throw new NoCalendarException(); + throw new Date\NoCalendarException(); } self::$inited = true; } diff --git a/packages/base/libraries/date/hdate.php b/packages/base/libraries/date/hdate.php index d3f8dda..2d0b515 100644 --- a/packages/base/libraries/date/hdate.php +++ b/packages/base/libraries/date/hdate.php @@ -1,6 +1,7 @@ self::umstartjd && $julianday < self::umendjd) { $i = (int) (($julianday - 1948438) / 29.53056) - ((self::umstartyear - 1) * 12); $mjd = $julianday - self::mjd_factor; + $umdata = self::getUmalquradata(); $umdata_count = count($umdata); for ($i = max(0, $i); $i < $umdata_count; $i++) { @@ -335,7 +337,7 @@ public static function daysOfYear($hmonth, $hday, $hyear): int { list($year, $month, $day, $dayinyear) = self::gregorianToHijri($year, $month, $day); return $dayinyear; } - public static function monthname($month): string { + public static function monthname(string $month): string { switch($month) { case('01'):return('محرم');break; case('02'):return('صفر');break; @@ -350,6 +352,7 @@ public static function monthname($month): string { case('11'):return('ذیقعده');break; case('12'):return('ذیحجه');break; } + throw new Exception('The given month is not valid!'); } public static function mstart($month, $day, $year): string { list( $hyear, $hmonth, $hday ) = self::gregorianToHijri($year, $month, $day); @@ -357,7 +360,7 @@ public static function mstart($month, $day, $year): string { $timestamp = mktime(0, 0, 0, $month, $day, $year); return date("w", $timestamp); } - public static function short_monthname($month): string { + public static function short_monthname(string $month): string { switch($month) { case('01'):return('مح');break; case('02'):return('صف');break; @@ -372,6 +375,7 @@ public static function short_monthname($month): string { case('11'):return('ذق');break; case('12'):return('ذح');break; } + throw new Exception('The given month is not valid!'); } public static function mktime($hour = null, $minute = null, $second = null , $month = null, $day = null, $year = null): int { list( $year, $month, $day ) = self::hijriToGregorian($year, $month, $day); diff --git a/packages/base/libraries/date/jdate.php b/packages/base/libraries/date/jdate.php index 0431237..326271b 100644 --- a/packages/base/libraries/date/jdate.php +++ b/packages/base/libraries/date/jdate.php @@ -136,7 +136,7 @@ public static function format($type,$maket="now"){ case "w":$result1=date("w",$need);if($transnumber==1) $result.=self::Convertnumber2farsi($result1);else $result.=$result1;break; case "y":$result1=substr($jyear,2,4);if($transnumber==1) $result.=self::Convertnumber2farsi($result1);else $result.=$result1;break; case "Y":$result1=$jyear;if($transnumber==1) $result.=self::Convertnumber2farsi($result1);else $result.=$result1;break; - case "U" :$result.=mktime();break; + case "U" :$result.=mktime(date('H', $need), date('i', $need), date('s', $need), date('m', $need), date('d', $need), date('Y',$need));break; case "Z" :$result.=self::days_of_year($jmonth,$jday,$jyear);break; case "L" :list( $tmp_year, $tmp_month, $tmp_day ) = self::jalali_to_gregorian(1384, 12, 1);echo $tmp_day;break; default:$result.=$subtype; @@ -289,25 +289,6 @@ static function jcheckdate($month,$day,$year){ } return 0; } - static function jtime(){ - return mktime() ; - } - static function jgetdate($timestamp=""){ - if($timestamp=="")$timestamp=mktime(); - return array( - 0=>$timestamp, - "seconds"=>self::format("s",$timestamp), - "minutes"=>self::format("i",$timestamp), - "hours"=>self::format("G",$timestamp), - "mday"=>self::format("j",$timestamp), - "wday"=>self::format("w",$timestamp), - "mon"=>self::format("n",$timestamp), - "year"=>self::format("Y",$timestamp), - "yday"=>self::days_of_year(self::format("m",$timestamp),self::format("d",$timestamp),self::format("Y",$timestamp)), - "weekday"=>self::format("l",$timestamp), - "month"=>self::format("F",$timestamp), - ); - } static function div($a,$b) {return (int) ($a / $b);} static function jalali_to_gregorian($j_y, $j_m, $j_d){ $g_days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); diff --git a/packages/base/libraries/db/MysqliDb.php b/packages/base/libraries/db/MysqliDb.php index d8952ae..f071d4d 100644 --- a/packages/base/libraries/db/MysqliDb.php +++ b/packages/base/libraries/db/MysqliDb.php @@ -191,6 +191,8 @@ class MysqliDb */ protected $_lockInShareMode = false; + protected $_transaction_in_progress = false; + /** * Key field for Map()'ed result array * @var string @@ -387,6 +389,8 @@ protected function reset() $this->_lastInsertId = null; $this->_updateColumns = null; $this->_mapKey = null; + + return $this; } /** @@ -970,7 +974,7 @@ public function joinWhere($whereJoin, $whereProp, $whereValue = 'DBNULL', $opera * * @return dbWrapper */ - public function joinOrWhere($whereJoin, $whereProp, $whereValue = 'DBNULL', $operator = '=', $cond = 'AND') + public function joinOrWhere($whereJoin, $whereProp, $whereValue = 'DBNULL', $operator = '=') { return $this->joinWhere($whereJoin, $whereProp, $whereValue, $operator, 'OR'); } @@ -1997,7 +2001,7 @@ public function startTransaction() * @uses mysqli->commit(); * @uses mysqli->autocommit(true); */ - public function commit() + public function commit(): bool { $result = $this->mysqli()->commit(); $this->_transaction_in_progress = false; @@ -2011,7 +2015,7 @@ public function commit() * @uses mysqli->rollback(); * @uses mysqli->autocommit(true); */ - public function rollback() + public function rollback(): bool { $result = $this->mysqli()->rollback(); $this->_transaction_in_progress = false; diff --git a/packages/base/libraries/db/db.php b/packages/base/libraries/db/db.php index e0e1bf2..524b61b 100644 --- a/packages/base/libraries/db/db.php +++ b/packages/base/libraries/db/db.php @@ -1,141 +1,91 @@ jsonBuilder(); - } - } - /** - * Helper function to create dbObject with array return type - * Added for consistency as thats default output type - * - */ - static function arrayBuilder(){ - if(self::has_connection()){ - return self::connection()->arrayBuilder(); - } - } - - /** - * Method to set a prefix - * - * @param string $prefix Contains a tableprefix - * - */ - static function setPrefix($prefix = ''){ - if(self::has_connection()){ - return self::connection()->setPrefix($prefix); - } - } +namespace packages\base; - /** - * Execute raw SQL query. - * - * @param string $query User-provided query to execute. - * @param array $bindParams Variables array to bind to the SQL statement. - * - * @return array Contains the returned rows from the query. - */ - static function rawQuery($query, $bindParams = null){ - if(self::has_connection()){ - return self::connection()->rawQuery($query, $bindParams); - } - } +use packages\base\db\MysqliDb; + +/** + * @method static MysqliDb jsonBuilder() + * @method static MysqliDb arrayBuilder() + * @method static MysqliDb setPrefix(string $prefix = '') + * @method static array rawQuery(string $query, ?array $bindParams = null) + * @method static array rawQueryOne(string $query, ?array $bindParams = null) + * @method static mixed rawQueryValue(string $query, ?array $bindParams = null) + * @method static array query(string $query, array|int|null $numRows = null) + * @method static MysqliDb setQueryOption(string|array $options) + * @method static MysqliDb withTotalCount() + * @method static array get(string $tableName, int|array|null $numRows = null, string|array $columns = '*') + * @method static array getOne(string $tableName, string|array $columns = '*') + * @method static mixed getValue(string $tableName, string $column, int $limit = 1) + * @method static bool insert(string $tableName, array $insertData) + * @method static bool insertMulti(string $tableName, array $multiInsertData) + * @method static bool replace(string $tableName, array $insertData) + * @method static bool has(string $tableName) + * @method static bool update(string $tableName, array $tableData, ?int $numRows = null) + * @method static bool delete(string $tableName, int|array|null $numRows = null) + * @method static MysqliDb where(string $whereProp, mixed $whereValue = 'DBNULL', string $operator = '=', string $cond = 'AND') + * @method static MysqliDb onDuplicate(array $updateColumns, ?string $lastInsertId = null) + * @method static MysqliDb orWhere(string $whereProp, mixed $whereValue = 'DBNULL', string $operator = '=') + * @method static MysqliDb having(string $havingProp, mixed $havingValue = 'DBNULL', string $operator = '=', string $cond = 'AND') + * @method static MysqliDb orHaving(string $havingProp, mixed $havingValue = null, string $operator = null) + * @method static MysqliDb join(string $joinTable, string $joinCondition, string $joinType = '') + * @method static MysqliDb joinWhere(string $whereJoin, string $whereProp, mixed $whereValue = 'DBNULL', string $operator = '=', string $cond = 'AND') + * @method static MysqliDb joinOrWhere(string $whereJoin, string $whereProp, mixed $whereValue = 'DBNULL', string $operator = '=') + * @method static MysqliDb orderBy(string $orderByField, string $orderbyDirection = "DESC", ?array $customFields = null) + * @method static MysqliDb groupBy(string $groupByField) + * @method static int getInsertId() + * @method static bool ping() + * @method static string getLastQuery() + * @method static string getLastError() + * @method static array getSubQuery() + * @method static string interval(string $diff, string $func = "NOW()") + * @method static array now(string $diff = null, string $func = "NOW()") + * @method static array inc(int $num = 1) + * @method static array dec(int $num = 1) + * @method static array not(?string $col = null) + * @method static MysqliDb subQuery(string $subQueryAlias = "") + * @method static startTransaction() + * @method static bool commit() + * @method static bool rollback() + * @method static _transaction_status_check() + * @method static array tables() + * @method static bool tableExists(string|array $tables) + * @method static MysqliDb map(string $idField) + * @method static array paginate(string $table, int $page, array|string|null $fields = null) + */ +class DB +{ + /** @var array $driver */ + private static $driver = array(); - /** - * Helper function to execute raw SQL query and return only 1 row of results. - * Note that function do not add 'limit 1' to the query by itself - * Same idea as getOne() - * - * @param string $query User-provided query to execute. - * @param array $bindParams Variables array to bind to the SQL statement. - * - * @return array|null Contains the returned row from the query. - */ - static function rawQueryOne($query, $bindParams = null){ - if(self::has_connection()){ - return self::connection()->rawQueryOne($query, $bindParams); - } - } - /** - * Helper function to execute raw SQL query and return only 1 column of results. - * If 'limit 1' will be found, then string will be returned instead of array - * Same idea as getValue() - * - * @param string $query User-provided query to execute. - * @param array $bindParams Variables array to bind to the SQL statement. - * - * @return mixed Contains the returned rows from the query. - */ - static function rawQueryValue($query, $bindParams = null){ - if(self::has_connection()){ - return self::connection()->rawQueryValue($query, $bindParams); - } + public static function connect($conname, $host, $username, $db = null, $password = null, $port = null, $charset = 'utf8mb4'): void + { + self::$driver[$conname] = new MysqliDb($host, $username, $password, $db, $port, $charset); } - /** - * A method to perform select query - * - * @param string $query Contains a user-provided select query. - * @param int|array $numRows Array to define SQL limit in format Array ($count, $offset) - * - * @return array Contains the returned rows from the query. - */ - static function query($query, $numRows = null){ - if(self::has_connection()){ - return self::connection()->query($query, $numRows); + public static function has_connection($conname = 'default'): bool + { + if (!isset(self::$driver[$conname])) { + Loader::connectdb(); } + return isset(self::$driver[$conname]); } - /** - * This method allows you to specify multiple (method chaining optional) options for SQL queries. - * - * @uses $MySqliDb->setQueryOption('name'); - * - * @param string|array $options The optons name of the query. - * - * @throws Exception - * @return MysqliDb - */ - static function setQueryOption($options){ - if(self::has_connection()){ - return self::connection()->setQueryOption($options); + public static function connection($conname = 'default'): MysqliDb|false + { + if (self::has_connection($conname)) { + return self::$driver[$conname]; } + return false; } - /** - * Function to enable SQL_CALC_FOUND_ROWS in the get queries - * - * @return MysqliDb - */ - static function withTotalCount(){ - if(self::has_connection()){ - return self::connection()->withTotalCount(); + public static function getConnectionOrFail($conname = 'default'): MysqliDb + { + $connection = self::connection($conname); + if (!$connection) { + throw new db\DatabaseException("connection [{$conname}] does not exists!"); } + return $connection; } /** @@ -143,615 +93,18 @@ static function withTotalCount(){ * * @return int */ - static function totalCount(){ - if(self::has_connection()){ - return self::connection()->totalCount; - } - } - - /** - * A convenient SELECT * function. - * - * @param string $tableName The name of the database table to work with. - * @param int|array $numRows Array to define SQL limit in format Array ($count, $offset) - * or only $count - * @param string $columns Desired columns - * - * @return array Contains the returned rows from the select query. - */ - static function get($tableName, $numRows = null, $columns = '*'){ - if(self::has_connection()){ - return self::connection()->get($tableName, $numRows, $columns); - } - } - - /** - * A convenient SELECT * function to get one record. - * - * @param string $tableName The name of the database table to work with. - * @param string $columns Desired columns - * - * @return array Contains the returned rows from the select query. - */ - static function getOne($tableName, $columns = '*'){ - if(self::has_connection()){ - return self::connection()->getOne($tableName, $columns); - } - } - - /** - * A convenient SELECT COLUMN function to get a single column value from one row - * - * @param string $tableName The name of the database table to work with. - * @param string $column The desired column - * @param int $limit Limit of rows to select. Use null for unlimited..1 by default - * - * @return mixed Contains the value of a returned column / array of values - */ - static function getValue($tableName, $column, $limit = 1){ - if(self::has_connection()){ - return self::connection()->getValue($tableName, $column, $limit); - } - } - - /** - * Insert method to add new row - * - * @param string $tableName The name of the table. - * @param array $insertData Data containing information for inserting into the DB. - * - * @return bool Boolean indicating whether the insert query was completed succesfully. - */ - static function insert(string $tableName, array $insertData){ - if(self::has_connection()){ - return self::connection()->insert($tableName, $insertData); - } - } - /** - * Insert method to add new row - * - * @param string $tableName The name of the table. - * @param array $multiInsertData Two-dimensinal Data-array containing information for inserting into the DB. - * - * @return bool Boolean indicating the insertion failed (false), else return last id inserted id - */ - static function insertMulti(string $tableName, array $multiInsertData){ - if(self::has_connection()){ - return self::connection()->insertMulti($tableName, $multiInsertData); - } + public static function totalCount(): int + { + return self::getConnectionOrFail()->totalCount; } - /** - * Replace method to add new row - * - * @param string $tableName The name of the table. - * @param array $insertData Data containing information for inserting into the DB. - * - * @return bool Boolean indicating whether the insert query was completed succesfully. - */ - static function replace($tableName, $insertData){ - if(self::has_connection()){ - return self::connection()->replace($tableName, $insertData); - } + public static function pageLimit($limit): void + { + self::getConnectionOrFail()->pageLimit = $limit; } - /** - * A convenient function that returns TRUE if exists at least an element that - * satisfy the where condition specified calling the "where" method before this one. - * - * @param string $tableName The name of the database table to work with. - * - * @return array Contains the returned rows from the select query. - */ - static function has($tableName){ - if(self::has_connection()){ - return self::connection()->has($tableName); - } - } - - /** - * Update query. Be sure to first call the "where" method. - * - * @param string $tableName The name of the database table to work with. - * @param array $tableData Array of data to update the desired row. - * @param int $numRows Limit on the number of rows that can be updated. - * - * @return bool - */ - static function update($tableName, $tableData, $numRows = null){ - if(self::has_connection()){ - return self::connection()->update($tableName, $tableData, $numRows); - } - } - - /** - * Delete query. Call the "where" method first. - * - * @param string $tableName The name of the database table to work with. - * @param int|array $numRows Array to define SQL limit in format Array ($count, $offset) - * or only $count - * - * @return bool Indicates success. 0 or 1. - */ - static function delete($tableName, $numRows = null){ - if(self::has_connection()){ - return self::connection()->delete($tableName, $numRows); - } - } - - /** - * This method allows you to specify multiple (method chaining optional) AND WHERE statements for SQL queries. - * - * @uses $MySqliDb->where('id', 7)->where('title', 'MyTitle'); - * - * @param string $whereProp The name of the database field. - * @param mixed $whereValue The value of the database field. - * @param string $operator Comparison operator. Default is = - * @param string $cond Condition of where statement (OR, AND) - * - * @return MysqliDb - */ - static function where($whereProp, $whereValue = 'DBNULL', $operator = '=', $cond = 'AND'){ - if(self::has_connection()){ - return self::connection()->where($whereProp, $whereValue, $operator, $cond); - } - } - - /** - * This function store update column's name and column name of the - * autoincrement column - * - * @param array $updateColumns Variable with values - * @param string $lastInsertId Variable value - * - * @return MysqliDb - */ - static function onDuplicate($updateColumns, $lastInsertId = null){ - if(self::has_connection()){ - return self::connection()->onDuplicate($updateColumns, $lastInsertId); - } - } - - /** - * This method allows you to specify multiple (method chaining optional) OR WHERE statements for SQL queries. - * - * @uses $MySqliDb->orWhere('id', 7)->orWhere('title', 'MyTitle'); - * - * @param string $whereProp The name of the database field. - * @param mixed $whereValue The value of the database field. - * @param string $operator Comparison operator. Default is = - * - * @return MysqliDb - */ - static function orWhere($whereProp, $whereValue = 'DBNULL', $operator = '='){ - if(self::has_connection()){ - return self::connection()->orWhere($whereProp, $whereValue, $operator); - } - } - - /** - * This method allows you to specify multiple (method chaining optional) AND HAVING statements for SQL queries. - * - * @uses $MySqliDb->having('SUM(tags) > 10') - * - * @param string $havingProp The name of the database field. - * @param mixed $havingValue The value of the database field. - * @param string $operator Comparison operator. Default is = - * - * @return MysqliDb - */ - - static function having($havingProp, $havingValue = 'DBNULL', $operator = '=', $cond = 'AND'){ - if(self::has_connection()){ - return self::connection()->having($havingProp, $havingValue, $operator, $cond); - } - } - - /** - * This method allows you to specify multiple (method chaining optional) OR HAVING statements for SQL queries. - * - * @uses $MySqliDb->orHaving('SUM(tags) > 10') - * - * @param string $havingProp The name of the database field. - * @param mixed $havingValue The value of the database field. - * @param string $operator Comparison operator. Default is = - * - * @return MysqliDb - */ - static function orHaving($havingProp, $havingValue = null, $operator = null){ - if(self::has_connection()){ - return self::connection()->orHaving($havingProp, $havingValue, $operator); - } - } - - /** - * This method allows you to concatenate joins for the final SQL statement. - * - * @uses $MySqliDb->join('table1', 'field1 <> field2', 'LEFT') - * - * @param string $joinTable The name of the table. - * @param string $joinCondition the condition. - * @param string $joinType 'LEFT', 'INNER' etc. - * - * @throws Exception - * @return MysqliDb - */ - static function join($joinTable, $joinCondition, $joinType = ''){ - if(self::has_connection()){ - return self::connection()->join($joinTable, $joinCondition, $joinType); - } - } - /** - * This method allows you to specify multiple (method chaining optional) AND WHERE statements for the join table on part of the SQL query. - * - * @uses $dbWrapper->joinWhere('user u', 'u.id', 7)->where('user u', 'u.title', 'MyTitle'); - * - * @param string $whereJoin The name of the table followed by its prefix. - * @param string $whereProp The name of the database field. - * @param mixed $whereValue The value of the database field. - * - * @return MysqliDb - */ - public static function joinWhere($whereJoin, $whereProp, $whereValue = 'DBNULL', $operator = '=', $cond = 'AND') - { - if(self::has_connection()){ - return self::connection()->joinWhere($whereJoin, $whereProp, $whereValue, $operator, $cond); - } - } - - /** - * This method allows you to specify multiple (method chaining optional) OR WHERE statements for the join table on part of the SQL query. - * - * @uses $dbWrapper->joinWhere('user u', 'u.id', 7)->where('user u', 'u.title', 'MyTitle'); - * - * @param string $whereJoin The name of the table followed by its prefix. - * @param string $whereProp The name of the database field. - * @param mixed $whereValue The value of the database field. - * - * @return MysqliDb - */ - public static function joinOrWhere($whereJoin, $whereProp, $whereValue = 'DBNULL', $operator = '=') - { - if(self::has_connection()){ - return self::connection()->joinOrWhere($whereJoin, $whereProp, $whereValue, $operator); - } - } - /** - * This method allows you to specify multiple (method chaining optional) ORDER BY statements for SQL queries. - * - * @uses $MySqliDb->orderBy('id', 'desc')->orderBy('name', 'desc'); - * - * @param string $orderByField The name of the database field. - * @param string $orderByDirection Order direction. - * @param array $customFields Fieldset for ORDER BY FIELD() ordering - * - * @throws Exception - * @return MysqliDb - */ - static function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null){ - if(self::has_connection()){ - return self::connection()->orderBy($orderByField, $orderbyDirection, $customFields); - } - } - - /** - * This method allows you to specify multiple (method chaining optional) GROUP BY statements for SQL queries. - * - * @uses $MySqliDb->groupBy('name'); - * - * @param string $groupByField The name of the database field. - * - * @return MysqliDb - */ - static function groupBy($groupByField){ - if(self::has_connection()){ - return self::connection()->groupBy($groupByField); - } - } - - /** - * This methods returns the ID of the last inserted item - * - * @return int The last inserted item ID. - */ - static function getInsertId(){ - if(self::has_connection()){ - return self::connection()->getInsertId(); - } - } - - /** - * Escape harmful characters which might affect a query. - * - * @param string $str The string to escape. - * - * @return string The escaped string. - */ - static function escape($str){ - if(self::has_connection()){ - return self::connection()->escape($str); - } - } - - /** - * Method to call mysqli->ping() to keep unused connections open on - * long-running scripts, or to reconnect timed out connections (if php.ini has - * global mysqli.reconnect set to true). Can't do this directly using object - * since _mysqli is protected. - * - * @return bool True if connection is up - */ - static function ping(){ - if(self::has_connection()){ - return self::connection()->ping(); - } - } - - /** - * Method returns last executed query - * - * @return string - */ - static function getLastQuery(){ - if(self::has_connection()){ - return self::connection()->getLastQuery(); - } - } - - /** - * Method returns mysql error - * - * @return string - */ - static function getLastError(){ - if(self::has_connection()){ - return self::connection()->getLastError(); - } - } - - /** - * Method returns mysql error code - * @return int - */ - static function getLastErrno () { - if(self::has_connection()){ - return self::connection()->getLastErrno(); - } - } - - /** - * Mostly internal method to get query and its params out of subquery object - * after get() and getAll() - * - * @return array - */ - static function getSubQuery(){ - if(self::has_connection()){ - return self::connection()->getSubQuery(); - } - } - - /* Helper functions */ - - /** - * Method returns generated interval function as a string - * - * @param string $diff interval in the formats: - * "1", "-1d" or "- 1 day" -- For interval - 1 day - * Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear - * Default null; - * @param string $func Initial date - * - * @return string - */ - static function interval($diff, $func = "NOW()"){ - if(self::has_connection()){ - return self::connection()->interval($diff, $func); - } - } - - /** - * Method returns generated interval function as an insert/update function - * - * @param string $diff interval in the formats: - * "1", "-1d" or "- 1 day" -- For interval - 1 day - * Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear - * Default null; - * @param string $func Initial date - * - * @return array - */ - static function now($diff = null, $func = "NOW()"){ - if(self::has_connection()){ - return self::connection()->now($diff, $func); - } - } - - /** - * Method generates incremental function call - * - * @param int $num increment by int or float. 1 by default - * - * @throws Exception - * @return array - */ - static function inc($num = 1){ - if(self::has_connection()){ - return self::connection()->inc($num); - } - } - - /** - * Method generates decrimental function call - * - * @param int $num increment by int or float. 1 by default - * - * @return array - */ - static function dec($num = 1){ - if(self::has_connection()){ - return self::connection()->dec($num); - } - } - - /** - * Method generates change boolean function call - * - * @param string $col column name. null by default - * - * @return array - */ - static function not($col = null){ - if(self::has_connection()){ - return self::connection()->not($col); - } - } - - /** - * Method generates user defined function call - * - * @param string $expr user function body - * @param array $bindParams - * - * @return array - */ - static function func($expr, $bindParams = null){ - if(self::has_connection()){ - return self::connection()->func($expr, $bindParams); - } - } - - /** - * Method creates new mysqlidb object for a subquery generation - * - * @param string $subQueryAlias - * - * @return MysqliDb - */ - static function subQuery($subQueryAlias = ""){ - if(self::has_connection()){ - return self::connection()->subQuery($subQueryAlias); - } - } - - /** - * Method returns a copy of a mysqlidb subquery object - * - * @return MysqliDb new mysqlidb object - */ - static function copy(){ - if(self::has_connection()){ - return self::connection()->copy(); - } - } - - /** - * Begin a transaction - * - * @uses mysqli->autocommit(false) - * @uses register_shutdown_function(array($this, "_transaction_shutdown_check")) - */ - static function startTransaction(){ - if(self::has_connection()){ - return self::connection()->startTransaction(); - } - } - - /** - * Transaction commit - * - * @uses mysqli->commit(); - * @uses mysqli->autocommit(true); - */ - static function commit(){ - if(self::has_connection()){ - return self::connection()->commit(); - } - } - - /** - * Transaction rollback function - * - * @uses mysqli->rollback(); - * @uses mysqli->autocommit(true); - */ - static function rollback(){ - if(self::has_connection()){ - return self::connection()->rollback(); - } - } - - /** - * Shutdown handler to rollback uncommited operations in order to keep - * atomic operations sane. - * - * @uses mysqli->rollback(); - */ - static function _transaction_status_check(){ - if(self::has_connection()){ - return self::connection()->_transaction_status_check(); - } - } - - /** - * Query exection time tracking switch - * - * @param bool $enabled Enable execution time tracking - * @param string $stripPrefix Prefix to strip from the path in exec log - * - * @return MysqliDb - */ - static function setTrace($enabled, $stripPrefix = null){ - if(self::has_connection()){ - return self::connection()->setTrace($enabled, $stripPrefix); - } - } - /** - * Method to check if needed table is created - * - * @param array $tables Table name or an Array of table names to check - * - * @return bool True if table exists - */ - static function tableExists($tables){ - if(self::has_connection()){ - return self::connection()->tableExists($tables); - } - } - - /** - * Return result as an associative array with $idField field value used as a record key - * - * Array Returns an array($k => $v) if get(.."param1, param2"), array ($k => array ($v, $v)) otherwise - * - * @param string $idField field name to use for a mapped element key - * - * @return MysqliDb - */ - static function map($idField){ - if(self::has_connection()){ - return self::connection()->map($idField); - } - } - - static function pageLimit ($limit) { - if(self::has_connection()){ - return self::connection()->pageLimit = $limit; - } - } - /** - * Pagination wraper to get() - * - * @access public - * @param string $table The name of the database table to work with - * @param int $page Page number - * @param array|string $fields Array or coma separated list of fields to fetch - * @return array - */ - static function paginate ($table, $page, $fields = null) { - if(self::has_connection()){ - return self::connection()->paginate($table,$page, $fields); - } + public static function __callStatic(string $method, array $arguments) + { + return call_user_func_array([self::getConnectionOrFail(), $method], $arguments); } } -?> diff --git a/packages/base/libraries/db/dbObject.php b/packages/base/libraries/db/dbObject.php index fb4c751..23dafd9 100644 --- a/packages/base/libraries/db/dbObject.php +++ b/packages/base/libraries/db/dbObject.php @@ -69,7 +69,7 @@ * * @property int|null $totalCount **/ -class dbObject implements IValidator { +class DBObject implements IValidator { private $connection = 'default'; /** * Working instance of MysqliDb created earlier @@ -229,10 +229,13 @@ public function __get ($name) { } } public function __isset ($name) { - if (isset ($this->data[$name])) + if (isset ($this->data[$name])) { return isset ($this->data[$name]); - if (property_exists ($this->db, $name)) + } + if (property_exists ($this->db, $name)) { return isset ($this->db->$name); + } + return false; } public function __unset ($name) { unset ($this->data[$name]); diff --git a/packages/base/libraries/frontend/Source.php b/packages/base/libraries/frontend/Source.php index b905b1c..abd1f0d 100644 --- a/packages/base/libraries/frontend/Source.php +++ b/packages/base/libraries/frontend/Source.php @@ -11,8 +11,7 @@ class Source { /** * construct a theme from its package.json - * - * @param packages\base\IO\directory $home + * * @throws packages\base\IO\NotFoundException if cannot find theme.json in the home directory * @throws packages\base\IO\SourceConfigException if source doesn't have name * @throws packages\base\IO\SourceConfigException if event listener was invalid @@ -66,7 +65,7 @@ public static function fromDirectory(IO\directory $home): Source { return $source; } - /** @var packages\base\IO\directory */ + /** @var \packages\base\IO\Directory */ private $home; /** @var string */ @@ -78,6 +77,9 @@ public static function fromDirectory(IO\directory $home): Source { /** @var packages\base\IO\file|null */ private $bootstrap; + /** @var array */ + private $views = []; + /** @var array */ private $assets = []; @@ -86,10 +88,9 @@ public static function fromDirectory(IO\directory $home): Source { /** * Get home directory of source. - * - * @return IO\directory + * */ - public function getHome(): IO\directory{ + public function getHome(): IO\Directory { return $this->home; } @@ -103,19 +104,17 @@ public function getPath(): string { } /** * Get file - * - * @return packages\base\IO\file + * */ - public function getFile(string $path): IO\file { + public function getFile(string $path): IO\File { return $this->home->file($path); } /** * Get theme.json file - * - * @return packages\base\IO\file + * */ - public function getConfigFile(): IO\file { + public function getConfigFile(): IO\File { return $this->getFile("theme.json"); } @@ -169,7 +168,7 @@ public function addAsset(array $asset): void { $this->addNodePackageAsset($asset); break; default: - throw new SourceAssetException("Unkown asset type", $this->path); + throw new SourceAssetException("Unkown asset type", $this->getPath()); } } @@ -199,7 +198,7 @@ private function addCodeAsset(array $asset): void { } elseif (isset($asset['inline'])) { $assetData['inline'] = $asset['inline']; } else { - throw new SourceAssetException("No file and no Code for asset",$this->path); + throw new SourceAssetException("No file and no Code for asset", $this->getPath()); } $this->assets[] = $assetData; } @@ -214,11 +213,11 @@ private function addCodeAsset(array $asset): void { */ private function addNodePackageAsset(array $asset): void { if (!isset($asset['name'])) { - throw new SourceAssetException("No node package name",$this->path); + throw new SourceAssetException("No node package name",$this->getPath()); } if (isset($asset['version'])) { if (!preg_match("/^[\^\>\=\~\<\*]*[\\d\\w\\.\\-]+$/", $asset['version'])) { - throw new SourceAssetException("invalid node package version",$this->path); + throw new SourceAssetException("invalid node package version",$this->getPath()); } } $this->assets[] = $asset; @@ -283,7 +282,7 @@ public function url(string $file, bool $absolute = false): string { /**3 */ public function addView($view){ if(isset($view['name'])){ - if(!isset($view['file']) or is_file("{$this->path}/{$view['file']}")){ + if(!isset($view['file']) or is_file("{$this->getPath()}/{$view['file']}")){ if(substr($view['name'], 0, 1) == "\\"){ $view['name'] = substr($view['name'], 1); } @@ -302,10 +301,10 @@ public function addView($view){ $this->views[] = $newview; }else{ - throw new SourceViewFileException($view['file'], $this->path); + throw new SourceViewFileException($view['file'], $this->getPath()); } }else{ - throw new SourceViewException("View name is not set", $this->path); + throw new SourceViewException("View name is not set", $this->getPath()); } } diff --git a/packages/base/libraries/frontend/theme.php b/packages/base/libraries/frontend/theme.php index 3ba737a..f2ef525 100644 --- a/packages/base/libraries/frontend/theme.php +++ b/packages/base/libraries/frontend/theme.php @@ -1,6 +1,8 @@ hostname){ $this->hostname = $this->getDriver()->getHostname(); } @@ -257,7 +257,7 @@ public function serialize(){ if(!$this->password){ $this->password = $this->getDriver()->getPassword(); } - $data = array( + return array( 'directory' => $this->directory, 'basename' => $this->basename, 'hostname' => $this->hostname, @@ -265,15 +265,13 @@ public function serialize(){ 'username' => $this->username, 'password' => $this->password ); - return serialize($data); - } - public function unserialize($data){ - $data = unserialize($data); - $this->directory = isset($data['directory']) ? $data['directory'] : null; - $this->basename = isset($data['basename']) ? $data['basename'] : null; - $this->hostname = isset($data['hostname']) ? $data['hostname'] : null; - $this->port = isset($data['port']) ? $data['port'] : 21; - $this->username = isset($data['username']) ? $data['username'] : null; - $this->password = isset($data['password']) ? $data['password'] : null; + } + public function __unserialize(array $data): void { + $this->directory = $data['directory'] ?? null; + $this->basename = $data['basename'] ?? null; + $this->hostname = $data['hostname'] ?? null; + $this->port = $data['port'] ?? 21; + $this->username = $data['username'] ?? null; + $this->password = $data['password'] ?? null; } } diff --git a/packages/base/libraries/io/directory/sftp.php b/packages/base/libraries/io/directory/sftp.php index cac93b4..1bd04a4 100644 --- a/packages/base/libraries/io/directory/sftp.php +++ b/packages/base/libraries/io/directory/sftp.php @@ -162,7 +162,7 @@ public function getDirectory():directory\sftp{ $directory->setDriver($this->getDriver()); return $directory; } - public function serialize(){ + public function __serialize(): array { if(!$this->hostname){ $this->hostname = $this->getDriver()->getSSH()->getHost(); } @@ -175,7 +175,7 @@ public function serialize(){ if(!$this->password){ $this->password = $this->getDriver()->getSSH()->getPassword(); } - $data = array( + return array( 'directory' => $this->directory, 'basename' => $this->basename, 'hostname' => $this->hostname, @@ -183,15 +183,14 @@ public function serialize(){ 'username' => $this->username, 'password' => $this->password ); - return serialize($data); - } - public function unserialize($data){ - $data = unserialize($data); - $this->directory = isset($data['directory']) ? $data['directory'] : null; - $this->basename = isset($data['basename']) ? $data['basename'] : null; - $this->hostname = isset($data['hostname']) ? $data['hostname'] : null; - $this->port = isset($data['port']) ? $data['port'] : 21; - $this->username = isset($data['username']) ? $data['username'] : null; - $this->password = isset($data['password']) ? $data['password'] : null; + } + + public function __unserialize(array $data): void { + $this->directory = $data['directory'] ?? null; + $this->basename = $data['basename'] ?? null; + $this->hostname = $data['hostname'] ?? null; + $this->port = $data['port'] ?? 21; + $this->username = $data['username'] ?? null; + $this->password = $data['password'] ?? null; } } \ No newline at end of file diff --git a/packages/base/libraries/mvc/FormError.php b/packages/base/libraries/mvc/FormError.php index 67aeb5c..30ca6b7 100644 --- a/packages/base/libraries/mvc/FormError.php +++ b/packages/base/libraries/mvc/FormError.php @@ -59,7 +59,7 @@ public function getInput(): ?string { * * @return mixed */ - public function jsonSerialize() { + public function jsonSerialize(): array { $data = parent::jsonSerialize(); if ($this->input) { $data['input'] = $this->input; diff --git a/packages/base/libraries/router/PathException.php b/packages/base/libraries/router/PathException.php index 47e1b24..e90b20f 100644 --- a/packages/base/libraries/router/PathException.php +++ b/packages/base/libraries/router/PathException.php @@ -2,16 +2,8 @@ namespace packages\base\router; class PathException extends RouterRuleException { - /** @var mixed wrong path */ - private $path; - - /** - * @param mixed $path - * @param string $message - */ - public function __construct($path, string $message){ - $this->path = $path; - parent::__construct($message); + public function __construct(Rule $rule, private mixed $path, string $message) { + parent::__construct($rule, $message); } /** diff --git a/packages/base/libraries/router/RuleException.php b/packages/base/libraries/router/RuleException.php index 608e7d0..484aef0 100644 --- a/packages/base/libraries/router/RuleException.php +++ b/packages/base/libraries/router/RuleException.php @@ -5,22 +5,11 @@ class RuleException extends Exception { - - /** - * @param packages\base\router\rule $rule - * @param string $message - */ - public function __construct(rule $rule, string $message = ""){ + public function __construct(protected Rule $rule, string $message = ""){ parent::__construct($message); - $this->rule = $rule; } - /** - * Getter for rule - * - * @return packages\base\router\rule - */ - public function getRule(): rule { + public function getRule(): Rule { return $this->rule; } } \ No newline at end of file diff --git a/packages/base/libraries/router/exceptions.php b/packages/base/libraries/router/exceptions.php index 34b8c35..531d0bf 100644 --- a/packages/base/libraries/router/exceptions.php +++ b/packages/base/libraries/router/exceptions.php @@ -13,14 +13,14 @@ public function getMiddleware(){ } class RouterRuleException extends Exception { - /** @var packages\base\router\rule */ + /** @var \packages\base\router\Rule */ private $rule; /** - * @param packages\base\router\rule $rule + * @param \packages\base\router\Rule $rule * @param string $message */ - public function __construct(rule $rule, string $message = ""){ + public function __construct(Rule $rule, string $message = ""){ parent::__construct($message); $this->rule = $rule; } @@ -28,9 +28,9 @@ public function __construct(rule $rule, string $message = ""){ /** * Getter for rule * - * @return packages\base\router\rule + * @return \packages\base\router\rule */ - public function getRule(): rule { + public function getRule(): Rule { return $this->rule; } } diff --git a/packages/base/libraries/router/rule.php b/packages/base/libraries/router/rule.php index 187f14c..4484ea0 100644 --- a/packages/base/libraries/router/rule.php +++ b/packages/base/libraries/router/rule.php @@ -277,7 +277,7 @@ public function setPath($path): void { if (is_string($path)){ $path = explode("/", $path); } elseif (!is_array($path)) { - throw new PathException($path); + throw new PathException($this, $path, 'path must be string or array'); } $this->path = array(); $this->wildcards = 0; @@ -382,7 +382,7 @@ public function addScheme(string $scheme): void { return; } if (!in_array($scheme, array(self::http, self::https))) { - throw new SchemeException(); + throw new SchemeException($this); } $this->schemes[] = $scheme; } @@ -397,7 +397,7 @@ public function addScheme(string $scheme): void { public function addDomain(string $domain): void { if (substr($domain, 1) == "/" and substr($domain, -1) == "/") { if (@preg_match($domain, null) === false) { - throw new DomainException(); + throw new DomainException($this); } } elseif(substr($domain, 0, 4) == 'www.'){ $domain = substr($domain, 4); diff --git a/packages/base/libraries/translator/translator.php b/packages/base/libraries/translator/translator.php index fd1aaa6..e7b06dd 100644 --- a/packages/base/libraries/translator/translator.php +++ b/packages/base/libraries/translator/translator.php @@ -98,7 +98,7 @@ public static function import(language $lang){ foreach($phrases as $key => $phrase){ self::$langs[$code]->addPhrase($key, $phrase); } - }catch(PhraseAlreadyExists $e){ + }catch(translator\PhraseAlreadyExists $e){ } } diff --git a/packages/base/libraries/utility/password.php b/packages/base/libraries/utility/password.php index 6e9e456..4a8f755 100644 --- a/packages/base/libraries/utility/password.php +++ b/packages/base/libraries/utility/password.php @@ -1,12 +1,8 @@