From 035a942cb8b93533e7191b0ff8d66cfae48b5e4f Mon Sep 17 00:00:00 2001 From: weregod Date: Sat, 10 Dec 2022 16:00:38 +0700 Subject: [PATCH] PHP ^7.0 compatibility implemented. --- README.md | 16 ++- build/bin/phpunit.bat | 3 +- build/config/phpunit.xml | 2 +- src/ExcavatingTrait.php | 57 ++++---- src/LoggerInterface.php | 2 +- src/PDOExcavated.php | 86 +++++++----- src/PDOStatementExcavated.php | 145 +++++++++++--------- src/Tools.php | 44 +++--- tests/CommonTest.php | 31 +++-- tests/ExtendedClassesTest.php | 15 +- tests/src/Logger.php | 2 +- tests/src/PDOExcavatedExtended.php | 6 +- tests/src/PDOStatementExcavatedExtended.php | 2 +- tests/src/TestCaseConfigAndDatabase.php | 40 +++--- 14 files changed, 257 insertions(+), 194 deletions(-) diff --git a/README.md b/README.md index fd9a382..c827538 100644 --- a/README.md +++ b/README.md @@ -2,22 +2,25 @@ [![GitHub license](https://img.shields.io/github/license/deepeloper/pdo-debugging.svg)](https://github.com/deepeloper/pdo-debugging/blob/master/LICENSE) ## Compatibility -[![PHP ^5.6](https://img.shields.io/badge/PHP%C2%A0%C2%A0-%5E5.6-%237A86B8)]() ‾‾❞ -[![1.2.0](https://img.shields.io/badge/Release-1.2.0-%233fb950)](https://github.com/deepeloper/pdo-debugging/releases/tag/1.1.0) +[![PHP ^7.0](https://img.shields.io/badge/PHP-%5E7.0-%237A86B8)]() ‾‾ +[![2.0.0](https://img.shields.io/badge/Release-2.0.0-%233fb950)](https://github.com/deepeloper/pdo-debugging/releases/tag/2.0.0) -[![PHP ^5.5](https://img.shields.io/badge/PHP%C2%A0%C2%A0-%5E5.5-%237A86B8)]() ‾‾❞ +[![PHP ^5.6](https://img.shields.io/badge/PHP-%5E5.6-%237A86B8)]() ‾‾ +[![1.2.0](https://img.shields.io/badge/Release-1.2.0-%233fb950)](https://github.com/deepeloper/pdo-debugging/releases/tag/1.2.0) + +[![PHP ^5.5](https://img.shields.io/badge/PHP-%5E5.5-%237A86B8)]() ‾‾ [![1.1.0](https://img.shields.io/badge/Release-1.1.0-%233fb950)](https://github.com/deepeloper/pdo-debugging/releases/tag/1.1.0) -[![PHP ^5.4](https://img.shields.io/badge/PHP%C2%A0%C2%A0-%5E5.4-%237A86B8)]() ‾‾❞ +[![PHP ^5.4](https://img.shields.io/badge/PHP-%5E5.4-%237A86B8)]() ‾‾ [![1.0.0](https://img.shields.io/badge/Release-1.0.0-%233fb950)](https://github.com/deepeloper/pdo-debugging/releases/tag/1.0.0) ## Installation -`composer require deepeloper/pdo-debugging "^1.2"` +`composer require deepeloper/pdo-debugging "^2.0"` or add to "composer.json" section ```json "require": { - "deepeloper/pdo-debugging": "^1.2" + "deepeloper/pdo-debugging": "^2.0" } ``` @@ -349,5 +352,4 @@ deepeloper\PDO\PDOExcavatedExtended::scope deepeloper\PDO\PDOExcavatedExtended::scope deepeloper\PDO\PDOExcavatedExtended::scope deepeloper\PDO\PDOStatementExcavatedExtended::scope - ``` \ No newline at end of file diff --git a/build/bin/phpunit.bat b/build/bin/phpunit.bat index a444d32..e670c46 100644 --- a/build/bin/phpunit.bat +++ b/build/bin/phpunit.bat @@ -1,3 +1,4 @@ @cd "../.." @echo ------------------------------------------------------ -@call php "vendor/bin/phpunit" -c "build/config/phpunit.xml" --log-junit "build/logs/junit.xml" -v --debug +@rem call php "vendor/bin/phpunit" -c "build/config/phpunit.xml" --log-junit "build/logs/junit.xml" -v --debug +@call php "vendor/bin/phpunit" -c "build/config/phpunit.xml" --log-junit "build/logs/junit.xml" diff --git a/build/config/phpunit.xml b/build/config/phpunit.xml index 90b2eb3..85ff6cd 100644 --- a/build/config/phpunit.xml +++ b/build/config/phpunit.xml @@ -1,7 +1,7 @@ "Y-m-d H:i:s.u", 'precision' => "%.05f", 'count' => "%03d", - // @codingStandardsIgnoreStart + // phpcs:disable 'call' => "[ %TIME_STAMP% ] [ %EXECUTION_TIME% ] [ CALL ] [ %DSN%;user=%USER_NAME% ] [ %SOURCE%(%ARGS%) ]", 'query' => "[ %TIME_STAMP% ] [ %EXECUTION_TIME% ] [ QUERY ] [ %DSN%;user=%USER_NAME% ] [ #%COUNT% ] [ %SOURCE% ] [ %QUERY% ]", - // @codingStandardsIgnoreEnd + // phpcs:enable ], 'sources' => [ ], @@ -75,12 +86,11 @@ abstract protected function scope(array &$scope); /** * Prepares query for logging. * - * @param string &$query + * @param string $query * @return void * @link self::after() */ - abstract protected function prepareQueryForLogging(&$query); - + abstract protected function prepareQueryForLogging(string &$query); /** * Initializes debugging. @@ -91,7 +101,7 @@ abstract protected function prepareQueryForLogging(&$query); */ public function initDebugging(array $options = [], BenchmarksContainer $benchmarkContainer = null) { - $this->debuggingOptions = \array_replace_recursive($this->debuggingOptions, $options); + $this->debuggingOptions = array_replace_recursive($this->debuggingOptions, $options); $this->benchmarks = null !== $benchmarkContainer ? $benchmarkContainer : new BenchmarksContainer(); } @@ -101,7 +111,7 @@ public function initDebugging(array $options = [], BenchmarksContainer $benchmar * @return array * @see PDOStatementExcavated::__construct() */ - public function getDebuggingEnvironment() + public function getDebuggingEnvironment(): array { return [$this->debuggingOptions, $this->benchmarks]; } @@ -111,7 +121,7 @@ public function getDebuggingEnvironment() * * @return array */ - public function getBenchmarks() + public function getBenchmarks(): array { return $this->benchmarks->container; } @@ -129,22 +139,22 @@ protected function before(array $args = null, array $excludeArgIndexes = null) return; } if (null === $args) { - $trace = \debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2); - $source = \sprintf("%s::%s", $trace[1]['class'], $trace[1]['function']); + $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2); + $source = sprintf("%s::%s", $trace[1]['class'], $trace[1]['function']); $args = $trace[1]['args']; } else { $source = $args['source']; unset($args['source']); } if (null !== $excludeArgIndexes) { - $args = \array_diff_key($args, array_combine($excludeArgIndexes, $excludeArgIndexes)); + $args = array_diff_key($args, array_combine($excludeArgIndexes, $excludeArgIndexes)); } - \preg_match("/\w+::.+$/", $source, $matches); + preg_match("/\w+::.+$/", $source, $matches); $source = $matches[0]; $dateTime = new DateTime(); $call = [ 'timeStamp' => $dateTime->format($this->debuggingOptions['format']['timeStamp']), - 'microTime' => \microtime(true), + 'microTime' => microtime(true), 'source' => $source, ]; if (empty($args['query'])) { @@ -160,26 +170,25 @@ protected function before(array $args = null, array $excludeArgIndexes = null) * called or about query. * * @return void - * @todo PHP >=7: Add comma after last element of array, no problem with code coverage. */ protected function after() { if ($this->skipLogging) { return; } - $call = \array_pop($this->stack); + $call = array_pop($this->stack); $scope = [ 'TIME_STAMP' => $call['timeStamp'], 'DSN' => $this->debuggingOptions['dsn'], 'USER_NAME' => $this->debuggingOptions['username'], - 'EXECUTION_TIME' => \sprintf( + 'EXECUTION_TIME' => sprintf( $this->debuggingOptions['format']['precision'], - \microtime(true) - $call['microTime'] + microtime(true) - $call['microTime'] ), 'SOURCE' => $call['source'], ]; if (empty($call['query'])) { - $scope['ARGS'] = \json_encode($call['args'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $scope['ARGS'] = json_encode($call['args'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } else { $this->prepareQueryForLogging($call['query']); $scope += [ @@ -187,11 +196,11 @@ protected function after() 'COUNT' => $this->benchmarks->container['query']['count'], ]; } - $log = 0 === \sizeof($this->debuggingOptions['sources']); + $log = 0 === sizeof($this->debuggingOptions['sources']); if (!$log) { foreach ($this->debuggingOptions['sources'] as $pattern) { $log = substr($pattern, 0, 1) === "/" - ? \preg_match($pattern, $call['source']) + ? preg_match($pattern, $call['source']) : $pattern === $call['source']; if ($log) { break; @@ -202,7 +211,7 @@ protected function after() if ($log) { $this->scope($scope); if (isset($scope['COUNT'])) { - $scope['COUNT'] = \sprintf($this->debuggingOptions['format']['count'], $scope['COUNT']); + $scope['COUNT'] = sprintf($this->debuggingOptions['format']['count'], $scope['COUNT']); } $this->debuggingOptions['logger']->log( $this->renderLogMessage($this->debuggingOptions['format'][$format], $scope), @@ -219,7 +228,7 @@ protected function after() * @param PDOException|null $e * @return mixed */ - protected function getResult($delay, $result, PDOException $e = null) + protected function getResult(float $delay, $result, PDOException $e = null) { $this->benchmarks->container['total']['time'] += $delay; if (isset($this->statementBenchmarks)) { @@ -240,10 +249,10 @@ protected function getResult($delay, $result, PDOException $e = null) * @param array $scope * @return string */ - protected function renderLogMessage($template, array $scope) + protected function renderLogMessage(string $template, array $scope): string { foreach ($scope as $name => $value) { - $template = \str_replace("%$name%", $value, $template); + $template = str_replace("%$name%", $value, $template); } return $template; } diff --git a/src/LoggerInterface.php b/src/LoggerInterface.php index 186e9c6..b7c91fc 100644 --- a/src/LoggerInterface.php +++ b/src/LoggerInterface.php @@ -22,5 +22,5 @@ interface LoggerInterface * @return void * @link ExcavatingTrait::after() */ - public function log($message, array $scope); + public function log(string $message, array $scope); } diff --git a/src/PDOExcavated.php b/src/PDOExcavated.php index d419870..01c9660 100644 --- a/src/PDOExcavated.php +++ b/src/PDOExcavated.php @@ -13,6 +13,11 @@ use PDOException; use PDOStatement; +use function is_array; +use function is_object; +use function microtime; +use function sprintf; + /** * PDO having benchmarking and debugging abilities class. */ @@ -22,10 +27,10 @@ class PDOExcavated extends PDO /** * @todo PHP >=7.1: Add visibility and remove ignorance. - * @codingStandardsIgnoreStart + * phpcs:disable */ const ATTR_DEBUG = "debug"; - // @codingStandardsIgnoreEnd + // phpcs:enable /** * Represents a connection between PHP and a database server. @@ -36,7 +41,7 @@ class PDOExcavated extends PDO * @param array $options * @see https://www.php.net/manual/en/class.pdo.php */ - public function __construct($dsn, $username = null, $password = null, array $options = []) + public function __construct(string $dsn, string $username = null, string $password = null, array $options = []) { if (isset($options[self::ATTR_DEBUG])) { $this->initDebugging( @@ -51,9 +56,9 @@ public function __construct($dsn, $username = null, $password = null, array $opt unset($options[self::ATTR_DEBUG]); } $this->before(null, [2, 3]); - $timeStamp = \microtime(true); + $timeStamp = microtime(true); parent::__construct($dsn, $username, $password, $options); - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; $this->benchmarks->container['total']['time'] += $delay; $this->after(); } @@ -64,19 +69,19 @@ public function __construct($dsn, $username = null, $password = null, array $opt * @return bool * @see https://www.php.net/manual/en/pdo.begintransaction.php */ - public function beginTransaction() + public function beginTransaction(): bool { $this->before(); $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { $result = parent::beginTransaction(); // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; return $this->getResult($delay, $result, $e); } @@ -86,19 +91,19 @@ public function beginTransaction() * @return bool * @see https://www.php.net/manual/en/pdo.commit.php */ - public function commit() + public function commit(): bool { $this->before(); $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { $result = parent::commit(); // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; $this->benchmarks->container['commit']['time'] += $delay; $this->benchmarks->container['commit']['count']++; return $this->getResult($delay, $result, $e); @@ -111,7 +116,7 @@ public function commit() * @return int * @see https://www.php.net/manual/en/pdo.exec.php */ - public function exec($statement) + public function exec($statement): int { $this->before([ 'source' => __METHOD__, @@ -119,14 +124,14 @@ public function exec($statement) ]); $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { $result = parent::exec($statement); // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; $this->benchmarks->container['query']['time'] += $delay; $this->benchmarks->container['query']['count']++; return $this->getResult($delay, $result, $e); @@ -137,22 +142,22 @@ public function exec($statement) * * @param string $query * @param array $options - * @return PDOStatementExcavated + * @return PDOStatement * @see https://www.php.net/manual/en/pdo.prepare.php */ - public function prepare($query, $options = []) + public function prepare($query, $options = null): PDOStatement { $this->before(); $stmt = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { - $stmt = parent::prepare($query, $options); + $stmt = is_array($options) ? parent::prepare($query, $options) : parent::prepare($query); // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; return $this->getResultStatement($delay, "prepare", $query, $stmt, $e); } @@ -163,18 +168,22 @@ public function prepare($query, $options = []) * @param int $mode * @param mixed $arg3 * @param array $constructorArgs - * @return PDOStatementExcavated + * @return PDOStatement * @see https://www.php.net/manual/en/pdo.query.php */ - public function query($statement, $mode = PDO::ATTR_DEFAULT_FETCH_MODE, $arg3 = null, array $constructorArgs = []) - { + public function query( + string $statement, + int $mode = PDO::ATTR_DEFAULT_FETCH_MODE, + $arg3 = null, + array $constructorArgs = [] + ): PDOStatement { $this->before([ - 'source' => \sprintf("%s::query", __CLASS__), + 'source' => sprintf("%s::query", __CLASS__), 'query' => $statement, ]); $stmt = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { switch ($mode) { case PDO::ATTR_DEFAULT_FETCH_MODE: @@ -194,7 +203,7 @@ public function query($statement, $mode = PDO::ATTR_DEFAULT_FETCH_MODE, $arg3 = } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; return $this->getResultStatement($delay, "query", $statement, $stmt, $e); } @@ -204,12 +213,12 @@ public function query($statement, $mode = PDO::ATTR_DEFAULT_FETCH_MODE, $arg3 = * @return bool * @see https://www.php.net/manual/en/pdo.rollback.php */ - public function rollBack() + public function rollBack(): bool { $this->before(); $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { $result = parent::rollBack(); // @codeCoverageIgnoreStart @@ -217,7 +226,7 @@ public function rollBack() // @codeCoverageIgnoreEnd } // @codeCoverageIgnoreEnd - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; $this->benchmarks->container['rollBack']['time'] += $delay; $this->benchmarks->container['rollBack']['count']++; return $this->getResult($delay, $result, $e); @@ -226,11 +235,11 @@ public function rollBack() /** * Prepares query for logging. * - * @param string &$query + * @param string $query * @return void * @see ExcavatingTrait::after() */ - protected function prepareQueryForLogging(&$query) + protected function prepareQueryForLogging(string &$query) { } @@ -253,18 +262,23 @@ protected function scope(array &$scope) * @param string $template * @param PDOStatement $stmt * @param PDOException|null $e - * @return PDOStatementExcavated + * @return PDOStatement * @see self::prepare() * @see self::query() */ - protected function getResultStatement($delay, $key, $template, $stmt, PDOException $e = null) - { + protected function getResultStatement( + float $delay, + string $key, + string $template, + PDOStatement $stmt = null, + PDOException $e = null + ): PDOStatement { $this->benchmarks->container[$key]['count']++; $this->benchmarks->container[$key]['time'] += $delay; $this->benchmarks->container['total']['time'] += $delay; $this->after(); - if (isset($stmt)) { - return \is_object($stmt) ? $this->getStatement($template, $stmt) : $stmt; + if ($stmt) { + return is_object($stmt) ? $this->getStatement($template, $stmt) : $stmt; } else { throw $e; } @@ -278,7 +292,7 @@ protected function getResultStatement($delay, $key, $template, $stmt, PDOExcepti * @return PDOStatementExcavated * @see self::getResultStatement() */ - protected function getStatement($template, PDOStatement $stmt) + protected function getStatement(string $template, PDOStatement $stmt): PDOStatementExcavated { return new PDOStatementExcavated($template, $this, $stmt); } diff --git a/src/PDOStatementExcavated.php b/src/PDOStatementExcavated.php index 466802b..b633c51 100644 --- a/src/PDOStatementExcavated.php +++ b/src/PDOStatementExcavated.php @@ -13,6 +13,15 @@ use PDOException; use PDOStatement; +use function is_array; +use function is_int; +use function is_string; +use function microtime; +use function sizeof; +use function sprintf; +use function str_replace; +use function uniqid; + /** * PDOStatement having benchmarking and debugging abilities class. * @@ -84,7 +93,7 @@ class PDOStatementExcavated extends PDOStatement * @param PDOExcavated $pdo * @param PDOStatement $stmt */ - public function __construct($template, PDOExcavated $pdo, PDOStatement $stmt) + public function __construct(string $template, PDOExcavated $pdo, PDOStatement $stmt) { $this->template = $template; $this->pdo = $pdo; @@ -101,7 +110,7 @@ public function __construct($template, PDOExcavated $pdo, PDOStatement $stmt) * * @return string */ - public function getQueryString() + public function getQueryString(): string { return $this->template; } @@ -111,7 +120,7 @@ public function getQueryString() * * @return array */ - public function getBenchmarks() + public function getBenchmarks(): array { return $this->statementBenchmarks; } @@ -121,7 +130,7 @@ public function getBenchmarks() * * @return string */ - public function getLastExecutedQuery() + public function getLastExecutedQuery(): string { return $this->lastExecutedQuery; } @@ -131,14 +140,14 @@ public function getLastExecutedQuery() * * @param $column * @param $var - * @param $type - * @param $maxLength + * @param int $type + * @param int $maxLength * @param $driverOptions * @return bool * @see https://www.php.net/manual/en/pdostatement.bindcolumn.php * @codeCoverageIgnore */ - public function bindColumn($column, &$var, $type = PDO::PARAM_STR, $maxLength = 0, $driverOptions = null) + public function bindColumn($column, &$var, $type = PDO::PARAM_STR, $maxLength = 0, $driverOptions = null): bool { return $this->stmt->bindColumn($column, $var, $type, $maxLength, $driverOptions); } @@ -155,7 +164,7 @@ public function bindColumn($column, &$var, $type = PDO::PARAM_STR, $maxLength = * @see https://www.php.net/manual/en/pdostatement.bindparam.php * @codeCoverageIgnore */ - public function bindParam($param, &$var, $type = PDO::PARAM_STR, $maxLength = 0, $driverOptions = null) + public function bindParam($param, &$var, $type = PDO::PARAM_STR, $maxLength = 0, $driverOptions = null): bool { $this->values[$param] = [&$var, $type]; return $this->stmt->bindParam($param, $var, $type); @@ -171,7 +180,7 @@ public function bindParam($param, &$var, $type = PDO::PARAM_STR, $maxLength = 0, * @see https://www.php.net/manual/en/pdostatement.bindvalue.php * @codeCoverageIgnore */ - public function bindValue($param, $value, $type = PDO::PARAM_STR) + public function bindValue($param, $value, $type = PDO::PARAM_STR): bool { $this->values[$param] = [$value, $type]; return $this->stmt->bindValue($param, $value, $type); @@ -184,7 +193,7 @@ public function bindValue($param, $value, $type = PDO::PARAM_STR) * @see https://www.php.net/manual/en/pdostatement.closecursor.php * @codeCoverageIgnore */ - public function closeCursor() + public function closeCursor(): bool { return $this->stmt->closeCursor(); } @@ -196,7 +205,7 @@ public function closeCursor() * @see https://www.php.net/manual/en/pdostatement.columncount.php * @codeCoverageIgnore */ - public function columnCount() + public function columnCount(): int { return $this->stmt->columnCount(); } @@ -220,7 +229,7 @@ public function debugDumpParams() * @see https://www.php.net/manual/en/pdostatement.errorcode.php * @codeCoverageIgnore */ - public function errorCode() + public function errorCode(): string { return $this->stmt->errorCode(); } @@ -232,7 +241,7 @@ public function errorCode() * @see https://www.php.net/manual/en/pdostatement.errorinfo.php * @codeCoverageIgnore */ - public function errorInfo() + public function errorInfo(): array { return $this->stmt->errorInfo(); } @@ -240,15 +249,15 @@ public function errorInfo() /** * Executes a prepared statement. * - * @param array $inputParameters + * @param array $params * @return bool * @see https://www.php.net/manual/en/pdostatement.execute.php */ - public function execute($inputParameters = null) + public function execute($params = null): bool { - if (\is_array($inputParameters)) { - foreach ($inputParameters as $parameter => $value) { - $this->bindValue(\is_int($parameter) ? $parameter + 1 : $parameter, $value); + if (is_array($params)) { + foreach ($params as $param => $value) { + $this->bindValue(is_int($param) ? $param + 1 : $param, $value); } } $this->benchmarks->container['query']['count']++; @@ -256,14 +265,14 @@ public function execute($inputParameters = null) $this->render(); $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { $result = $this->stmt->execute(); // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; $this->benchmarks->container['query']['time'] += $delay; $this->statementBenchmarks['query']['time'] += $delay; return $this->getResult($delay, $result, $e); @@ -272,118 +281,118 @@ public function execute($inputParameters = null) /** * Fetches the next row from a result set. * - * @param int $fetchStyle + * @param int $mode * @param int $cursorOrientation * @param int $cursorOffset * @return mixed * @see https://www.php.net/manual/en/pdostatement.fetch.php */ - public function fetch($fetchStyle = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) + public function fetch($mode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { - $result = $this->stmt->fetch($fetchStyle, $cursorOrientation, $cursorOffset); + $result = $this->stmt->fetch($mode, $cursorOrientation, $cursorOffset); // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; return $this->getFetchResult($delay, $result, $e); } /** * Fetches the remaining rows from a result set. * - * @param int $fetchStyle - * @param mixed $fetchArgument - * @param array $constructorArgs + * @param int $mode + * @param mixed $fetch_argument + * @param array $args Constructor arguments * @return array * @see https://www.php.net/manual/en/pdostatement.fetchall.php */ - public function fetchAll($fetchStyle = null, $fetchArgument = null, $constructorArgs = null) + public function fetchAll($mode = null, $fetch_argument = null, $args = null): array { $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { - if (null === $fetchStyle) { + if (null === $mode) { $result = $this->stmt->fetchAll(); - } elseif (null === $fetchArgument) { - $result = $this->stmt->fetchAll($fetchStyle); - } elseif (null === $constructorArgs) { - $result = $this->stmt->fetchAll($fetchStyle, $fetchArgument); + } elseif (null === $fetch_argument) { + $result = $this->stmt->fetchAll($mode); + } elseif (null === $args) { + $result = $this->stmt->fetchAll($mode, $fetch_argument); } else { - $result = $this->stmt->fetchAll($fetchStyle, $fetchArgument, $constructorArgs); + $result = $this->stmt->fetchAll($mode, $fetch_argument, $args); } // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; return $this->getFetchResult($delay, $result, $e); } /** * Returns a single column from the next row of a result set. * - * @param int $columnNumber + * @param int $column Column number * @return mixed * @see https://www.php.net/manual/en/pdostatement.fetchcolumn.php */ - public function fetchColumn($columnNumber = 0) + public function fetchColumn($column = 0) { $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { - $result = $this->stmt->fetchColumn($columnNumber); + $result = $this->stmt->fetchColumn($column); // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; return $this->getFetchResult($delay, $result, $e); } /** * Fetches the next row and returns it as an object. * - * @param string $className + * @param string $class * @param array $constructorArgs - * @return array + * @return object * @see https://www.php.net/manual/en/pdostatement.fetchobject.php */ - public function fetchObject($className = null, $constructorArgs = null) + public function fetchObject($class = null, $constructorArgs = null) { $result = null; $e = null; - $timeStamp = \microtime(true); + $timeStamp = microtime(true); try { if (null === $constructorArgs) { $constructorArgs = []; } - $result = $this->stmt->fetchObject($className, $constructorArgs); + $result = $this->stmt->fetchObject($class, $constructorArgs); // @codeCoverageIgnoreStart } catch (PDOException $e) { // @codeCoverageIgnoreEnd } - $delay = \microtime(true) - $timeStamp; + $delay = microtime(true) - $timeStamp; return $this->getFetchResult($delay, $result, $e); } /** * Retrieves a statement attribute. * - * @param int $attribute + * @param int $name * @return mixed * @see https://www.php.net/manual/en/pdostatement.getattribute.php * @codeCoverageIgnore */ - public function getAttribute($attribute) + public function getAttribute($name) { - return $this->stmt->getAttribute($attribute); + return $this->stmt->getAttribute($name); } /** @@ -394,7 +403,7 @@ public function getAttribute($attribute) * @see https://www.php.net/manual/en/pdostatement.getcolumnmeta.php * @codeCoverageIgnore */ - public function getColumnMeta($column) + public function getColumnMeta($column): array { return $this->stmt->getColumnMeta($column); } @@ -406,7 +415,7 @@ public function getColumnMeta($column) * @see https://www.php.net/manual/en/pdostatement.nextrowset.php * @codeCoverageIgnore */ - public function nextRowset() + public function nextRowset(): bool { return $this->stmt->nextRowset(); } @@ -418,7 +427,7 @@ public function nextRowset() * @see https://www.php.net/manual/en/pdostatement.rowcount.php * @codeCoverageIgnore */ - public function rowCount() + public function rowCount(): int { return $this->stmt->rowCount(); } @@ -432,7 +441,7 @@ public function rowCount() * @see https://www.php.net/manual/en/pdostatement.setattribute.php * @codeCoverageIgnore */ - public function setAttribute($attribute, $value) + public function setAttribute($attribute, $value): bool { return $this->stmt->setAttribute($attribute, $value); } @@ -446,7 +455,7 @@ public function setAttribute($attribute, $value) * @see https://www.php.net/manual/en/pdostatement.setfetchmode.php * @codeCoverageIgnore */ - public function setFetchMode($mode, $params = null) + public function setFetchMode($mode, $params = null): bool { return $this->stmt->setFetchMode($mode); } @@ -465,11 +474,11 @@ protected function scope(array &$scope) /** * Prepares query for logging. * - * @param string &$query + * @param string $query * @return void * @see ExcavatingTrait::after() */ - protected function prepareQueryForLogging(&$query) + protected function prepareQueryForLogging(string &$query) { } @@ -482,15 +491,15 @@ protected function prepareQueryForLogging(&$query) protected function render() { $query = $this->template; - if (\sizeof($this->values) > 0) { - $marker = \uniqid("-") . "-"; - $query = \str_replace("?", $marker, $query); - $search = \sprintf("/%s/", preg_quote($marker, "/")); + if (sizeof($this->values) > 0) { + $marker = uniqid("-") . "-"; + $query = str_replace("?", $marker, $query); + $search = sprintf("/%s/", preg_quote($marker, "/")); foreach ($this->values as $field => $data) { $dataType = $data[1] & ~PDO::PARAM_INPUT_OUTPUT; switch ($dataType) { case PDO::PARAM_BOOL: - $value = \is_int($data[0]) ? (int)(bool)$data[0] : $data[0]; + $value = is_int($data[0]) ? (int)(bool)$data[0] : $data[0]; break; case PDO::PARAM_INT: $value = (int)$data[0]; @@ -499,19 +508,19 @@ protected function render() $value = $this->pdo->quote($data[0], $data[1]); break; } - $query = \is_string($field) - ? \str_replace( + $query = is_string($field) + ? str_replace( ":$field", $value, $query ) : preg_replace($search, $value, $query); } - $query = \str_replace($marker, "?", $query); + $query = str_replace($marker, "?", $query); } $this->lastExecutedQuery = $query; $this->before([ - 'source' => \sprintf("%s::execute", __CLASS__), + 'source' => sprintf("%s::execute", __CLASS__), 'query' => $query, ]); } @@ -528,7 +537,7 @@ protected function render() * @see self::fetchColumn() * @see self::fetchObject() */ - protected function getFetchResult($delay, $result, PDOException $e = null) + protected function getFetchResult(float $delay, $result, PDOException $e = null) { $this->benchmarks->container['fetch']['count']++; $this->statementBenchmarks['fetch']['count']++; diff --git a/src/Tools.php b/src/Tools.php index 935201a..0eb77e2 100644 --- a/src/Tools.php +++ b/src/Tools.php @@ -12,6 +12,14 @@ use PDO; use PDOStatement; +use function array_keys; +use function array_map; +use function array_merge; +use function array_values; +use function implode; +use function preg_match; +use function sprintf; + /** * PDO related library. * @@ -54,44 +62,44 @@ class Tools * @return PDOStatement */ public static function prepareModifyingStatement( - $pdo, - $template, + PDO $pdo, + string $template, array $record, array $types = [], array $rawValues = [] - ) { - $fields = \array_map( + ): PDOStatement { + $fields = array_map( function ($field) { - return \sprintf("`%s`", $field); + return sprintf("`%s`", $field); }, array_merge(array_keys($record), array_keys($rawValues)) ); - $placeholders = \array_merge( - \array_map( + $placeholders = array_merge( + array_map( function ($field) { - return \sprintf(":%s", $field); + return sprintf(":%s", $field); }, - \array_keys($record) + array_keys($record) ), - \array_values($rawValues) + array_values($rawValues) ); - if (\preg_match("/^\s?insert\s+/i", $template)) { - $query = \sprintf( + if (preg_match("/^\s?insert\s+/i", $template)) { + $query = sprintf( $template, - \sprintf( + sprintf( "(%s) VALUES (%s)", - \implode(", ", $fields), - \implode(", ", $placeholders) + implode(", ", $fields), + implode(", ", $placeholders) ) ); } else { $set = []; foreach ($fields as $index => $field) { - $set[] = \sprintf("%s = %s", $field, $placeholders[$index]); + $set[] = sprintf("%s = %s", $field, $placeholders[$index]); } - $query = \sprintf( + $query = sprintf( $template, - \sprintf("SET %s", implode(", ", $set)) + sprintf("SET %s", implode(", ", $set)) ); } diff --git a/tests/CommonTest.php b/tests/CommonTest.php index c572379..8286311 100644 --- a/tests/CommonTest.php +++ b/tests/CommonTest.php @@ -13,6 +13,11 @@ use PDOException; use stdClass; +use function array_values; +use function get_class; +use function is_object; +use function sizeof; + /** * Common tests. */ @@ -68,7 +73,7 @@ public function testGetAvailableDrivers() */ public function testClasses() { - $pdo = $this->connectDatabase(); + $pdo = self::connectDatabase(); $benchmarks = $pdo->getBenchmarks(); $totalTime = $benchmarks['total']['time']; unset($benchmarks['total']); @@ -132,7 +137,7 @@ public function testClasses() self::assertGreaterThan(0, $benchmarks->container['fetch']['time']); $stmt->closeCursor(); $stmt->execute(); - self::assertEquals([\array_values($record)], $stmt->fetchAll(PDO::FETCH_NUM)); + self::assertEquals([array_values($record)], $stmt->fetchAll(PDO::FETCH_NUM)); $stmt->closeCursor(); $stmt->execute(); self::assertEquals([100500], $stmt->fetchAll(PDO::FETCH_COLUMN, 0)); @@ -170,8 +175,8 @@ public function testClasses() * @var stdClass $result */ $result = $stmt->fetch(); - self::assertTrue(\is_object($result)); - self::assertEquals("stdClass", \get_class($result)); + self::assertTrue(is_object($result)); + self::assertEquals("stdClass", get_class($result)); self::assertEquals(5, $benchmarks->container['fetch']['count']); $stmt = $pdo->query( @@ -196,7 +201,7 @@ public function testClasses() self::assertEquals("1", $stmt->fetchColumn()); $stmt->closeCursor(); $stmt->execute(); - self::assertEquals($expected, $stmt->fetchObject("stdClass")); + self::assertEquals($expected, $stmt->fetchObject()); $stmt = $pdo->prepare("SELECT ?"); $stmt->bindValue(1, 100500, PDO::PARAM_BOOL); @@ -220,7 +225,7 @@ public function testWithLoggerAndNonemptySources() self::$log = []; $logger = new Logger(self::$log); - $pdo = $this->connectDatabase([ + $pdo = self::connectDatabase([ 'logger' => $logger, 'sources' => [ "/^PDOStatementExcavated::/", @@ -228,20 +233,20 @@ public function testWithLoggerAndNonemptySources() ]); $stmt = $pdo->prepare("SELECT ?"); $stmt->execute(["ED"]); - self::assertEquals(1, \sizeof(self::$log)); + self::assertEquals(1, sizeof(self::$log)); $pdo->query("SELECT 1"); - self::assertEquals(1, \sizeof(self::$log)); + self::assertEquals(1, sizeof(self::$log)); $stmt = $pdo->prepare("SELECT ?"); $stmt->bindValue(1, 100500, PDO::PARAM_INT); $stmt->execute(); - self::assertEquals(2, \sizeof(self::$log)); + self::assertEquals(2, sizeof(self::$log)); $stmt = $pdo->prepare("SELECT ?"); $stmt->bindValue(1, 100500, PDO::PARAM_INT); $stmt->execute(); self::$log = []; - $pdo = $this->connectDatabase([ + $pdo = self::connectDatabase([ 'logger' => $logger, 'sources' => [ "/^PDOExcavated::/", @@ -260,9 +265,9 @@ public function testWithLoggerAndNonemptySources() */ public function testExceptionOnWrongQuery() { - $pdo = $this->connectDatabase(); + $pdo = self::connectDatabase(); $this->expectException(PDOException::class); - $stmt = $pdo->query("SOME KIND OF SHIT"); + $pdo->query("SOME KIND OF SHIT"); } /** @@ -273,7 +278,7 @@ public function testExceptionOnWrongQuery() */ public function testExceptionOnInvalidCommit() { - $pdo = $this->connectDatabase(); + $pdo = self::connectDatabase(); $this->expectException(PDOException::class); $this->expectExceptionMessage("There is no active transaction"); $pdo->commit(); diff --git a/tests/ExtendedClassesTest.php b/tests/ExtendedClassesTest.php index cbf2ec3..7d0db45 100644 --- a/tests/ExtendedClassesTest.php +++ b/tests/ExtendedClassesTest.php @@ -11,19 +11,26 @@ use PDO; +/** + * Autoload doesn't work in PHP 7.0 / PHPUnit "^6". + * + * @todo Explore possibility to avoid inclusion of the file in PHP >=7.1 + * phpcs:disable + */ +require_once "./tests/src/PDOExcavatedExtended.php"; +// phpcs:enable + /** * Extended PDOExcavated and PDOStatementExcavated classes tests. */ class ExtendedClassesTest extends TestCaseConfigAndDatabase { - public function testGetAvailableDrivers() + public function testExtension() { - $logger = new Logger(self::$log); - self::$log = []; $logger = new Logger(self::$log); - $pdo = $this->connectDatabase( + $pdo = self::connectDatabase( [ 'logger' => $logger, 'format' => [ diff --git a/tests/src/Logger.php b/tests/src/Logger.php index 7a7a428..48c9b5e 100644 --- a/tests/src/Logger.php +++ b/tests/src/Logger.php @@ -38,7 +38,7 @@ public function __construct(array &$log) * @param array $scope * @return void */ - public function log($message, array $scope) + public function log(string $message, array $scope) { // echo "$message\n"; $this->log[] = $message; diff --git a/tests/src/PDOExcavatedExtended.php b/tests/src/PDOExcavatedExtended.php index cde7321..6803ae0 100644 --- a/tests/src/PDOExcavatedExtended.php +++ b/tests/src/PDOExcavatedExtended.php @@ -23,7 +23,7 @@ class PDOExcavatedExtended extends PDOExcavated * @return void * @see ExcavatingTrait::after() */ - protected function prepareQueryForLogging(&$query) + protected function prepareQueryForLogging(string &$query) { } @@ -43,11 +43,11 @@ protected function scope(array &$scope) * Method used to replace PDOStatementExcavated by possible child. * * @param string $template - * @param PDOStatementExcavated $stmt + * @param PDOStatement $stmt * @return PDOStatementExcavatedExtended * @see self::getResultStatement() */ - protected function getStatement($template, PDOStatement $stmt) + protected function getStatement(string $template, PDOStatement $stmt): PDOStatementExcavated { return new PDOStatementExcavatedExtended($template, $this, $stmt); } diff --git a/tests/src/PDOStatementExcavatedExtended.php b/tests/src/PDOStatementExcavatedExtended.php index 2d6c9ef..60c670a 100644 --- a/tests/src/PDOStatementExcavatedExtended.php +++ b/tests/src/PDOStatementExcavatedExtended.php @@ -33,7 +33,7 @@ protected function scope(array &$scope) * @return void * @link ExcavatingTrait::after() */ - protected function prepareQueryForLogging(&$query) + protected function prepareQueryForLogging(string &$query) { } } diff --git a/tests/src/TestCaseConfigAndDatabase.php b/tests/src/TestCaseConfigAndDatabase.php index faad94b..53a3add 100644 --- a/tests/src/TestCaseConfigAndDatabase.php +++ b/tests/src/TestCaseConfigAndDatabase.php @@ -9,10 +9,18 @@ namespace deepeloper\PDO; -use PDO; use PHPUnit\Framework\TestCase; use RuntimeException; +use function array_replace_recursive; +use function is_array; +use function ob_end_clean; +use function ob_get_contents; +use function ob_start; +use function passthru; +use function sprintf; +use function var_export; + /** * Config and database related functionality. */ @@ -46,7 +54,7 @@ public static function setUpBeforeClass() parent::setUpBeforeClass(); static::$config = require("tests/config/config.php"); - $command = \sprintf( + $command = sprintf( static::$config['db']['commands']['create'], static::$config['db']['username'] ); @@ -61,7 +69,7 @@ public static function setUpBeforeClass() public static function tearDownAfterClass() { if (isset(self::$config['db']['commands']['drop'])) { - $command = \sprintf( + $command = sprintf( self::$config['db']['commands']['drop'], self::$config['db']['username'], self::$config['db']['name'] @@ -78,17 +86,17 @@ public static function tearDownAfterClass() * @param string $command * @return void */ - protected static function executeCommand($command) + protected static function executeCommand(string $command) { - \ob_start(); - \passthru($command, $result); - $output = \ob_get_contents(); - \ob_end_clean(); + ob_start(); + passthru($command, $result); + $output = ob_get_contents(); + ob_end_clean(); if (0 !== $result) { - throw new RuntimeException(\sprintf( + throw new RuntimeException(sprintf( "Cannot execute '%s' command, output: %s", $command, - \var_export($output, true) + var_export($output, true) )); } } @@ -100,19 +108,19 @@ protected static function executeCommand($command) * @param string $pdoClassName * @return PDOExcavated */ - protected function connectDatabase( + protected static function connectDatabase( array $debuggingOptions = null, - $pdoClassName = "\\deepeloper\\PDO\\PDOExcavated" - ) { + string $pdoClassName = "\\deepeloper\\PDO\\PDOExcavated" + ): PDOExcavated { $options = static::$config['db']['options']; - if (\is_array($debuggingOptions)) { - $options[PDOExcavated::ATTR_DEBUG] = \array_replace_recursive( + if (is_array($debuggingOptions)) { + $options[PDOExcavated::ATTR_DEBUG] = array_replace_recursive( $options[PDOExcavated::ATTR_DEBUG], $debuggingOptions ); } return new $pdoClassName( - \sprintf(static::$config['db']['dsn'], static::$config['db']['name']), + sprintf(static::$config['db']['dsn'], static::$config['db']['name']), static::$config['db']['username'], static::$config['db']['password'], $options