From 1d583bcc23524ad8840e4be580e549e8d6e549f4 Mon Sep 17 00:00:00 2001 From: Timothy J Warren Date: Wed, 24 Jan 2018 13:14:03 -0500 Subject: [PATCH] Add more type hinting --- src/ConnectionManager.php | 1 + src/Drivers/AbstractDriver.php | 63 ++++--- src/Drivers/AbstractSQL.php | 2 +- src/Drivers/AbstractUtil.php | 2 +- src/Drivers/DriverInterface.php | 50 +++--- src/Drivers/Mysql/Driver.php | 5 +- src/Drivers/Mysql/SQL.php | 36 ++-- src/Drivers/Mysql/Util.php | 2 + src/Drivers/PDOStatementInterface.php | 175 ------------------- src/Drivers/Pgsql/Driver.php | 3 +- src/Drivers/Pgsql/SQL.php | 32 ++-- src/Drivers/SQLInterface.php | 34 ++-- src/Drivers/Sqlite/Driver.php | 19 +-- src/Drivers/Sqlite/SQL.php | 36 ++-- src/QueryBuilder.php | 15 +- src/State.php | 28 ++-- src/common.php | 213 ++++++++++-------------- tests/CoreTest.php | 10 ++ tests/Drivers/MySQL/MySQLDriverTest.php | 4 +- tests/Drivers/PgSQL/PgSQLDriverTest.php | 3 +- 20 files changed, 258 insertions(+), 475 deletions(-) delete mode 100644 src/Drivers/PDOStatementInterface.php diff --git a/src/ConnectionManager.php b/src/ConnectionManager.php index 389f740..e191952 100644 --- a/src/ConnectionManager.php +++ b/src/ConnectionManager.php @@ -200,6 +200,7 @@ final class ConnectionManager { /** * Create the dsn from the db type and params * + * @codeCoverageIgnore * @param string $dbtype * @param \stdClass $params * @return string diff --git a/src/Drivers/AbstractDriver.php b/src/Drivers/AbstractDriver.php index 38a7fde..4ababcb 100644 --- a/src/Drivers/AbstractDriver.php +++ b/src/Drivers/AbstractDriver.php @@ -83,7 +83,7 @@ abstract class AbstractDriver * @param string $password * @param array $driverOptions */ - public function __construct($dsn, $username=NULL, $password=NULL, array $driverOptions=[]) + public function __construct(string $dsn, string $username=NULL, string $password=NULL, array $driverOptions=[]) { // Set PDO to display errors as exceptions, and apply driver options $driverOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; @@ -182,7 +182,7 @@ abstract class AbstractDriver * @param string $prefix * @return void */ - public function setTablePrefix($prefix) + public function setTablePrefix(string $prefix): void { $this->tablePrefix = $prefix; } @@ -199,16 +199,11 @@ abstract class AbstractDriver * @return PDOStatement | FALSE * @throws InvalidArgumentException */ - public function prepareQuery($sql, $data) + public function prepareQuery(string $sql, array $data): ?PDOStatement { // Prepare the sql, save the statement for easy access later $this->statement = $this->prepare($sql); - if( ! (\is_array($data) || \is_object($data))) - { - throw new InvalidArgumentException('Data argument must be an object or associative array'); - } - // Bind the parameters foreach($data as $k => $value) { @@ -229,9 +224,10 @@ abstract class AbstractDriver * * @param string $sql * @param array $params + * @throws InvalidArgumentException * @return PDOStatement */ - public function prepareExecute($sql, $params): PDOStatement + public function prepareExecute(string $sql, array $params): ?PDOStatement { $this->statement = $this->prepareQuery($sql, $params); $this->statement->execute(); @@ -255,7 +251,7 @@ abstract class AbstractDriver * @param string $table * @return string */ - public function prefixTable($table): string + public function prefixTable(string $table): string { // Add the prefix to the table name // before quoting it @@ -502,7 +498,7 @@ abstract class AbstractDriver $flag = $filteredIndex ? PDO::FETCH_NUM : PDO::FETCH_ASSOC; $all = $res->fetchAll($flag); - return $filteredIndex ? \db_filter($all, 0) : $all; + return $filteredIndex ? \dbFilter($all, 0) : $all; } /** @@ -529,10 +525,10 @@ abstract class AbstractDriver * Create sql for batch insert * * @param string $table - * @param array|object $data + * @param mixed $data * @return null|array */ - public function insertBatch($table, $data=[]) + public function insertBatch(string $table, array $data=[]): array { $data = (array) $data; $firstRow = (array) current($data); @@ -570,12 +566,30 @@ abstract class AbstractDriver * @param string $where * @return int|null */ - public function updateBatch($table, $data, $where) + public function updateBatch(string $table, $data, $where) { // @TODO implement return NULL; } + /** + * Empty the passed table + * + * @param string $table + * @return PDOStatement + */ + public function truncate(string $table): PDOStatement + { + $sql = $this->hasTruncate + ? 'TRUNCATE TABLE ' + : 'DELETE FROM '; + + $sql .= $this->quoteTable($table); + + $this->statement = $this->query($sql); + return $this->statement; + } + /** * Helper method for quote_ident * @@ -603,7 +617,7 @@ abstract class AbstractDriver * @param string $str * @return string */ - protected function _prefix($str): string + protected function _prefix(string $str): string { // Don't prefix an already prefixed table if (strpos($str, $this->tablePrefix) !== FALSE) @@ -613,23 +627,4 @@ abstract class AbstractDriver return $this->tablePrefix . $str; } - - /** - * Empty the passed table - * - * @param string $table - * @return PDOStatement - */ - public function truncate($table): PDOStatement - { - $sql = $this->hasTruncate - ? 'TRUNCATE TABLE ' - : 'DELETE FROM '; - - $sql .= $this->quoteTable($table); - - $this->statement = $this->query($sql); - return $this->statement; - } - } \ No newline at end of file diff --git a/src/Drivers/AbstractSQL.php b/src/Drivers/AbstractSQL.php index 46f7503..d795d66 100644 --- a/src/Drivers/AbstractSQL.php +++ b/src/Drivers/AbstractSQL.php @@ -30,7 +30,7 @@ abstract class AbstractSQL implements SQLInterface { * @param int|bool $offset * @return string */ - public function limit($sql, $limit, $offset=FALSE) + public function limit(string $sql, int $limit, $offset=FALSE): string { $sql .= "\nLIMIT {$limit}"; diff --git a/src/Drivers/AbstractUtil.php b/src/Drivers/AbstractUtil.php index 0bcfa4d..d9e676d 100644 --- a/src/Drivers/AbstractUtil.php +++ b/src/Drivers/AbstractUtil.php @@ -67,7 +67,7 @@ abstract class AbstractUtil { // 'constraint' => ..., // 'index' => ..., // ) - $columnArray = \array_zipper([ + $columnArray = \arrayZipper([ 'type' => $fields, 'constraint' => $constraints ]); diff --git a/src/Drivers/DriverInterface.php b/src/Drivers/DriverInterface.php index f257f6a..aad7d0a 100644 --- a/src/Drivers/DriverInterface.php +++ b/src/Drivers/DriverInterface.php @@ -14,6 +14,8 @@ */ namespace Query\Drivers; +use PDOStatement; + /** * PDO Interface to implement for database drivers */ @@ -27,17 +29,17 @@ interface DriverInterface { * @param string $password * @param array $driverOptions */ - public function __construct($dsn, $username=NULL, $password=NULL, array $driverOptions = []); + public function __construct(string $dsn, string $username=NULL, string $password=NULL, array $driverOptions = []); /** * Simplifies prepared statements for database queries * * @param string $sql * @param array $data - * @return \PDOStatement | FALSE + * @return \PDOStatement|null * @throws \InvalidArgumentException */ - public function prepareQuery($sql, $data); + public function prepareQuery(string $sql, array $data): ?PDOStatement; /** * Retrieve column information for the current database table @@ -45,14 +47,14 @@ interface DriverInterface { * @param string $table * @return array */ - public function getColumns($table); + public function getColumns($table): ?array; /** * Retrieve list of data types for the database * * @return array */ - public function getTypes(); + public function getTypes(): ?array; /** * Retrieve indexes for the table @@ -60,7 +62,7 @@ interface DriverInterface { * @param string $table * @return array */ - public function getIndexes($table); + public function getIndexes($table): ?array; /** * Retrieve foreign keys for the table @@ -68,14 +70,14 @@ interface DriverInterface { * @param string $table * @return array */ - public function getFks($table); + public function getFks($table): ?array; /** * Return list of tables for the current database * * @return array */ - public function getTables(); + public function getTables(): ?array; /** * Retrieves an array of non-user-created tables for @@ -83,49 +85,49 @@ interface DriverInterface { * * @return array */ - public function getSystemTables(); + public function getSystemTables(): ?array; /** * Return list of dbs for the current connection, if possible * * @return array */ - public function getDbs(); + public function getDbs(): ?array; /** * Return list of views for the current database * * @return array */ - public function getViews(); + public function getViews(): ?array; /** * Return list of sequences for the current database, if they exist * * @return array */ - public function getSequences(); + public function getSequences(): ?array; /** * Return list of functions for the current database * * @return array */ - public function getFunctions(); + public function getFunctions(): ?array; /** * Return list of stored procedures for the current database * * @return array */ - public function getProcedures(); + public function getProcedures(): ?array; /** * Return list of triggers for the current database * * @return array */ - public function getTriggers(); + public function getTriggers(): ?array; /** * Surrounds the string with the databases identifier escape characters @@ -148,9 +150,9 @@ interface DriverInterface { * * @param string $sql * @param array $params - * @return \PDOStatement + * @return PDOStatement */ - public function prepareExecute($sql, $params); + public function prepareExecute(string $sql, array $params): ?PDOStatement; /** * Method to simplify retrieving db results for meta-data queries @@ -159,14 +161,14 @@ interface DriverInterface { * @param bool $filteredIndex * @return array */ - public function driverQuery($query, $filteredIndex=TRUE); + public function driverQuery($query, $filteredIndex=TRUE): ?array; /** * Returns number of rows affected by an INSERT, UPDATE, DELETE type query * * @return int */ - public function affectedRows(); + public function affectedRows(): int; /** * Return the number of rows returned for a SELECT query @@ -174,7 +176,7 @@ interface DriverInterface { * * @return int */ - public function numRows(); + public function numRows(): ?int; /** * Prefixes a table if it is not already prefixed @@ -182,7 +184,7 @@ interface DriverInterface { * @param string $table * @return string */ - public function prefixTable($table); + public function prefixTable(string $table): string; /** * Create sql for batch insert @@ -191,7 +193,7 @@ interface DriverInterface { * @param array $data * @return array */ - public function insertBatch($table, $data=[]); + public function insertBatch(string $table, array $data=[]): array; /** * Creates a batch update, and executes it. @@ -202,7 +204,7 @@ interface DriverInterface { * @param string $where * @return int|null */ - public function updateBatch($table, $data, $where); + public function updateBatch(string $table, $data, $where); /** * Get the SQL class for the current driver @@ -224,5 +226,5 @@ interface DriverInterface { * @param string $queryString * @return void */ - public function setLastQuery(string $queryString); + public function setLastQuery(string $queryString): void; } \ No newline at end of file diff --git a/src/Drivers/Mysql/Driver.php b/src/Drivers/Mysql/Driver.php index 2dca6b1..c83361e 100644 --- a/src/Drivers/Mysql/Driver.php +++ b/src/Drivers/Mysql/Driver.php @@ -16,12 +16,11 @@ namespace Query\Drivers\Mysql; use PDO; use Query\Drivers\AbstractDriver; -use Query\Drivers\DriverInterface; /** * MySQL specific class */ -class Driver extends AbstractDriver implements DriverInterface { +class Driver extends AbstractDriver { /** * Set the backtick as the MySQL escape character @@ -46,7 +45,7 @@ class Driver extends AbstractDriver implements DriverInterface { * @param string $password * @param array $options */ - public function __construct($dsn, $username=NULL, $password=NULL, array $options=[]) + public function __construct(string $dsn, string $username=NULL, string $password=NULL, array $options=[]) { // Set the charset to UTF-8 if (\defined('\\PDO::MYSQL_ATTR_INIT_COMMAND')) diff --git a/src/Drivers/Mysql/SQL.php b/src/Drivers/Mysql/SQL.php index da1746e..934cc08 100644 --- a/src/Drivers/Mysql/SQL.php +++ b/src/Drivers/Mysql/SQL.php @@ -29,7 +29,7 @@ class SQL extends AbstractSQL { * @param int|boolean $offset * @return string */ - public function limit($sql, $limit, $offset=FALSE) + public function limit(string $sql, int $limit, $offset=FALSE): string { if ( ! is_numeric($offset)) { @@ -45,7 +45,7 @@ class SQL extends AbstractSQL { * @param string $sql * @return string */ - public function explain($sql) + public function explain(string $sql): string { return "EXPLAIN EXTENDED {$sql}"; } @@ -55,7 +55,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function random() + public function random(): string { return ' RAND() DESC'; } @@ -65,7 +65,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function dbList() + public function dbList(): string { return "SHOW DATABASES WHERE `Database` NOT IN ('information_schema','mysql')"; } @@ -76,12 +76,14 @@ class SQL extends AbstractSQL { * @param string $database * @return string */ - public function tableList($database='') + public function tableList($database=''): string { + // @codeCoverageIgnoreStart if ( ! empty($database)) { return "SHOW TABLES FROM `{$database}`"; } + // @codeCoverageIgnoreEnd return 'SHOW TABLES'; } @@ -91,7 +93,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function systemTableList() + public function systemTableList(): string { return 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA`=\'information_schema\''; @@ -102,7 +104,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function viewList() + public function viewList(): string { return 'SELECT `table_name` FROM `information_schema`.`views`'; } @@ -112,7 +114,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function triggerList() + public function triggerList(): string { return 'SHOW TRIGGERS'; } @@ -122,7 +124,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function functionList() + public function functionList(): string { return 'SHOW FUNCTION STATUS'; } @@ -132,7 +134,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function procedureList() + public function procedureList(): string { return 'SHOW PROCEDURE STATUS'; } @@ -140,9 +142,9 @@ class SQL extends AbstractSQL { /** * Return sql to list sequences * - * @return NULL + * @return string */ - public function sequenceList() + public function sequenceList(): ?string { return NULL; } @@ -152,7 +154,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function typeList() + public function typeList(): string { return "SELECT DISTINCT `DATA_TYPE` FROM `information_schema`.`COLUMNS`"; } @@ -163,7 +165,7 @@ class SQL extends AbstractSQL { * @param string $table * @return string */ - public function columnList($table) + public function columnList(string $table): string { return "SHOW FULL COLUMNS FROM {$table}"; } @@ -175,7 +177,7 @@ class SQL extends AbstractSQL { * @param string $table * @return string */ - public function fkList($table) + public function fkList(string $table): string { return <<getDriver()->driverQuery("SHOW TABLES FROM `{$d}`", TRUE); diff --git a/src/Drivers/PDOStatementInterface.php b/src/Drivers/PDOStatementInterface.php deleted file mode 100644 index 0b39eb3..0000000 --- a/src/Drivers/PDOStatementInterface.php +++ /dev/null @@ -1,175 +0,0 @@ - - * @copyright 2012 - 2018 Timothy J. Warren - * @license http://www.opensource.org/licenses/mit-license.html MIT License - * @link https://git.timshomepage.net/aviat4ion/Query - */ -namespace Query\Drivers; - -use PDO; - -/** - * Interface created from official PHP Documentation - */ -interface PDOStatementInterface { - - /** - * Bind a column to a PHP variable - * - * @param mixed $column Number or name of the column in the result set - * @param mixed $param Name of the PHP variable to which the column will be bound - * @param int $type Data type of the parameter, specified by the PDO::PARAM_* constants - * @param int $maxlen A hint for pre-allocation - * @param mixed $driverdata Optional parameter(s) for the driver - * @return boolean - */ - public function bindColumn($column, &$param, $type, $maxlen, $driverdata); - - /** - * Binds a parameter to the specified variable name - * - * @param mixed $parameter Parameter identifier. For a prepared statement using named placeholders, this will be a - * parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the - * 1-indexed position of the parameter. - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. - * @param int $dataType Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT - * parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits - * for the data_type parameter. - * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, - * you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean - */ - public function bindParam($parameter, &$variable, $dataType = PDO::PARAM_STR, $length, $driverOptions); - - /** - * Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to - * prepare the statement - * - * @param mixed $parameter Parameter identifier. For a prepared statement using named placeholders, this will be a - * parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the - * 1-indexed position of the parameter. - * @param mixed $value The value to bind to the parameter - * @param int $dataType Explicit data type for the parameter using the PDO::PARAM_* constants. - * @return boolean - */ - public function bindValue($parameter, $value, $dataType = PDO::PARAM_STR); - - /** - * Frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a - * state that enables it to be executed again - * - * @return boolean - */ - public function closeCursor(); - - /** - * Returns the number of columns in the result set - * - * @return int - */ - public function columnCount(); - - /** - * Dumps the information contained by a prepared statement directly on the output - * - * @return void - */ - public function debugDumpParams(); - - /** - * Fetch the SQLSTATE associated with the last operation on the statement handle - * - * @return string - */ - public function errorCode(); - - /** - * Fetch extended error information associated with the last operation on the statement handle - * - * @return array - */ - public function errorInfo(); - - /** - * Run a prepared statement query - * - * @param array $boundInputParams - * @return boolean - */ - public function execute($boundInputParams = NULL); - - /** - * Fetches the next row from a result set - * - * @param int $how - * @param int $orientation - * @param int $offset - * @return mixed - */ - public function fetch($how = PDO::ATTR_DEFAULT_FETCH_MODE, $orientation = PDO::FETCH_ORI_NEXT, $offset = 0); - - /** - * Returns a single column from the next row of a result set - * - * @param int $columnNumber - * @return mixed - */ - public function fetchColumn($columnNumber = 0); - - /** - * Fetches the next row and returns it as an object - * - * @param string $className - * @param array $ctorArgs - * @return mixed - */ - public function fetchObject($className = "stdClass", $ctorArgs = NULL); - - /** - * Retrieve a statement attribute - * - * @param int $attribute - * @return mixed - */ - public function getAttribute($attribute); - - /** - * Advances to the next rowset in a multi-rowset statement handle - * - * @return boolean - */ - public function nextRowset(); - - /** - * Returns the number of rows affected by the last SQL statement - * - * @return int - */ - public function rowCount(); - - /** - * Set a statement attribute - * - * @param int $attribute - * @param mixed $value - * @return boolean - */ - public function setAttribute($attribute, $value); - - /** - * Set the default fetch mode for this statement - * - * @param int $mode - * @return boolean - */ - public function setFetchMode($mode); -} \ No newline at end of file diff --git a/src/Drivers/Pgsql/Driver.php b/src/Drivers/Pgsql/Driver.php index 7180f42..0c5d7e5 100644 --- a/src/Drivers/Pgsql/Driver.php +++ b/src/Drivers/Pgsql/Driver.php @@ -15,12 +15,11 @@ namespace Query\Drivers\Pgsql; use Query\Drivers\AbstractDriver; -use Query\Drivers\DriverInterface; /** * PostgreSQL specific class */ -class Driver extends AbstractDriver implements DriverInterface { +class Driver extends AbstractDriver { /** * Connect to a PosgreSQL database diff --git a/src/Drivers/Pgsql/SQL.php b/src/Drivers/Pgsql/SQL.php index 274945a..3aab205 100644 --- a/src/Drivers/Pgsql/SQL.php +++ b/src/Drivers/Pgsql/SQL.php @@ -27,7 +27,7 @@ class SQL extends AbstractSQL { * @param string $sql * @return string */ - public function explain($sql) + public function explain(string $sql): string { return "EXPLAIN VERBOSE {$sql}"; } @@ -37,7 +37,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function random() + public function random(): string { return ' RANDOM()'; } @@ -47,7 +47,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function dbList() + public function dbList(): string { return <<sql->tableList(); $res = $this->query($sql); - return db_filter($res->fetchAll(PDO::FETCH_ASSOC), 'name'); + return dbFilter($res->fetchAll(PDO::FETCH_ASSOC), 'name'); } /** @@ -98,9 +89,9 @@ class Driver extends AbstractDriver implements DriverInterface { * @codeCoverageIgnore * @param string $table * @param array $data - * @return string + * @return array */ - public function insertBatch($table, $data=[]) + public function insertBatch(string $table, array $data=[]): array { // If greater than version 3.7.11, supports the same syntax as // MySQL and Postgres @@ -114,7 +105,7 @@ class Driver extends AbstractDriver implements DriverInterface { // -------------------------------------------------------------------------- // Each member of the data array needs to be an array - if ( ! is_array(current($data))) + if ( ! \is_array(current($data))) { return NULL; } diff --git a/src/Drivers/Sqlite/SQL.php b/src/Drivers/Sqlite/SQL.php index 93c1e1d..d48f98e 100644 --- a/src/Drivers/Sqlite/SQL.php +++ b/src/Drivers/Sqlite/SQL.php @@ -27,7 +27,7 @@ class SQL extends AbstractSQL { * @param string $sql * @return string */ - public function explain($sql) + public function explain(string $sql): string { return "EXPLAIN QUERY PLAN {$sql}"; } @@ -37,7 +37,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function random() + public function random(): string { return ' RANDOM()'; } @@ -47,7 +47,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function dbList() + public function dbList(): string { return 'PRAGMA database_list'; } @@ -57,7 +57,7 @@ class SQL extends AbstractSQL { * * @return string */ - public function tableList() + public function tableList(): string { return <<driver] as $object) + //foreach([$this, $this->driver] as $object) { - foreach([$name, $camelName] as $methodName) + if (method_exists($this->driver, $name)) { - if (method_exists($object, $methodName)) - { - return \call_user_func_array([$object, $methodName], $params); - } + return \call_user_func_array([$this->driver, $name], $params); } - } throw new BadMethodCallException('Method does not exist'); @@ -1102,7 +1095,7 @@ class QueryBuilder implements QueryBuilderInterface { // Determine the correct conjunction $conjunctionList = array_column($queryMap, 'conjunction'); - if (empty($queryMap) || ( ! regex_in_array($conjunctionList, "/^ ?\n?WHERE/i"))) + if (empty($queryMap) || ( ! \regexInArray($conjunctionList, "/^ ?\n?WHERE/i"))) { $conj = "\nWHERE "; } diff --git a/src/State.php b/src/State.php index 4440daf..5d4c491 100644 --- a/src/State.php +++ b/src/State.php @@ -165,7 +165,7 @@ class State { * @param string $fromString * @return State */ - public function setFromString(string $fromString): State + public function setFromString(string $fromString): self { $this->fromString = $fromString; return $this; @@ -183,7 +183,7 @@ class State { * @param string $setString * @return State */ - public function setSetString(string $setString): State + public function setSetString(string $setString): self { $this->setString = $setString; return $this; @@ -201,7 +201,7 @@ class State { * @param string $orderString * @return State */ - public function setOrderString(string $orderString): State + public function setOrderString(string $orderString): self { $this->orderString = $orderString; return $this; @@ -219,7 +219,7 @@ class State { * @param string $groupString * @return State */ - public function setGroupString(string $groupString): State + public function setGroupString(string $groupString): self { $this->groupString = $groupString; return $this; @@ -237,7 +237,7 @@ class State { * @param array $setArrayKeys * @return State */ - public function appendSetArrayKeys(array $setArrayKeys): State + public function appendSetArrayKeys(array $setArrayKeys): self { $this->setArrayKeys = array_merge($this->setArrayKeys, $setArrayKeys); return $this; @@ -247,7 +247,7 @@ class State { * @param array $setArrayKeys * @return State */ - public function setSetArrayKeys(array $setArrayKeys): State + public function setSetArrayKeys(array $setArrayKeys): self { $this->setArrayKeys = $setArrayKeys; return $this; @@ -266,7 +266,7 @@ class State { * @param mixed $orderArray * @return State */ - public function setOrderArray(string $key, $orderArray): State + public function setOrderArray(string $key, $orderArray): self { $this->orderArray[$key] = $orderArray; return $this; @@ -284,7 +284,7 @@ class State { * @param array $groupArray * @return State */ - public function setGroupArray(array $groupArray): State + public function setGroupArray(array $groupArray): self { $this->groupArray = $groupArray; return $this; @@ -294,7 +294,7 @@ class State { * @param string $groupArray * @return State */ - public function appendGroupArray(string $groupArray): State + public function appendGroupArray(string $groupArray): self { $this->groupArray[] = $groupArray; return $this; @@ -312,7 +312,7 @@ class State { * @param array $values * @return State */ - public function appendValues(array $values): State + public function appendValues(array $values): self { $this->values = array_merge($this->values, $values); return $this; @@ -330,7 +330,7 @@ class State { * @param mixed $val * @return State */ - public function appendWhereValues($val): State + public function appendWhereValues($val): self { if (\is_array($val)) { @@ -358,7 +358,7 @@ class State { * @param int $limit * @return State */ - public function setLimit(int $limit): State + public function setLimit(int $limit): self { $this->limit = $limit; return $this; @@ -376,7 +376,7 @@ class State { * @param string|false $offset * @return State */ - public function setOffset($offset): State + public function setOffset($offset): self { $this->offset = $offset; return $this; @@ -420,7 +420,7 @@ class State { * @param array $item * @return State */ - public function appendHavingMap(array $item): State + public function appendHavingMap(array $item): self { $this->havingMap[] = $item; return $this; diff --git a/src/common.php b/src/common.php index df4990e..2dcb3f8 100644 --- a/src/common.php +++ b/src/common.php @@ -25,165 +25,128 @@ use Query\{ * Global functions that don't really fit anywhere else */ -if ( ! function_exists('mb_trim')) +/** + * Multibyte-safe trim function + * + * @param string $string + * @return string + */ +function mb_trim(string $string): string { - /** - * Multibyte-safe trim function - * - * @param string $string - * @return string - */ - function mb_trim(string $string): string - { - return preg_replace('/(^\s+)|(\s+$)/u', '', $string); - } + return preg_replace('/(^\s+)|(\s+$)/u', '', $string); } // -------------------------------------------------------------------------- -if ( ! function_exists('db_filter')) +/** + * Filter out db rows into one array + * + * @param array $array + * @param mixed $index + * @return array + */ +function dbFilter(array $array, $index): array { - /** - * Filter out db rows into one array - * - * @param array $array - * @param mixed $index - * @return array - */ - function db_filter(array $array, $index): array + $newArray = []; + + foreach($array as $a) { - $newArray = []; - - foreach($array as $a) - { - $newArray[] = $a[$index]; - } - - return $newArray; + $newArray[] = $a[$index]; } -} -if ( ! function_exists('to_camel_case')) -{ - /** - * Create a camelCase string from snake_case - * - * @param string $snakeCase - * @return string - */ - function to_camel_case(string $snakeCase): string - { - $pieces = explode('_', $snakeCase); - $numPieces = count($pieces); - - $pieces[0] = mb_strtolower($pieces[0]); - for($i = 1; $i < $numPieces; $i++) - { - $pieces[$i] = ucfirst(mb_strtolower($pieces[$i])); - } - - return implode('', $pieces); - } + return $newArray; } // -------------------------------------------------------------------------- -if ( ! function_exists('array_zipper')) +/** + * Zip a set of arrays together on common keys + * + * The $zipperInput array is an array of arrays indexed by their place in the output + * array. + * + * @param array $zipperInput + * @return array + */ +function arrayZipper(array $zipperInput): array { - /** - * Zip a set of arrays together on common keys - * - * The $zipperInput array is an array of arrays indexed by their place in the output - * array. - * - * @param array $zipperInput - * @return array - */ - function array_zipper(array $zipperInput): array - { - $output = []; + $output = []; - foreach($zipperInput as $appendKey => $values) + foreach($zipperInput as $appendKey => $values) + { + foreach($values as $index => $value) { - foreach($values as $index => $value) + if ( ! isset($output[$index])) { - if ( ! isset($output[$index])) - { - $output[$index] = []; - } - $output[$index][$appendKey] = $value; + $output[$index] = []; } + $output[$index][$appendKey] = $value; } - - return $output; } + + return $output; } // -------------------------------------------------------------------------- -if ( ! function_exists('regex_in_array')) +/** + * Determine whether a value in the passed array matches the pattern + * passed + * + * @param array $array + * @param string $pattern + * @return bool + */ +function regexInArray(array $array, string $pattern): bool { - /** - * Determine whether a value in the passed array matches the pattern - * passed - * - * @param array $array - * @param string $pattern - * @return bool - */ - function regex_in_array(array $array, string $pattern): bool + if (empty($array)) { - if (empty($array)) - { - return FALSE; - } - - foreach($array as $item) - { - if (is_scalar($item) && preg_match($pattern, $item)) - { - return TRUE; - } - } - return FALSE; } + + foreach($array as $item) + { + if (is_scalar($item) && preg_match($pattern, $item)) + { + return TRUE; + } + } + + return FALSE; } // -------------------------------------------------------------------------- -if ( ! function_exists('Query')) +/** + * Connection function + * + * Send an array or object as connection parameters to create a connection. If + * the array or object has an 'alias' parameter, passing that string to this + * function will return that connection. Passing no parameters returns the last + * connection created. + * + * @param string|object|array $params + * @return QueryBuilderInterface|null + */ +function Query($params = ''): ?QueryBuilderInterface { - /** - * Connection function - * - * Send an array or object as connection parameters to create a connection. If - * the array or object has an 'alias' parameter, passing that string to this - * function will return that connection. Passing no parameters returns the last - * connection created. - * - * @param string|object|array $params - * @return QueryBuilderInterface|null - */ - function Query($params = ''): ?QueryBuilderInterface + if ($params === NULL) { - $manager = ConnectionManager::getInstance(); - - if ($params === NULL) - { - return NULL; - } - - // If you are getting a previously created connection - if (is_scalar($params)) - { - return $manager->getConnection($params); - } - - $paramsObject = (object) $params; - - // Otherwise, return a new connection - return $manager->connect($paramsObject); + return NULL; } + + $manager = ConnectionManager::getInstance(); + + // If you are getting a previously created connection + if (is_scalar($params)) + { + return $manager->getConnection($params); + } + + $paramsObject = (object) $params; + + // Otherwise, return a new connection + return $manager->connect($paramsObject); } + // End of common.php diff --git a/tests/CoreTest.php b/tests/CoreTest.php index 5ac2d5b..55091b5 100644 --- a/tests/CoreTest.php +++ b/tests/CoreTest.php @@ -63,4 +63,14 @@ class CoreTest extends TestCase { $this->assertTrue($numSupported > 0); } + + public function testNullQuery(): void + { + $this->assertNull(\Query(NULL)); + } + + public function testEmptyRegexInArray(): void + { + $this->assertFalse(\regexInArray([], 'foo')); + } } \ No newline at end of file diff --git a/tests/Drivers/MySQL/MySQLDriverTest.php b/tests/Drivers/MySQL/MySQLDriverTest.php index fee331b..87b4fb2 100644 --- a/tests/Drivers/MySQL/MySQLDriverTest.php +++ b/tests/Drivers/MySQL/MySQLDriverTest.php @@ -14,10 +14,10 @@ */ namespace Query\Tests\Drivers\MySQL; -use InvalidArgumentException; use PDO; use Query\Drivers\Mysql\Driver; use Query\Tests\BaseDriverTest; +use TypeError; /** * MySQLTest class. @@ -132,7 +132,7 @@ SQL; public function testBadPreparedStatement() { - $this->expectException(InvalidArgumentException::class); + $this->expectException(TypeError::class); $sql = <<expectException(InvalidArgumentException::class); + $this->expectException(TypeError::class); $sql = <<