From b772c5ee792e7933efa23454e24c8337572f0155 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 25 Sep 2020 10:41:42 +0700 Subject: [PATCH 01/18] apply rector: set local variable name to camel case --- .github/workflows/test-rector.yml | 45 +++++++++++ composer.json | 3 +- rector.php | 27 +++++++ system/Autoloader/Autoloader.php | 8 +- system/Autoloader/FileLocator.php | 16 ++-- system/CLI/CLI.php | 60 +++++++-------- system/Cache/Handlers/FileHandler.php | 26 +++---- system/Cache/Handlers/MemcachedHandler.php | 4 +- system/Cache/Handlers/PredisHandler.php | 4 +- system/Cache/Handlers/RedisHandler.php | 4 +- system/Common.php | 8 +- system/Database/BaseBuilder.php | 76 +++++++++---------- system/Database/BaseConnection.php | 20 ++--- system/Database/BaseResult.php | 16 +++- system/Database/BaseUtils.php | 6 +- system/Database/Forge.php | 4 +- system/Database/MySQLi/Connection.php | 10 +-- system/Database/MySQLi/Forge.php | 8 +- system/Database/MySQLi/Result.php | 4 +- system/Database/Postgre/Connection.php | 4 +- system/Database/SQLite3/Result.php | 4 +- system/Debug/Iterator.php | 8 +- system/Debug/Toolbar/Views/toolbar.tpl.php | 2 +- system/Email/Email.php | 56 +++++++------- system/Encryption/Handlers/OpenSSLHandler.php | 8 +- system/HTTP/CURLRequest.php | 20 ++--- system/HTTP/DownloadResponse.php | 20 ++--- system/HTTP/Files/FileCollection.php | 8 +- system/HTTP/Message.php | 30 ++++---- system/HTTP/Negotiate.php | 8 +- system/HTTP/Request.php | 16 ++-- system/HTTP/UserAgent.php | 6 +- system/Helpers/filesystem_helper.php | 10 +-- system/Helpers/form_helper.php | 8 +- system/Helpers/html_helper.php | 6 +- system/Helpers/number_helper.php | 28 +++---- system/Helpers/text_helper.php | 14 ++-- system/Helpers/url_helper.php | 36 ++++----- system/Honeypot/Honeypot.php | 4 +- system/Images/Handlers/GDHandler.php | 4 +- system/Log/Handlers/FileHandler.php | 8 +- system/Router/RouteCollection.php | 24 +++--- system/Router/Router.php | 6 +- system/Security/Security.php | 10 +-- system/Session/Handlers/FileHandler.php | 8 +- system/Session/Handlers/MemcachedHandler.php | 26 +++---- system/Session/Handlers/RedisHandler.php | 22 +++--- system/Session/Session.php | 28 +++---- system/Test/Mock/MockCommon.php | 6 +- system/Test/ReflectionHelper.php | 26 +++---- system/Test/TestLogger.php | 4 +- system/Typography/Typography.php | 10 +-- system/Validation/Rules.php | 8 +- system/Validation/Validation.php | 16 ++-- system/View/Cell.php | 20 ++--- system/View/Parser.php | 4 +- 56 files changed, 481 insertions(+), 394 deletions(-) create mode 100644 .github/workflows/test-rector.yml create mode 100644 rector.php diff --git a/.github/workflows/test-rector.yml b/.github/workflows/test-rector.yml new file mode 100644 index 000000000000..210398390294 --- /dev/null +++ b/.github/workflows/test-rector.yml @@ -0,0 +1,45 @@ +# When a PR is opened or a push is made, perform +# a static analysis check on the code using Rector. +name: Rector + +on: + pull_request: + branches: + - 'develop' + - '4.*' + paths: + - 'app/**' + - 'system/**' + push: + branches: + - 'develop' + - '4.*' + paths: + - 'app/**' + - 'system/**' + +jobs: + build: + name: Analyze code (Rector) + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '7.4' + extensions: intl + + - name: Use latest Composer + run: composer self-update + + - name: Validate composer.json + run: composer validate --strict + + - name: Install dependencies + run: composer install --ansi --no-progress --no-suggest --no-interaction + + - name: Run static analysis + run: vendor/bin/rector process --dry-run diff --git a/composer.json b/composer.json index dbbd2661fa90..fc5856b3f33e 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,8 @@ "phpstan/phpstan": "^0.12", "phpunit/phpunit": "^8.5", "predis/predis": "^1.1", - "squizlabs/php_codesniffer": "^3.3" + "squizlabs/php_codesniffer": "^3.3", + "rector/rector": "dev-failing-test-case-4290" }, "autoload": { "psr-4": { diff --git a/rector.php b/rector.php new file mode 100644 index 000000000000..b693ce668ea1 --- /dev/null +++ b/rector.php @@ -0,0 +1,27 @@ +parameters(); + + // paths to refactor; solid alternative to CLI arguments + $parameters->set(Option::PATHS, [__DIR__ . '/app', __DIR__ . '/system']); + + // is there a file you need to skip? + $parameters->set(Option::EXCLUDE_PATHS, [ + __DIR__ . '/app/Views', + __DIR__ . '/system/ThirdParty', + ]); + + // Rector relies on autoload setup of your project; Composer autoload is included by default; to add more: + $parameters->set(Option::AUTOLOAD_PATHS, [ + // autoload specific file + __DIR__ . '/system/Test/bootstrap.php', + ]); + + $services = $containerConfigurator->services(); + $services->set(UnderscoreToCamelCaseLocalVariableNameRector::class); +}; diff --git a/system/Autoloader/Autoloader.php b/system/Autoloader/Autoloader.php index a5ce8a4525b9..fd07d89cac73 100644 --- a/system/Autoloader/Autoloader.php +++ b/system/Autoloader/Autoloader.php @@ -262,16 +262,16 @@ public function loadClass(string $class) $class = trim($class, '\\'); $class = str_ireplace('.php', '', $class); - $mapped_file = $this->loadInNamespace($class); + $mappedFile = $this->loadInNamespace($class); // Nothing? One last chance by looking // in common CodeIgniter folders. - if (! $mapped_file) + if (! $mappedFile) { - $mapped_file = $this->loadLegacy($class); + $mappedFile = $this->loadLegacy($class); } - return $mapped_file; + return $mappedFile; } //-------------------------------------------------------------------- diff --git a/system/Autoloader/FileLocator.php b/system/Autoloader/FileLocator.php index 9e516468c734..fc87beb07868 100644 --- a/system/Autoloader/FileLocator.php +++ b/system/Autoloader/FileLocator.php @@ -169,11 +169,11 @@ public function locateFile(string $file, string $folder = null, string $ext = 'p */ public function getClassname(string $file) : string { - $php = file_get_contents($file); - $tokens = token_get_all($php); - $dlm = false; - $namespace = ''; - $class_name = ''; + $php = file_get_contents($file); + $tokens = token_get_all($php); + $dlm = false; + $namespace = ''; + $className = ''; foreach ($tokens as $i => $token) { @@ -202,17 +202,17 @@ public function getClassname(string $file) : string && $tokens[$i - 1][0] === T_WHITESPACE && $token[0] === T_STRING) { - $class_name = $token[1]; + $className = $token[1]; break; } } - if (empty( $class_name )) + if (empty( $className )) { return ''; } - return $namespace . '\\' . $class_name; + return $namespace . '\\' . $className; } //-------------------------------------------------------------------- diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index 1ee6d45d345c..c4343dfcbf41 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -257,37 +257,37 @@ public static function input(string $prefix = null): string */ public static function prompt(string $field, $options = null, string $validation = null): string { - $extra_output = ''; - $default = ''; + $extraOutput = ''; + $default = ''; if (is_string($options)) { - $extra_output = ' [' . static::color($options, 'white') . ']'; - $default = $options; + $extraOutput = ' [' . static::color($options, 'white') . ']'; + $default = $options; } if (is_array($options) && $options) { - $opts = $options; - $extra_output_default = static::color($opts[0], 'white'); + $opts = $options; + $extraOutputDefault = static::color($opts[0], 'white'); unset($opts[0]); if (empty($opts)) { - $extra_output = $extra_output_default; + $extraOutput = $extraOutputDefault; } else { - $extra_output = ' [' . $extra_output_default . ', ' . implode(', ', $opts) . ']'; - $validation .= '|in_list[' . implode(',', $options) . ']'; - $validation = trim($validation, '|'); + $extraOutput = ' [' . $extraOutputDefault . ', ' . implode(', ', $opts) . ']'; + $validation .= '|in_list[' . implode(',', $options) . ']'; + $validation = trim($validation, '|'); } $default = $options[0]; } - static::fwrite(STDOUT, $field . $extra_output . ': '); + static::fwrite(STDOUT, $field . $extraOutput . ': '); // Read the input from keyboard. $input = trim(static::input()) ?: $default; @@ -1070,45 +1070,45 @@ public static function getOptionString(bool $useLongOpts = false, bool $trim = f public static function table(array $tbody, array $thead = []) { // All the rows in the table will be here until the end - $table_rows = []; + $tableRows = []; // We need only indexes and not keys if (! empty($thead)) { - $table_rows[] = array_values($thead); + $tableRows[] = array_values($thead); } foreach ($tbody as $tr) { - $table_rows[] = array_values($tr); + $tableRows[] = array_values($tr); } // Yes, it really is necessary to know this count - $total_rows = count($table_rows); + $totalRows = count($tableRows); // Store all columns lengths // $all_cols_lengths[row][column] = length - $all_cols_lengths = []; + $allColsLengths = []; // Store maximum lengths by column // $max_cols_lengths[column] = length - $max_cols_lengths = []; + $maxColsLengths = []; // Read row by row and define the longest columns - for ($row = 0; $row < $total_rows; $row ++) + for ($row = 0; $row < $totalRows; $row ++) { $column = 0; // Current column index - foreach ($table_rows[$row] as $col) + foreach ($tableRows[$row] as $col) { // Sets the size of this column in the current row - $all_cols_lengths[$row][$column] = static::strlen($col); + $allColsLengths[$row][$column] = static::strlen($col); // If the current column does not have a value among the larger ones // or the value of this is greater than the existing one // then, now, this assumes the maximum length - if (! isset($max_cols_lengths[$column]) || $all_cols_lengths[$row][$column] > $max_cols_lengths[$column]) + if (! isset($maxColsLengths[$column]) || $allColsLengths[$row][$column] > $maxColsLengths[$column]) { - $max_cols_lengths[$column] = $all_cols_lengths[$row][$column]; + $maxColsLengths[$column] = $allColsLengths[$row][$column]; } // We can go check the size of the next column... @@ -1118,15 +1118,15 @@ public static function table(array $tbody, array $thead = []) // Read row by row and add spaces at the end of the columns // to match the exact column length - for ($row = 0; $row < $total_rows; $row ++) + for ($row = 0; $row < $totalRows; $row ++) { $column = 0; - foreach ($table_rows[$row] as $col) + foreach ($tableRows[$row] as $col) { - $diff = $max_cols_lengths[$column] - static::strlen($col); + $diff = $maxColsLengths[$column] - static::strlen($col); if ($diff) { - $table_rows[$row][$column] = $table_rows[$row][$column] . str_repeat(' ', $diff); + $tableRows[$row][$column] = $tableRows[$row][$column] . str_repeat(' ', $diff); } $column ++; } @@ -1135,13 +1135,13 @@ public static function table(array $tbody, array $thead = []) $table = ''; // Joins columns and append the well formatted rows to the table - for ($row = 0; $row < $total_rows; $row ++) + for ($row = 0; $row < $totalRows; $row ++) { // Set the table border-top if ($row === 0) { $cols = '+'; - foreach ($table_rows[$row] as $col) + foreach ($tableRows[$row] as $col) { $cols .= str_repeat('-', static::strlen($col) + 2) . '+'; } @@ -1149,10 +1149,10 @@ public static function table(array $tbody, array $thead = []) } // Set the columns borders - $table .= '| ' . implode(' | ', $table_rows[$row]) . ' |' . PHP_EOL; + $table .= '| ' . implode(' | ', $tableRows[$row]) . ' |' . PHP_EOL; // Set the thead and table borders-bottom - if (isset($cols) && ($row === 0 && ! empty($thead) || $row + 1 === $total_rows)) + if (isset($cols) && ($row === 0 && ! empty($thead) || $row + 1 === $totalRows)) { $table .= $cols . PHP_EOL; } diff --git a/system/Cache/Handlers/FileHandler.php b/system/Cache/Handlers/FileHandler.php index f80d21567536..3291e6634473 100644 --- a/system/Cache/Handlers/FileHandler.php +++ b/system/Cache/Handlers/FileHandler.php @@ -185,9 +185,9 @@ public function increment(string $key, int $offset = 1) return false; } - $new_value = $data['data'] + $offset; + $newValue = $data['data'] + $offset; - return $this->save($key, $new_value, $data['ttl']) ? $new_value : false; + return $this->save($key, $newValue, $data['ttl']) ? $newValue : false; } //-------------------------------------------------------------------- @@ -218,9 +218,9 @@ public function decrement(string $key, int $offset = 1) return false; } - $new_value = $data['data'] - $offset; + $newValue = $data['data'] - $offset; - return $this->save($key, $new_value, $data['ttl']) ? $new_value : false; + return $this->save($key, $newValue, $data['ttl']) ? $newValue : false; } //-------------------------------------------------------------------- @@ -394,12 +394,12 @@ protected function deleteFiles(string $path, bool $del_dir = false, bool $htdocs // Trim the trailing slash $path = rtrim($path, '/\\'); - if (! $current_dir = @opendir($path)) + if (! $currentDir = @opendir($path)) { return false; } - while (false !== ($filename = @readdir($current_dir))) + while (false !== ($filename = @readdir($currentDir))) { if ($filename !== '.' && $filename !== '..') { @@ -414,7 +414,7 @@ protected function deleteFiles(string $path, bool $del_dir = false, bool $htdocs } } - closedir($current_dir); + closedir($currentDir); return ($del_dir === true && $_level > 0) ? @rmdir($path) : true; } @@ -437,15 +437,15 @@ protected function deleteFiles(string $path, bool $del_dir = false, bool $htdocs */ protected function getDirFileInfo(string $source_dir, bool $top_level_only = true, bool $_recursion = false) { - static $_filedata = []; - $relative_path = $source_dir; + static $filedata = []; + $relativePath = $source_dir; if ($fp = @opendir($source_dir)) { // reset the array and make sure $source_dir has a trailing slash on the initial call if ($_recursion === false) { - $_filedata = []; + $filedata = []; $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } @@ -458,14 +458,14 @@ protected function getDirFileInfo(string $source_dir, bool $top_level_only = tru } elseif ($file[0] !== '.') { - $_filedata[$file] = $this->getFileInfo($source_dir . $file); - $_filedata[$file]['relative_path'] = $relative_path; + $filedata[$file] = $this->getFileInfo($source_dir . $file); + $filedata[$file]['relative_path'] = $relativePath; } } closedir($fp); - return $_filedata; + return $filedata; } return false; diff --git a/system/Cache/Handlers/MemcachedHandler.php b/system/Cache/Handlers/MemcachedHandler.php index d1676eefbc55..1b421c5251b3 100644 --- a/system/Cache/Handlers/MemcachedHandler.php +++ b/system/Cache/Handlers/MemcachedHandler.php @@ -148,12 +148,12 @@ public function initialize() $this->memcached = new \Memcache(); // Check if we can connect to the server - $can_connect = $this->memcached->connect( + $canConnect = $this->memcached->connect( $this->config['host'], $this->config['port'] ); // If we can't connect, throw a CriticalError exception - if ($can_connect === false) + if ($canConnect === false) { throw new CriticalError('Cache: Memcache connection failed.'); } diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index bdfcea07fa96..4e57ceef2548 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -167,7 +167,7 @@ public function get(string $key) */ public function save(string $key, $value, int $ttl = 60) { - switch ($data_type = gettype($value)) + switch ($dataType = gettype($value)) { case 'array': case 'object': @@ -184,7 +184,7 @@ public function save(string $key, $value, int $ttl = 60) return false; } - if (! $this->redis->hmset($key, ['__ci_type' => $data_type, '__ci_value' => $value])) + if (! $this->redis->hmset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) { return false; } diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index d392a7959742..8ea9e5b06409 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -202,7 +202,7 @@ public function save(string $key, $value, int $ttl = 60) { $key = $this->prefix . $key; - switch ($data_type = gettype($value)) + switch ($dataType = gettype($value)) { case 'array': case 'object': @@ -219,7 +219,7 @@ public function save(string $key, $value, int $ttl = 60) return false; } - if (! $this->redis->hMSet($key, ['__ci_type' => $data_type, '__ci_value' => $value])) + if (! $this->redis->hMSet($key, ['__ci_type' => $dataType, '__ci_value' => $value])) { return false; } diff --git a/system/Common.php b/system/Common.php index 538e351d2a18..62d06ff5e66e 100644 --- a/system/Common.php +++ b/system/Common.php @@ -602,16 +602,16 @@ function force_https(int $duration = 31536000, RequestInterface $request = null, */ function function_usable(string $function_name): bool { - static $_suhosin_func_blacklist; + static $suhosinFuncBlacklist; if (function_exists($function_name)) { - if (! isset($_suhosin_func_blacklist)) + if (! isset($suhosinFuncBlacklist)) { - $_suhosin_func_blacklist = extension_loaded('suhosin') ? explode(',', trim(ini_get('suhosin.executor.func.blacklist'))) : []; + $suhosinFuncBlacklist = extension_loaded('suhosin') ? explode(',', trim(ini_get('suhosin.executor.func.blacklist'))) : []; } - return ! in_array($function_name, $_suhosin_func_blacklist, true); + return ! in_array($function_name, $suhosinFuncBlacklist, true); } return false; diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index ab3c8205ef1f..c6a06c13a111 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -1291,16 +1291,16 @@ protected function _like($field, string $match = '', string $type = 'AND ', stri $bind = $this->setBind($k, "%$v%", $escape); } - $like_statement = $this->_like_statement($prefix, $k, $not, $bind, $insensitiveSearch); + $likeStatement = $this->_like_statement($prefix, $k, $not, $bind, $insensitiveSearch); // some platforms require an escape sequence definition for LIKE wildcards if ($escape === true && $this->db->likeEscapeStr !== '') { - $like_statement .= sprintf($this->db->likeEscapeStr, $this->db->likeEscapeChar); + $likeStatement .= sprintf($this->db->likeEscapeStr, $this->db->likeEscapeChar); } $this->{$clause}[] = [ - 'condition' => $like_statement, + 'condition' => $likeStatement, 'escape' => $escape, ]; } @@ -1323,14 +1323,14 @@ protected function _like($field, string $match = '', string $type = 'AND ', stri */ protected function _like_statement(string $prefix = null, string $column, string $not = null, string $bind, bool $insensitiveSearch = false): string { - $like_statement = "{$prefix} {$column} {$not} LIKE :{$bind}:"; + $likeStatement = "{$prefix} {$column} {$not} LIKE :{$bind}:"; if ($insensitiveSearch === true) { - $like_statement = "{$prefix} LOWER({$column}) {$not} LIKE :{$bind}:"; + $likeStatement = "{$prefix} LOWER({$column}) {$not} LIKE :{$bind}:"; } - return $like_statement; + return $likeStatement; } //-------------------------------------------------------------------- @@ -1636,7 +1636,7 @@ public function orderBy(string $orderBy, string $direction = '', bool $escape = if ($escape === false) { - $qb_orderBy[] = [ + $qbOrderBy[] = [ 'field' => $orderBy, 'direction' => $direction, 'escape' => false, @@ -1644,10 +1644,10 @@ public function orderBy(string $orderBy, string $direction = '', bool $escape = } else { - $qb_orderBy = []; + $qbOrderBy = []; foreach (explode(',', $orderBy) as $field) { - $qb_orderBy[] = ($direction === '' && preg_match('/\s+(ASC|DESC)$/i', rtrim($field), $match, PREG_OFFSET_CAPTURE)) + $qbOrderBy[] = ($direction === '' && preg_match('/\s+(ASC|DESC)$/i', rtrim($field), $match, PREG_OFFSET_CAPTURE)) ? [ 'field' => ltrim(substr($field, 0, $match[0][1])), @@ -1663,7 +1663,7 @@ public function orderBy(string $orderBy, string $direction = '', bool $escape = } } - $this->QBOrderBy = array_merge($this->QBOrderBy, $qb_orderBy); + $this->QBOrderBy = array_merge($this->QBOrderBy, $qbOrderBy); return $this; } @@ -2085,19 +2085,19 @@ public function insertBatch(array $set = null, bool $escape = null, int $batchSi $table = $this->QBFrom[0]; // Batch this baby - $affected_rows = 0; + $affectedRows = 0; for ($i = 0, $total = count($this->QBSet); $i < $total; $i += $batchSize) { $sql = $this->_insertBatch($this->db->protectIdentifiers($table, true, $escape, false), $this->QBKeys, array_slice($this->QBSet, $i, $batchSize)); if ($this->testMode) { - ++ $affected_rows; + ++ $affectedRows; } else { $this->db->query($sql, $this->binds, false); - $affected_rows += $this->db->affectedRows(); + $affectedRows += $this->db->affectedRows(); } } @@ -2106,7 +2106,7 @@ public function insertBatch(array $set = null, bool $escape = null, int $batchSi $this->resetWrite(); } - return $affected_rows; + return $affectedRows; } //-------------------------------------------------------------------- @@ -2591,9 +2591,9 @@ public function updateBatch(array $set = null, string $index = null, int $batchS $table = $this->QBFrom[0]; // Batch this baby - $affected_rows = 0; - $savedSQL = []; - $savedQBWhere = $this->QBWhere; + $affectedRows = 0; + $savedSQL = []; + $savedQBWhere = $this->QBWhere; for ($i = 0, $total = count($this->QBSet); $i < $total; $i += $batchSize) { $sql = $this->_updateBatch($table, array_slice($this->QBSet, $i, $batchSize), $this->db->protectIdentifiers($index) @@ -2606,7 +2606,7 @@ public function updateBatch(array $set = null, string $index = null, int $batchS else { $this->db->query($sql, $this->binds, false); - $affected_rows += $this->db->affectedRows(); + $affectedRows += $this->db->affectedRows(); } $this->QBWhere = $savedQBWhere; @@ -2614,7 +2614,7 @@ public function updateBatch(array $set = null, string $index = null, int $batchS $this->resetWrite(); - return $this->testMode ? $savedSQL : $affected_rows; + return $this->testMode ? $savedSQL : $affectedRows; } //-------------------------------------------------------------------- @@ -2686,13 +2686,13 @@ public function setUpdateBatch($key, string $index = '', bool $escape = null) foreach ($key as $v) { - $index_set = false; - $clean = []; + $indexSet = false; + $clean = []; foreach ($v as $k2 => $v2) { if ($k2 === $index) { - $index_set = true; + $indexSet = true; } $bind = $this->setBind($k2, $v2, $escape); @@ -2700,7 +2700,7 @@ public function setUpdateBatch($key, string $index = '', bool $escape = null) $clean[$this->db->protectIdentifiers($k2, false, $escape)] = ":$bind:"; } - if ($index_set === false) + if ($indexSet === false) { throw new DatabaseException('One or more rows submitted for batch updating is missing the specified index.'); } @@ -2992,8 +2992,8 @@ protected function compileSelect($select_override = false): string // is because until the user calls the from() function we don't know if there are aliases foreach ($this->QBSelect as $key => $val) { - $no_escape = $this->QBNoEscape[$key] ?? null; - $this->QBSelect[$key] = $this->db->protectIdentifiers($val, false, $no_escape); + $noEscape = $this->QBNoEscape[$key] ?? null; + $this->QBSelect[$key] = $this->db->protectIdentifiers($val, false, $noEscape); } $sql .= implode(', ', $this->QBSelect); @@ -3300,14 +3300,14 @@ protected function isLiteral(string $str): bool return true; } - static $_str; + static $str; - if (empty($_str)) + if (empty($str)) { - $_str = ($this->db->escapeChar !== '"') ? ['"', "'"] : ["'"]; + $str = ($this->db->escapeChar !== '"') ? ['"', "'"] : ["'"]; } - return in_array($str[0], $_str, true); + return in_array($str[0], $str, true); } //-------------------------------------------------------------------- @@ -3338,9 +3338,9 @@ public function resetQuery() */ protected function resetRun(array $qb_reset_items) { - foreach ($qb_reset_items as $item => $default_value) + foreach ($qb_reset_items as $item => $defaultValue) { - $this->$item = $default_value; + $this->$item = $defaultValue; } } @@ -3422,12 +3422,12 @@ protected function hasOperator(string $str): bool */ protected function getOperator(string $str, bool $list = false) { - static $_operators; + static $operators; - if (empty($_operators)) + if (empty($operators)) { - $_les = ($this->db->likeEscapeStr !== '') ? '\s+' . preg_quote(trim(sprintf($this->db->likeEscapeStr, $this->db->likeEscapeChar)), '/') : ''; - $_operators = [ + $les = ($this->db->likeEscapeStr !== '') ? '\s+' . preg_quote(trim(sprintf($this->db->likeEscapeStr, $this->db->likeEscapeChar)), '/') : ''; + $operators = [ '\s*(?:<|>|!)?=\s*', // =, <=, >=, != '\s*<>?\s*', // <, <> '\s*>\s*', // > @@ -3438,12 +3438,12 @@ protected function getOperator(string $str, bool $list = false) '\s+BETWEEN\s+', // BETWEEN value AND value '\s+IN\s*\(.*\)', // IN(list) '\s+NOT IN\s*\(.*\)', // NOT IN (list) - '\s+LIKE\s+\S.*(' . $_les . ')?', // LIKE 'expr'[ ESCAPE '%s'] - '\s+NOT LIKE\s+\S.*(' . $_les . ')?', // NOT LIKE 'expr'[ ESCAPE '%s'] + '\s+LIKE\s+\S.*(' . $les . ')?', // LIKE 'expr'[ ESCAPE '%s'] + '\s+NOT LIKE\s+\S.*(' . $les . ')?', // NOT LIKE 'expr'[ ESCAPE '%s'] ]; } - return preg_match_all('/' . implode('|', $_operators) . '/i', $str, $match) ? ($list ? $match[0] : $match[0][0]) : false; + return preg_match_all('/' . implode('|', $operators) . '/i', $str, $match) ? ($list ? $match[0] : $match[0][0]) : false; } // -------------------------------------------------------------------- diff --git a/system/Database/BaseConnection.php b/system/Database/BaseConnection.php index c7a3bb202cb6..693ae210857e 100644 --- a/system/Database/BaseConnection.php +++ b/system/Database/BaseConnection.php @@ -1106,13 +1106,13 @@ public function protectIdentifiers($item, bool $prefixSingle = false, bool $prot if (is_array($item)) { - $escaped_array = []; + $escapedArray = []; foreach ($item as $k => $v) { - $escaped_array[$this->protectIdentifiers($k)] = $this->protectIdentifiers($v, $prefixSingle, $protectIdentifiers, $fieldExists); + $escapedArray[$this->protectIdentifiers($k)] = $this->protectIdentifiers($v, $prefixSingle, $protectIdentifiers, $fieldExists); } - return $escaped_array; + return $escapedArray; } // This is basically a bug fix for queries that use MAX, MIN, etc. @@ -1296,13 +1296,13 @@ public function escapeIdentifiers($item) return $item; } - static $preg_ec = []; + static $pregEc = []; - if (empty($preg_ec)) + if (empty($pregEc)) { if (is_array($this->escapeChar)) { - $preg_ec = [ + $pregEc = [ preg_quote($this->escapeChar[0], '/'), preg_quote($this->escapeChar[1], '/'), $this->escapeChar[0], @@ -1311,8 +1311,8 @@ public function escapeIdentifiers($item) } else { - $preg_ec[0] = $preg_ec[1] = preg_quote($this->escapeChar, '/'); - $preg_ec[2] = $preg_ec[3] = $this->escapeChar; + $pregEc[0] = $pregEc[1] = preg_quote($this->escapeChar, '/'); + $pregEc[2] = $pregEc[3] = $this->escapeChar; } } @@ -1320,11 +1320,11 @@ public function escapeIdentifiers($item) { if (strpos($item, '.' . $id) !== false) { - return preg_replace('/' . $preg_ec[0] . '?([^' . $preg_ec[1] . '\.]+)' . $preg_ec[1] . '?\./i', $preg_ec[2] . '$1' . $preg_ec[3] . '.', $item); + return preg_replace('/' . $pregEc[0] . '?([^' . $pregEc[1] . '\.]+)' . $pregEc[1] . '?\./i', $pregEc[2] . '$1' . $pregEc[3] . '.', $item); } } - return preg_replace('/' . $preg_ec[0] . '?([^' . $preg_ec[1] . '\.]+)' . $preg_ec[1] . '?(\.)?/i', $preg_ec[2] . '$1' . $preg_ec[3] . '$2', $item); + return preg_replace('/' . $pregEc[0] . '?([^' . $pregEc[1] . '\.]+)' . $pregEc[1] . '?(\.)?/i', $pregEc[2] . '$1' . $pregEc[3] . '$2', $item); } //-------------------------------------------------------------------- diff --git a/system/Database/BaseResult.php b/system/Database/BaseResult.php index 10d2c7f444cd..f040cbb91821 100644 --- a/system/Database/BaseResult.php +++ b/system/Database/BaseResult.php @@ -165,22 +165,36 @@ public function getCustomResultObject(string $className) } // Don't fetch the result set again if we already have it + /** + * @noRector \Rector\CodingStyle\Rector\Variable\UnderscoreToCamelCaseLocalVariableNameRector + */ $_data = null; if (($c = count($this->resultArray)) > 0) { + /** + * @noRector \Rector\CodingStyle\Rector\Variable\UnderscoreToCamelCaseLocalVariableNameRector + */ $_data = 'resultArray'; } elseif (($c = count($this->resultObject)) > 0) { + /** + * @noRector \Rector\CodingStyle\Rector\Variable\UnderscoreToCamelCaseLocalVariableNameRector + */ $_data = 'resultObject'; } + /** + * @noRector \Rector\CodingStyle\Rector\Variable\UnderscoreToCamelCaseLocalVariableNameRector + */ if ($_data !== null) { for ($i = 0; $i < $c; $i ++) { $this->customResultObject[$className][$i] = new $className(); - + /** + * @noRector \Rector\CodingStyle\Rector\Variable\UnderscoreToCamelCaseLocalVariableNameRector + */ foreach ($this->{$_data}[$i] as $key => $value) { $this->customResultObject[$className][$i]->$key = $value; diff --git a/system/Database/BaseUtils.php b/system/Database/BaseUtils.php index 1c5fff1dcc19..567403d78168 100644 --- a/system/Database/BaseUtils.php +++ b/system/Database/BaseUtils.php @@ -193,9 +193,9 @@ public function optimizeDatabase() } $result = []; - foreach ($this->db->listTables() as $table_name) + foreach ($this->db->listTables() as $tableName) { - $res = $this->db->query(sprintf($this->optimizeTable, $this->db->escapeIdentifiers($table_name))); + $res = $this->db->query(sprintf($this->optimizeTable, $this->db->escapeIdentifiers($tableName))); if (is_bool($res)) { return $res; @@ -208,7 +208,7 @@ public function optimizeDatabase() // Postgre & SQLite3 returns empty array if (empty($res)) { - $key = $table_name; + $key = $tableName; } else { diff --git a/system/Database/Forge.php b/system/Database/Forge.php index ac0235e81bcc..c3fb1b6f2b34 100644 --- a/system/Database/Forge.php +++ b/system/Database/Forge.php @@ -1300,9 +1300,9 @@ protected function _processForeignKeys(string $table): string { foreach ($this->foreignKeys as $field => $fkey) { - $name_index = $table . '_' . $field . '_foreign'; + $nameIndex = $table . '_' . $field . '_foreign'; - $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($name_index) + $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($nameIndex) . ' FOREIGN KEY(' . $this->db->escapeIdentifiers($field) . ') REFERENCES ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $fkey['table']) . ' (' . $this->db->escapeIdentifiers($fkey['field']) . ')'; if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions, true)) diff --git a/system/Database/MySQLi/Connection.php b/system/Database/MySQLi/Connection.php index 1c6de4232853..4f83c7700a10 100644 --- a/system/Database/MySQLi/Connection.php +++ b/system/Database/MySQLi/Connection.php @@ -106,7 +106,7 @@ public function connect(bool $persistent = false) $socket = ''; } - $client_flags = ($this->compress === true) ? MYSQLI_CLIENT_COMPRESS : 0; + $clientFlags = ($this->compress === true) ? MYSQLI_CLIENT_COMPRESS : 0; $this->mysqli = mysqli_init(); mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX); @@ -161,11 +161,11 @@ public function connect(bool $persistent = false) // https://bugs.php.net/bug.php?id=68344 elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT') && version_compare($this->mysqli->client_info, '5.6', '>=')) { - $client_flags += MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT; + $clientFlags += MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT; } } - $client_flags += MYSQLI_CLIENT_SSL; + $clientFlags += MYSQLI_CLIENT_SSL; $this->mysqli->ssl_set( $ssl['key'] ?? null, $ssl['cert'] ?? null, $ssl['ca'] ?? null, $ssl['capath'] ?? null, $ssl['cipher'] ?? null @@ -176,11 +176,11 @@ public function connect(bool $persistent = false) try { if ($this->mysqli->real_connect($hostname, $this->username, $this->password, - $this->database, $port, $socket, $client_flags) + $this->database, $port, $socket, $clientFlags) ) { // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails - if (($client_flags & MYSQLI_CLIENT_SSL) && version_compare($this->mysqli->client_info, '5.7.3', '<=') + if (($clientFlags & MYSQLI_CLIENT_SSL) && version_compare($this->mysqli->client_info, '5.7.3', '<=') && empty($this->mysqli->query("SHOW STATUS LIKE 'ssl_cipher'") ->fetch_object()->Value) ) diff --git a/system/Database/MySQLi/Forge.php b/system/Database/MySQLi/Forge.php index 5755c1aecf20..6dd7c40c4b08 100644 --- a/system/Database/MySQLi/Forge.php +++ b/system/Database/MySQLi/Forge.php @@ -212,11 +212,11 @@ protected function _alterTable(string $alter_type, string $table, $field) */ protected function _processColumn(array $field): string { - $extra_clause = isset($field['after']) ? ' AFTER ' . $this->db->escapeIdentifiers($field['after']) : ''; + $extraClause = isset($field['after']) ? ' AFTER ' . $this->db->escapeIdentifiers($field['after']) : ''; - if (empty($extra_clause) && isset($field['first']) && $field['first'] === true) + if (empty($extraClause) && isset($field['first']) && $field['first'] === true) { - $extra_clause = ' FIRST'; + $extraClause = ' FIRST'; } return $this->db->escapeIdentifiers($field['name']) @@ -228,7 +228,7 @@ protected function _processColumn(array $field): string . $field['auto_increment'] . $field['unique'] . (empty($field['comment']) ? '' : ' COMMENT ' . $field['comment']) - . $extra_clause; + . $extraClause; } //-------------------------------------------------------------------- diff --git a/system/Database/MySQLi/Result.php b/system/Database/MySQLi/Result.php index eb929b538b8d..24c0ea9b9ac1 100644 --- a/system/Database/MySQLi/Result.php +++ b/system/Database/MySQLi/Result.php @@ -87,7 +87,7 @@ public function getFieldNames(): array */ public function getFieldData(): array { - static $data_types = [ + static $dataTypes = [ MYSQLI_TYPE_DECIMAL => 'decimal', MYSQLI_TYPE_NEWDECIMAL => 'newdecimal', MYSQLI_TYPE_FLOAT => 'float', @@ -128,7 +128,7 @@ public function getFieldData(): array $retVal[$i]->name = $data->name; $retVal[$i]->type = $data->type; $retVal[$i]->type_name = in_array($data->type, [1, 247], true) - ? 'char' : (isset($data_types[$data->type]) ? $data_types[$data->type] : null); + ? 'char' : (isset($dataTypes[$data->type]) ? $dataTypes[$data->type] : null); $retVal[$i]->max_length = $data->max_length; $retVal[$i]->primary_key = (int) ($data->flags & 2); $retVal[$i]->length = $data->length; diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index 40fdb2b8a881..e86c0bba7767 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -369,10 +369,10 @@ public function _indexData(string $table): array { $obj = new \stdClass(); $obj->name = $row->indexname; - $_fields = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef))); + $fields = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef))); $obj->fields = array_map(function ($v) { return trim($v); - }, $_fields); + }, $fields); if (strpos($row->indexdef, 'CREATE UNIQUE INDEX pk') === 0) { diff --git a/system/Database/SQLite3/Result.php b/system/Database/SQLite3/Result.php index f6b96638639d..c66df671b43b 100644 --- a/system/Database/SQLite3/Result.php +++ b/system/Database/SQLite3/Result.php @@ -86,7 +86,7 @@ public function getFieldNames(): array */ public function getFieldData(): array { - static $data_types = [ + static $dataTypes = [ SQLITE3_INTEGER => 'integer', SQLITE3_FLOAT => 'float', SQLITE3_TEXT => 'text', @@ -103,7 +103,7 @@ public function getFieldData(): array $retVal[$i]->name = $this->resultID->columnName($i); // @phpstan-ignore-line $type = $this->resultID->columnType($i); // @phpstan-ignore-line $retVal[$i]->type = $type; - $retVal[$i]->type_name = isset($data_types[$type]) ? $data_types[$type] : null; + $retVal[$i]->type_name = isset($dataTypes[$type]) ? $dataTypes[$type] : null; $retVal[$i]->max_length = null; $retVal[$i]->length = null; } diff --git a/system/Debug/Iterator.php b/system/Debug/Iterator.php index c9101df11a31..ed8dadd34283 100644 --- a/system/Debug/Iterator.php +++ b/system/Debug/Iterator.php @@ -99,21 +99,21 @@ public function run(int $iterations = 1000, bool $output = true) // clear memory before start gc_collect_cycles(); - $start = microtime(true); - $start_mem = $max_memory = memory_get_usage(true); + $start = microtime(true); + $startMem = $maxMemory = memory_get_usage(true); for ($i = 0; $i < $iterations; $i ++) { $result = $test(); - $max_memory = max($max_memory, memory_get_usage(true)); + $maxMemory = max($maxMemory, memory_get_usage(true)); unset($result); } $this->results[$name] = [ 'time' => microtime(true) - $start, - 'memory' => $max_memory - $start_mem, + 'memory' => $maxMemory - $startMem, 'n' => $iterations, ]; } diff --git a/system/Debug/Toolbar/Views/toolbar.tpl.php b/system/Debug/Toolbar/Views/toolbar.tpl.php index 5f5d7c43a6f1..8c826c0464f0 100644 --- a/system/Debug/Toolbar/Views/toolbar.tpl.php +++ b/system/Debug/Toolbar/Views/toolbar.tpl.php @@ -99,7 +99,7 @@ 89 -104 206 -162 247 -17 13 -18 12 -11 -15z"/> - + diff --git a/system/Email/Email.php b/system/Email/Email.php index 14ea1eb665d6..a86e6815411b 100644 --- a/system/Email/Email.php +++ b/system/Email/Email.php @@ -1208,27 +1208,27 @@ protected function buildMessage() $this->appendAttachments($body, $boundary); break; case 'html-attach': - $alt_boundary = uniqid('B_ALT_', true); - $last_boundary = null; + $altBoundary = uniqid('B_ALT_', true); + $lastBoundary = null; if ($this->attachmentsHaveMultipart('mixed')) { - $atc_boundary = uniqid('B_ATC_', true); - $hdr .= 'Content-Type: multipart/mixed; boundary="' . $atc_boundary . '"'; - $last_boundary = $atc_boundary; + $atcBoundary = uniqid('B_ATC_', true); + $hdr .= 'Content-Type: multipart/mixed; boundary="' . $atcBoundary . '"'; + $lastBoundary = $atcBoundary; } if ($this->attachmentsHaveMultipart('related')) { - $rel_boundary = uniqid('B_REL_', true); - $rel_boundary_header = 'Content-Type: multipart/related; boundary="' . $rel_boundary . '"'; - if (isset($last_boundary)) + $relBoundary = uniqid('B_REL_', true); + $relBoundaryHeader = 'Content-Type: multipart/related; boundary="' . $relBoundary . '"'; + if (isset($lastBoundary)) { - $body .= '--' . $last_boundary . $this->newline . $rel_boundary_header; + $body .= '--' . $lastBoundary . $this->newline . $relBoundaryHeader; } else { - $hdr .= $rel_boundary_header; + $hdr .= $relBoundaryHeader; } - $last_boundary = $rel_boundary; + $lastBoundary = $relBoundary; } if ($this->getProtocol() === 'mail') { @@ -1236,27 +1236,27 @@ protected function buildMessage() } static::strlen($body) && $body .= $this->newline . $this->newline; $body .= $this->getMimeMessage() . $this->newline . $this->newline - . '--' . $last_boundary . $this->newline - . 'Content-Type: multipart/alternative; boundary="' . $alt_boundary . '"' . $this->newline . $this->newline - . '--' . $alt_boundary . $this->newline + . '--' . $lastBoundary . $this->newline + . 'Content-Type: multipart/alternative; boundary="' . $altBoundary . '"' . $this->newline . $this->newline + . '--' . $altBoundary . $this->newline . 'Content-Type: text/plain; charset=' . $this->charset . $this->newline . 'Content-Transfer-Encoding: ' . $this->getEncoding() . $this->newline . $this->newline . $this->getAltMessage() . $this->newline . $this->newline - . '--' . $alt_boundary . $this->newline + . '--' . $altBoundary . $this->newline . 'Content-Type: text/html; charset=' . $this->charset . $this->newline . 'Content-Transfer-Encoding: quoted-printable' . $this->newline . $this->newline . $this->prepQuotedPrintable($this->body) . $this->newline . $this->newline - . '--' . $alt_boundary . '--' . $this->newline . $this->newline; - if (! empty($rel_boundary)) + . '--' . $altBoundary . '--' . $this->newline . $this->newline; + if (! empty($relBoundary)) { $body .= $this->newline . $this->newline; - $this->appendAttachments($body, $rel_boundary, 'related'); + $this->appendAttachments($body, $relBoundary, 'related'); } // multipart/mixed attachments - if (! empty($atc_boundary)) + if (! empty($atcBoundary)) { $body .= $this->newline . $this->newline; - $this->appendAttachments($body, $atc_boundary, 'mixed'); + $this->appendAttachments($body, $atcBoundary, 'mixed'); } break; } @@ -1321,7 +1321,7 @@ protected function prepQuotedPrintable($str) // ASCII code numbers for "safe" characters that can always be // used literally, without encoding, as described in RFC 2049. // http://www.ietf.org/rfc/rfc2049.txt - static $ascii_safe_chars = [ + static $asciiSafeChars = [ // ' ( ) + , - . / : = ? 39, 40, @@ -1448,7 +1448,7 @@ protected function prepQuotedPrintable($str) { $char = $escape . strtoupper(sprintf('%02s', dechex($ascii))); // =3D } - elseif (! in_array($ascii, $ascii_safe_chars, true)) + elseif (! in_array($ascii, $asciiSafeChars, true)) { $char = $escape . strtoupper(sprintf('%02s', dechex($ascii))); } @@ -2113,12 +2113,12 @@ public function printDebugger($include = ['headers', 'subject', 'body']) { $msg = implode('', $this->debugMessage); // Determine which parts of our raw data needs to be printed - $raw_data = ''; - is_array($include) || $include = [$include]; // @phpstan-ignore-line - in_array('headers', $include, true) && $raw_data = htmlspecialchars($this->headerStr) . "\n"; - in_array('subject', $include, true) && $raw_data .= htmlspecialchars($this->subject) . "\n"; - in_array('body', $include, true) && $raw_data .= htmlspecialchars($this->finalBody); - return $msg . ($raw_data === '' ? '' : '
' . $raw_data . '
'); + $rawData = ''; + is_array($include) || $include = [$include]; // @phpstan-ignore-line + in_array('headers', $include, true) && $rawData = htmlspecialchars($this->headerStr) . "\n"; + in_array('subject', $include, true) && $rawData .= htmlspecialchars($this->subject) . "\n"; + in_array('body', $include, true) && $rawData .= htmlspecialchars($this->finalBody); + return $msg . ($rawData === '' ? '' : '
' . $rawData . '
'); } //-------------------------------------------------------------------- /** diff --git a/system/Encryption/Handlers/OpenSSLHandler.php b/system/Encryption/Handlers/OpenSSLHandler.php index de65e616a3f9..488c501b9250 100644 --- a/system/Encryption/Handlers/OpenSSLHandler.php +++ b/system/Encryption/Handlers/OpenSSLHandler.php @@ -94,7 +94,7 @@ public function encrypt($data, $params = null) $secret = \hash_hkdf($this->digest, $this->key); // basic encryption - $iv = ($iv_size = \openssl_cipher_iv_length($this->cipher)) ? \openssl_random_pseudo_bytes($iv_size) : null; + $iv = ($ivSize = \openssl_cipher_iv_length($this->cipher)) ? \openssl_random_pseudo_bytes($ivSize) : null; $data = \openssl_encrypt($data, $this->cipher, $secret, OPENSSL_RAW_DATA, $iv); @@ -146,10 +146,10 @@ public function decrypt($data, $params = null) throw EncryptionException::forAuthenticationFailed(); } - if ($iv_size = \openssl_cipher_iv_length($this->cipher)) + if ($ivSize = \openssl_cipher_iv_length($this->cipher)) { - $iv = self::substr($data, 0, $iv_size); - $data = self::substr($data, $iv_size); + $iv = self::substr($data, 0, $ivSize); + $data = self::substr($data, $ivSize); } else { diff --git a/system/HTTP/CURLRequest.php b/system/HTTP/CURLRequest.php index 336f22bad093..33547796da34 100644 --- a/system/HTTP/CURLRequest.php +++ b/system/HTTP/CURLRequest.php @@ -418,7 +418,7 @@ public function getMethod(bool $upper = false): string public function send(string $method, string $url) { // Reset our curl options so we're on a fresh slate. - $curl_options = []; + $curlOptions = []; if (! empty($this->config['query']) && is_array($this->config['query'])) { @@ -429,16 +429,16 @@ public function send(string $method, string $url) unset($this->config['query']); } - $curl_options[CURLOPT_URL] = $url; - $curl_options[CURLOPT_RETURNTRANSFER] = true; - $curl_options[CURLOPT_HEADER] = true; - $curl_options[CURLOPT_FRESH_CONNECT] = true; + $curlOptions[CURLOPT_URL] = $url; + $curlOptions[CURLOPT_RETURNTRANSFER] = true; + $curlOptions[CURLOPT_HEADER] = true; + $curlOptions[CURLOPT_FRESH_CONNECT] = true; // Disable @file uploads in post data. - $curl_options[CURLOPT_SAFE_UPLOAD] = true; + $curlOptions[CURLOPT_SAFE_UPLOAD] = true; - $curl_options = $this->setCURLOptions($curl_options, $this->config); - $curl_options = $this->applyMethod($method, $curl_options); - $curl_options = $this->applyRequestHeaders($curl_options); + $curlOptions = $this->setCURLOptions($curlOptions, $this->config); + $curlOptions = $this->applyMethod($method, $curlOptions); + $curlOptions = $this->applyRequestHeaders($curlOptions); // Do we need to delay this request? if ($this->delay > 0) @@ -446,7 +446,7 @@ public function send(string $method, string $url) sleep($this->delay); // @phpstan-ignore-line } - $output = $this->sendRequest($curl_options); + $output = $this->sendRequest($curlOptions); // Set the string we want to break our response from $breakString = "\r\n\r\n"; diff --git a/system/HTTP/DownloadResponse.php b/system/HTTP/DownloadResponse.php index 37ae9bd17e4d..1baa30cdcc08 100644 --- a/system/HTTP/DownloadResponse.php +++ b/system/HTTP/DownloadResponse.php @@ -182,9 +182,9 @@ private function setContentTypeByMimeType() if ($this->setMime === true) { - if (($last_dot_position = strrpos($this->filename, '.')) !== false) + if (($lastDotPosition = strrpos($this->filename, '.')) !== false) { - $mime = Mimes::guessTypeFromExtension(substr($this->filename, $last_dot_position + 1)); + $mime = Mimes::guessTypeFromExtension(substr($this->filename, $lastDotPosition + 1)); $charset = $this->charset; } } @@ -234,20 +234,20 @@ private function getDownloadFileName(): string */ private function getContentDisposition() : string { - $download_filename = $this->getDownloadFileName(); + $downloadFilename = $this->getDownloadFileName(); - $utf8_filename = $download_filename; + $utf8Filename = $downloadFilename; if (strtoupper($this->charset) !== 'UTF-8') { - $utf8_filename = mb_convert_encoding($download_filename, 'UTF-8', $this->charset); + $utf8Filename = mb_convert_encoding($downloadFilename, 'UTF-8', $this->charset); } - $result = sprintf('attachment; filename="%s"', $download_filename); + $result = sprintf('attachment; filename="%s"', $downloadFilename); - if ($utf8_filename) + if ($utf8Filename) { - $result .= '; filename*=UTF-8\'\'' . rawurlencode($utf8_filename); + $result .= '; filename*=UTF-8\'\'' . rawurlencode($utf8Filename); } return $result; @@ -526,10 +526,10 @@ public function sendBody() */ private function sendBodyByFilePath() { - $spl_file_object = $this->file->openFile('rb'); + $splFileObject = $this->file->openFile('rb'); // Flush 1MB chunks of data - while (! $spl_file_object->eof() && ($data = $spl_file_object->fread(1048576)) !== false) + while (! $splFileObject->eof() && ($data = $splFileObject->fread(1048576)) !== false) { echo $data; } diff --git a/system/HTTP/Files/FileCollection.php b/system/HTTP/Files/FileCollection.php index fb62ccd036d6..7cdcc724f135 100644 --- a/system/HTTP/Files/FileCollection.php +++ b/system/HTTP/Files/FileCollection.php @@ -312,14 +312,14 @@ protected function getValueDotNotationSyntax(array $index, array $value) { if (! empty($index)) { - $current_index = array_shift($index); + $currentIndex = array_shift($index); } - if (isset($current_index) && is_array($index) && $index && is_array($value[$current_index]) && $value[$current_index]) + if (isset($currentIndex) && is_array($index) && $index && is_array($value[$currentIndex]) && $value[$currentIndex]) { - return $this->getValueDotNotationSyntax($index, $value[$current_index]); + return $this->getValueDotNotationSyntax($index, $value[$currentIndex]); } - return (isset($current_index) && isset($value[$current_index])) ? $value[$current_index] : null; + return (isset($currentIndex) && isset($value[$currentIndex])) ? $value[$currentIndex] : null; } } diff --git a/system/HTTP/Message.php b/system/HTTP/Message.php index 3f58de9c15b1..0c70b4b278da 100644 --- a/system/HTTP/Message.php +++ b/system/HTTP/Message.php @@ -189,14 +189,14 @@ public function getHeaders(): array */ public function getHeader(string $name) { - $orig_name = $this->getHeaderName($name); + $origName = $this->getHeaderName($name); - if (! isset($this->headers[$orig_name])) + if (! isset($this->headers[$origName])) { return null; } - return $this->headers[$orig_name]; + return $this->headers[$origName]; } /** @@ -208,9 +208,9 @@ public function getHeader(string $name) */ public function hasHeader(string $name): bool { - $orig_name = $this->getHeaderName($name); + $origName = $this->getHeaderName($name); - return isset($this->headers[$orig_name]); + return isset($this->headers[$origName]); } /** @@ -230,14 +230,14 @@ public function hasHeader(string $name): bool */ public function getHeaderLine(string $name): string { - $orig_name = $this->getHeaderName($name); + $origName = $this->getHeaderName($name); - if (! array_key_exists($orig_name, $this->headers)) + if (! array_key_exists($origName, $this->headers)) { return ''; } - return $this->headers[$orig_name]->getValueLine(); + return $this->headers[$origName]->getValueLine(); } /** @@ -282,9 +282,9 @@ public function setHeader(string $name, $value): self */ public function removeHeader(string $name): self { - $orig_name = $this->getHeaderName($name); + $origName = $this->getHeaderName($name); - unset($this->headers[$orig_name]); + unset($this->headers[$origName]); unset($this->headerMap[strtolower($name)]); return $this; @@ -301,10 +301,10 @@ public function removeHeader(string $name): self */ public function appendHeader(string $name, ?string $value): self { - $orig_name = $this->getHeaderName($name); + $origName = $this->getHeaderName($name); - array_key_exists($orig_name, $this->headers) - ? $this->headers[$orig_name]->appendValue($value) + array_key_exists($origName, $this->headers) + ? $this->headers[$origName]->appendValue($value) : $this->setHeader($name, $value); return $this; @@ -321,9 +321,9 @@ public function appendHeader(string $name, ?string $value): self */ public function prependHeader(string $name, string $value): self { - $orig_name = $this->getHeaderName($name); + $origName = $this->getHeaderName($name); - $this->headers[$orig_name]->prependValue($value); + $this->headers[$origName]->prependValue($value); return $this; } diff --git a/system/HTTP/Negotiate.php b/system/HTTP/Negotiate.php index 793e1344945b..46ee46ac587e 100644 --- a/system/HTTP/Negotiate.php +++ b/system/HTTP/Negotiate.php @@ -297,8 +297,8 @@ public function parseHeader(string $header): array usort($results, function ($a, $b) { if ($a['q'] === $b['q']) { - $a_ast = substr_count($a['value'], '*'); - $b_ast = substr_count($b['value'], '*'); + $aAst = substr_count($a['value'], '*'); + $bAst = substr_count($b['value'], '*'); // '*/*' has lower precedence than 'text/*', // and 'text/*' has lower priority than 'text/plain' @@ -306,7 +306,7 @@ public function parseHeader(string $header): array // This seems backwards, but needs to be that way // due to the way PHP7 handles ordering or array // elements created by reference. - if ($a_ast > $b_ast) + if ($aAst > $bAst) { return 1; } @@ -317,7 +317,7 @@ public function parseHeader(string $header): array // This seems backwards, but needs to be that way // due to the way PHP7 handles ordering or array // elements created by reference. - if ($a_ast === $b_ast) + if ($aAst === $bAst) { return count($b['params']) - count($a['params']); } diff --git a/system/HTTP/Request.php b/system/HTTP/Request.php index 8c64f1623ed2..8e0ff0e0ac53 100644 --- a/system/HTTP/Request.php +++ b/system/HTTP/Request.php @@ -105,15 +105,15 @@ public function getIPAddress(): string return $this->ipAddress; } - $proxy_ips = $this->proxyIPs; + $proxyIps = $this->proxyIPs; if (! empty($this->proxyIPs) && ! is_array($this->proxyIPs)) { - $proxy_ips = explode(',', str_replace(' ', '', $this->proxyIPs)); + $proxyIps = explode(',', str_replace(' ', '', $this->proxyIPs)); } $this->ipAddress = $this->getServer('REMOTE_ADDR'); - if ($proxy_ips) + if ($proxyIps) { foreach (['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'] as $header) { @@ -137,14 +137,14 @@ public function getIPAddress(): string if ($spoof) { - foreach ($proxy_ips as $proxy_ip) + foreach ($proxyIps as $proxyIp) { // Check if we have an IP address or a subnet - if (strpos($proxy_ip, '/') === false) + if (strpos($proxyIp, '/') === false) { // An IP address (and not a subnet) is specified. // We can compare right away. - if ($proxy_ip === $this->ipAddress) + if ($proxyIp === $this->ipAddress) { $this->ipAddress = $spoof; break; @@ -158,7 +158,7 @@ public function getIPAddress(): string isset($separator) || $separator = $this->isValidIP($this->ipAddress, 'ipv6') ? ':' : '.'; // If the proxy entry doesn't match the IP protocol - skip it - if (strpos($proxy_ip, $separator) === false) // @phpstan-ignore-line + if (strpos($proxyIp, $separator) === false) // @phpstan-ignore-line { continue; } @@ -190,7 +190,7 @@ public function getIPAddress(): string } // Split the netmask length off the network address - sscanf($proxy_ip, '%[^/]/%d', $netaddr, $masklen); + sscanf($proxyIp, '%[^/]/%d', $netaddr, $masklen); // Again, an IPv6 address is most likely in a compressed form if ($separator === ':') // @phpstan-ignore-line diff --git a/system/HTTP/UserAgent.php b/system/HTTP/UserAgent.php index 4f7777ac75f6..83ff93ea7455 100644 --- a/system/HTTP/UserAgent.php +++ b/system/HTTP/UserAgent.php @@ -238,10 +238,10 @@ public function isReferral(): bool } else { - $referer_host = @parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); - $own_host = parse_url(\base_url(), PHP_URL_HOST); + $refererHost = @parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); + $ownHost = parse_url(\base_url(), PHP_URL_HOST); - $this->referrer = ($referer_host && $referer_host !== $own_host); + $this->referrer = ($refererHost && $refererHost !== $ownHost); } } diff --git a/system/Helpers/filesystem_helper.php b/system/Helpers/filesystem_helper.php index 54a18d502533..368803548792 100644 --- a/system/Helpers/filesystem_helper.php +++ b/system/Helpers/filesystem_helper.php @@ -68,7 +68,7 @@ function directory_map(string $source_dir, int $directory_depth = 0, bool $hidde $fp = opendir($source_dir); $fileData = []; - $new_depth = $directory_depth - 1; + $newDepth = $directory_depth - 1; $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; while (false !== ($file = readdir($fp))) @@ -81,9 +81,9 @@ function directory_map(string $source_dir, int $directory_depth = 0, bool $hidde is_dir($source_dir . $file) && $file .= DIRECTORY_SEPARATOR; - if (($directory_depth < 1 || $new_depth > 0) && is_dir($source_dir . $file)) + if (($directory_depth < 1 || $newDepth > 0) && is_dir($source_dir . $file)) { - $fileData[$file] = directory_map($source_dir . $file, $new_depth, $hidden); + $fileData[$file] = directory_map($source_dir . $file, $newDepth, $hidden); } else { @@ -290,7 +290,7 @@ function get_filenames(string $source_dir, ?bool $include_path = false, bool $hi function get_dir_file_info(string $source_dir, bool $top_level_only = true, bool $recursion = false): array { static $fileData = []; - $relative_path = $source_dir; + $relativePath = $source_dir; try { @@ -312,7 +312,7 @@ function get_dir_file_info(string $source_dir, bool $top_level_only = true, bool elseif ($file[0] !== '.') { $fileData[$file] = get_file_info($source_dir . $file); - $fileData[$file]['relative_path'] = $relative_path; + $fileData[$file]['relative_path'] = $relativePath; } } diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index 554c54940984..e6aefb76f47c 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -421,11 +421,11 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): continue; } $form .= '\n"; - foreach ($val as $optgroup_key => $optgroup_val) + foreach ($val as $optgroupKey => $optgroupVal) { - $sel = in_array($optgroup_key, $selected, true) ? ' selected="selected"' : ''; - $form .= '\n"; + $sel = in_array($optgroupKey, $selected, true) ? ' selected="selected"' : ''; + $form .= '\n"; } $form .= "\n"; } diff --git a/system/Helpers/html_helper.php b/system/Helpers/html_helper.php index 53ba7b0b7747..85455a7b0be6 100755 --- a/system/Helpers/html_helper.php +++ b/system/Helpers/html_helper.php @@ -109,10 +109,10 @@ function _list(string $type = 'ul', $list = [], $attributes = '', int $depth = 0 // Cycle through the list elements. If an array is // encountered we will recursively call _list() - static $_last_list_item = ''; + static $lastListItem = ''; foreach ($list as $key => $val) { - $_last_list_item = $key; + $lastListItem = $key; $out .= str_repeat(' ', $depth + 2) . '
  • '; @@ -122,7 +122,7 @@ function _list(string $type = 'ul', $list = [], $attributes = '', int $depth = 0 } else { - $out .= $_last_list_item + $out .= $lastListItem . "\n" . _list($type, $val, '', $depth + 4) . str_repeat(' ', $depth + 2); diff --git a/system/Helpers/number_helper.php b/system/Helpers/number_helper.php index 57d3db70a0d6..e8d253cb4d00 100644 --- a/system/Helpers/number_helper.php +++ b/system/Helpers/number_helper.php @@ -280,25 +280,25 @@ function number_to_roman(string $num): ?string return null; } - $_number_to_roman = function ($num, $th) use (&$_number_to_roman) { + $numberToRoman = function ($num, $th) use (&$numberToRoman) { $return = ''; $key1 = null; $key2 = null; switch ($th) { case 1: - $key1 = 'I'; - $key2 = 'V'; - $key_f = 'X'; + $key1 = 'I'; + $key2 = 'V'; + $keyF = 'X'; break; case 2: - $key1 = 'X'; - $key2 = 'L'; - $key_f = 'C'; + $key1 = 'X'; + $key2 = 'L'; + $keyF = 'C'; break; case 3: - $key1 = 'C'; - $key2 = 'D'; - $key_f = 'M'; + $key1 = 'C'; + $key2 = 'D'; + $keyF = 'M'; break; case 4: $key1 = 'M'; @@ -323,20 +323,20 @@ function number_to_roman(string $num): ?string $return = $key2 . str_repeat($key1, $n - 5); break; case 9: - $return = $key1 . $key_f; // @phpstan-ignore-line + $return = $key1 . $keyF; // @phpstan-ignore-line break; } switch ($num) { case 10: - $return = $key_f; // @phpstan-ignore-line + $return = $keyF; // @phpstan-ignore-line break; } if ($num > 10) { - $return = $_number_to_roman($num / 10, ++ $th) . $return; + $return = $numberToRoman($num / 10, ++ $th) . $return; } return $return; }; - return $_number_to_roman($num, 1); + return $numberToRoman($num, 1); } } diff --git a/system/Helpers/text_helper.php b/system/Helpers/text_helper.php index 6f4ef5b413ab..0dfababbdc47 100755 --- a/system/Helpers/text_helper.php +++ b/system/Helpers/text_helper.php @@ -423,26 +423,26 @@ function highlight_phrase(string $str, string $phrase, string $tag_open = 'characterList) || ! is_array($config->characterList)) { - $array_from = []; - $array_to = []; + $arrayFrom = []; + $arrayTo = []; return $str; } - $array_from = array_keys($config->characterList); - $array_to = array_values($config->characterList); + $arrayFrom = array_keys($config->characterList); + $arrayTo = array_values($config->characterList); unset($config); } - return preg_replace($array_from, $array_to, $str); + return preg_replace($arrayFrom, $arrayTo, $str); } } diff --git a/system/Helpers/url_helper.php b/system/Helpers/url_helper.php index 7ad2ad84a7a4..38c5d2ac3bfa 100644 --- a/system/Helpers/url_helper.php +++ b/system/Helpers/url_helper.php @@ -270,13 +270,13 @@ function anchor($uri = '', string $title = '', $attributes = '', \Config\App $al // use alternate config if provided, else default one $config = $altConfig ?? config(\Config\App::class); - $site_url = is_array($uri) ? site_url($uri, null, $config) : (preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config)); + $siteUrl = is_array($uri) ? site_url($uri, null, $config) : (preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config)); // eliminate trailing slash - $site_url = rtrim($site_url, '/'); + $siteUrl = rtrim($siteUrl, '/'); if ($title === '') { - $title = $site_url; + $title = $siteUrl; } if ($attributes !== '') @@ -284,7 +284,7 @@ function anchor($uri = '', string $title = '', $attributes = '', \Config\App $al $attributes = stringify_attributes($attributes); } - return '' . $title . ''; + return '' . $title . ''; } } @@ -310,17 +310,17 @@ function anchor_popup($uri = '', string $title = '', $attributes = false, \Confi // use alternate config if provided, else default one $config = $altConfig ?? config(\Config\App::class); - $site_url = preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, '', $config); - $site_url = rtrim($site_url, '/'); + $siteUrl = preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, '', $config); + $siteUrl = rtrim($siteUrl, '/'); if ($title === '') { - $title = $site_url; + $title = $siteUrl; } if ($attributes === false) { - return '" . $title . ''; + return '" . $title . ''; } if (! is_array($attributes)) @@ -328,16 +328,16 @@ function anchor_popup($uri = '', string $title = '', $attributes = false, \Confi $attributes = [$attributes]; // Ref: http://www.w3schools.com/jsref/met_win_open.asp - $window_name = '_blank'; + $windowName = '_blank'; } elseif (! empty($attributes['window_name'])) { - $window_name = $attributes['window_name']; + $windowName = $attributes['window_name']; unset($attributes['window_name']); } else { - $window_name = '_blank'; + $windowName = '_blank'; } foreach (['width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'menubar' => 'no', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0'] as $key => $val) @@ -348,8 +348,8 @@ function anchor_popup($uri = '', string $title = '', $attributes = false, \Confi $attributes = stringify_attributes($attributes); - return '' . $title . ''; } } @@ -591,13 +591,13 @@ function prep_url(string $str = ''): string */ function url_title(string $str, string $separator = '-', bool $lowercase = false): string { - $q_separator = preg_quote($separator, '#'); + $qSeparator = preg_quote($separator, '#'); $trans = [ - '&.+?;' => '', - '[^\w\d\pL\pM _-]' => '', - '\s+' => $separator, - '(' . $q_separator . ')+' => $separator, + '&.+?;' => '', + '[^\w\d\pL\pM _-]' => '', + '\s+' => $separator, + '(' . $qSeparator . ')+' => $separator, ]; $str = strip_tags($str); diff --git a/system/Honeypot/Honeypot.php b/system/Honeypot/Honeypot.php index 9bdfff107793..2dffd6abad48 100644 --- a/system/Honeypot/Honeypot.php +++ b/system/Honeypot/Honeypot.php @@ -108,10 +108,10 @@ public function hasContent(RequestInterface $request) */ public function attachHoneypot(ResponseInterface $response) { - $prep_field = $this->prepareTemplate($this->config->template); + $prepField = $this->prepareTemplate($this->config->template); $body = $response->getBody(); - $body = str_ireplace('', $prep_field . '', $body); + $body = str_ireplace('', $prepField . '', $body); $response->setBody($body); } diff --git a/system/Images/Handlers/GDHandler.php b/system/Images/Handlers/GDHandler.php index de5278fbd6a6..69f315e6b805 100644 --- a/system/Images/Handlers/GDHandler.php +++ b/system/Images/Handlers/GDHandler.php @@ -171,9 +171,9 @@ public function getVersion() { if (function_exists('gd_info')) { - $gd_version = @gd_info(); + $gdVersion = @gd_info(); - return preg_replace('/\D/', '', $gd_version['GD Version']); + return preg_replace('/\D/', '', $gdVersion['GD Version']); } return false; diff --git a/system/Log/Handlers/FileHandler.php b/system/Log/Handlers/FileHandler.php index 85cb95768837..2a478840c576 100644 --- a/system/Log/Handlers/FileHandler.php +++ b/system/Log/Handlers/FileHandler.php @@ -124,10 +124,10 @@ public function handle($level, $message): bool // Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format if (strpos($this->dateFormat, 'u') !== false) { - $microtime_full = microtime(true); - $microtime_short = sprintf('%06d', ($microtime_full - floor($microtime_full)) * 1000000); - $date = new \DateTime(date('Y-m-d H:i:s.' . $microtime_short, (int) $microtime_full)); - $date = $date->format($this->dateFormat); + $microtimeFull = microtime(true); + $microtimeShort = sprintf('%06d', ($microtimeFull - floor($microtimeFull)) * 1000000); + $date = new \DateTime(date('Y-m-d H:i:s.' . $microtimeShort, (int) $microtimeFull)); + $date = $date->format($this->dateFormat); } else { diff --git a/system/Router/RouteCollection.php b/system/Router/RouteCollection.php index 77491b1fe580..a06c56a4f5a4 100644 --- a/system/Router/RouteCollection.php +++ b/system/Router/RouteCollection.php @@ -808,12 +808,12 @@ public function resource(string $name, array $options = null): RouteCollectionIn // In order to allow customization of the route the // resources are sent to, we need to have a new name // to store the values in. - $new_name = implode('\\', array_map('ucfirst', explode('/', $name))); + $newName = implode('\\', array_map('ucfirst', explode('/', $name))); // If a new controller is specified, then we replace the // $name value with the name of the new controller. if (isset($options['controller'])) { - $new_name = ucfirst(filter_var($options['controller'], FILTER_SANITIZE_STRING)); + $newName = ucfirst(filter_var($options['controller'], FILTER_SANITIZE_STRING)); } // In order to allow customization of allowed id values @@ -844,32 +844,32 @@ public function resource(string $name, array $options = null): RouteCollectionIn if (in_array('index', $methods, true)) { - $this->get($name, $new_name . '::index', $options); + $this->get($name, $newName . '::index', $options); } if (in_array('new', $methods, true)) { - $this->get($name . '/new', $new_name . '::new', $options); + $this->get($name . '/new', $newName . '::new', $options); } if (in_array('edit', $methods, true)) { - $this->get($name . '/' . $id . '/edit', $new_name . '::edit/$1', $options); + $this->get($name . '/' . $id . '/edit', $newName . '::edit/$1', $options); } if (in_array('show', $methods, true)) { - $this->get($name . '/' . $id, $new_name . '::show/$1', $options); + $this->get($name . '/' . $id, $newName . '::show/$1', $options); } if (in_array('create', $methods, true)) { - $this->post($name, $new_name . '::create', $options); + $this->post($name, $newName . '::create', $options); } if (in_array('update', $methods, true)) { - $this->put($name . '/' . $id, $new_name . '::update/$1', $options); - $this->patch($name . '/' . $id, $new_name . '::update/$1', $options); + $this->put($name . '/' . $id, $newName . '::update/$1', $options); + $this->patch($name . '/' . $id, $newName . '::update/$1', $options); } if (in_array('delete', $methods, true)) { - $this->delete($name . '/' . $id, $new_name . '::delete/$1', $options); + $this->delete($name . '/' . $id, $newName . '::delete/$1', $options); } // Web Safe? delete needs checking before update because of method name @@ -877,11 +877,11 @@ public function resource(string $name, array $options = null): RouteCollectionIn { if (in_array('delete', $methods, true)) { - $this->post($name . '/' . $id . '/delete', $new_name . '::delete/$1', $options); + $this->post($name . '/' . $id . '/delete', $newName . '::delete/$1', $options); } if (in_array('update', $methods, true)) { - $this->post($name . '/' . $id, $new_name . '::update/$1', $options); + $this->post($name . '/' . $id, $newName . '::update/$1', $options); } } diff --git a/system/Router/Router.php b/system/Router/Router.php index abf91e26379f..aa44a77e77f1 100644 --- a/system/Router/Router.php +++ b/system/Router/Router.php @@ -614,8 +614,8 @@ protected function validateRequest(array $segments): array }); $segments = array_values($segments); - $c = count($segments); - $directory_override = isset($this->directory); + $c = count($segments); + $directoryOverride = isset($this->directory); // Loop through our segments and return as soon as a controller // is found or when such a directory doesn't exist @@ -623,7 +623,7 @@ protected function validateRequest(array $segments): array { $test = $this->directory . ucfirst($this->translateURIDashes === true ? str_replace('-', '_', $segments[0]) : $segments[0]); - if (! is_file(APPPATH . 'Controllers/' . $test . '.php') && $directory_override === false && is_dir(APPPATH . 'Controllers/' . $this->directory . ucfirst($segments[0]))) + if (! is_file(APPPATH . 'Controllers/' . $test . '.php') && $directoryOverride === false && is_dir(APPPATH . 'Controllers/' . $this->directory . ucfirst($segments[0]))) { $this->setDirectory(array_shift($segments), true); continue; diff --git a/system/Security/Security.php b/system/Security/Security.php index 3bc3a261e3d1..906e81da9a1f 100644 --- a/system/Security/Security.php +++ b/system/Security/Security.php @@ -288,10 +288,10 @@ public function CSRFVerify(RequestInterface $request) */ public function CSRFSetCookie(RequestInterface $request) { - $expire = $this->CSRFExpire === 0 ? $this->CSRFExpire : time() + $this->CSRFExpire; - $secure_cookie = (bool) $this->cookieSecure; + $expire = $this->CSRFExpire === 0 ? $this->CSRFExpire : time() + $this->CSRFExpire; + $secureCookie = (bool) $this->cookieSecure; - if ($secure_cookie && ! $request->isSecure()) + if ($secureCookie && ! $request->isSecure()) { return false; } @@ -311,7 +311,7 @@ public function CSRFSetCookie(RequestInterface $request) $expire, $this->cookiePath . $samesite, $this->cookieDomain, - $secure_cookie, + $secureCookie, true // Enforce HTTP only cookie for security ); } @@ -322,7 +322,7 @@ public function CSRFSetCookie(RequestInterface $request) 'expires' => $expire, 'path' => $this->cookiePath, 'domain' => $this->cookieDomain, - 'secure' => $secure_cookie, + 'secure' => $secureCookie, 'httponly' => true,// Enforce HTTP only cookie for security ]; diff --git a/system/Session/Handlers/FileHandler.php b/system/Session/Handlers/FileHandler.php index a63c39cff514..ec38183896fd 100644 --- a/system/Session/Handlers/FileHandler.php +++ b/system/Session/Handlers/FileHandler.php @@ -213,7 +213,7 @@ public function read($sessionID) rewind($this->fileHandle); } - $session_data = ''; + $sessionData = ''; clearstatcache(); // Address https://github.com/codeigniter4/CodeIgniter4/issues/2056 for ($read = 0, $length = filesize($this->filePath . $sessionID); $read < $length; $read += strlen($buffer)) { @@ -222,12 +222,12 @@ public function read($sessionID) break; } - $session_data .= $buffer; + $sessionData .= $buffer; } - $this->fingerprint = md5($session_data); + $this->fingerprint = md5($sessionData); - return $session_data; + return $sessionData; } //-------------------------------------------------------------------- diff --git a/system/Session/Handlers/MemcachedHandler.php b/system/Session/Handlers/MemcachedHandler.php index 51537982274f..95a786901bb2 100644 --- a/system/Session/Handlers/MemcachedHandler.php +++ b/system/Session/Handlers/MemcachedHandler.php @@ -123,11 +123,11 @@ public function open($save_path, $name): bool $this->memcached = new \Memcached(); $this->memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); // required for touch() usage - $server_list = []; + $serverList = []; foreach ($this->memcached->getServerList() as $server) { - $server_list[] = $server['host'] . ':' . $server['port']; + $serverList[] = $server['host'] . ':' . $server['port']; } if (! preg_match_all('#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->savePath, $matches, PREG_SET_ORDER) @@ -142,7 +142,7 @@ public function open($save_path, $name): bool foreach ($matches as $match) { // If Memcached already has this server (or if the port is invalid), skip it - if (in_array($match[1] . ':' . $match[2], $server_list, true)) + if (in_array($match[1] . ':' . $match[2], $serverList, true)) { $this->logger->debug('Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]); continue; @@ -154,11 +154,11 @@ public function open($save_path, $name): bool } else { - $server_list[] = $match[1] . ':' . $match[2]; + $serverList[] = $match[1] . ':' . $match[2]; } } - if (empty($server_list)) + if (empty($serverList)) { $this->logger->error('Session: Memcached server pool is empty.'); @@ -189,10 +189,10 @@ public function read($sessionID): string $this->sessionID = $sessionID; } - $session_data = (string) $this->memcached->get($this->keyPrefix . $sessionID); - $this->fingerprint = md5($session_data); + $sessionData = (string) $this->memcached->get($this->keyPrefix . $sessionID); + $this->fingerprint = md5($sessionData); - return $session_data; + return $sessionData; } return ''; @@ -338,25 +338,25 @@ protected function lockSession(string $sessionID): bool } // 30 attempts to obtain a lock, in case another request already has it - $lock_key = $this->keyPrefix . $sessionID . ':lock'; - $attempt = 0; + $lockKey = $this->keyPrefix . $sessionID . ':lock'; + $attempt = 0; do { - if ($this->memcached->get($lock_key)) + if ($this->memcached->get($lockKey)) { sleep(1); continue; } - if (! $this->memcached->set($lock_key, time(), 300)) + if (! $this->memcached->set($lockKey, time(), 300)) { $this->logger->error('Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID); return false; } - $this->lockKey = $lock_key; + $this->lockKey = $lockKey; break; } while (++ $attempt < 30); diff --git a/system/Session/Handlers/RedisHandler.php b/system/Session/Handlers/RedisHandler.php index 1b4370f9350d..82224e49d8b7 100644 --- a/system/Session/Handlers/RedisHandler.php +++ b/system/Session/Handlers/RedisHandler.php @@ -194,12 +194,12 @@ public function read($sessionID): string $this->sessionID = $sessionID; } - $session_data = $this->redis->get($this->keyPrefix . $sessionID); - is_string($session_data) ? $this->keyExists = true : $session_data = ''; + $sessionData = $this->redis->get($this->keyPrefix . $sessionID); + is_string($sessionData) ? $this->keyExists = true : $sessionData = ''; - $this->fingerprint = md5($session_data); + $this->fingerprint = md5($sessionData); - return $session_data; + return $sessionData; } return ''; @@ -273,9 +273,9 @@ public function close(): bool { try { - $ping_reply = $this->redis->ping(); + $pingReply = $this->redis->ping(); // @phpstan-ignore-next-line - if (($ping_reply === true) || ($ping_reply === '+PONG')) + if (($pingReply === true) || ($pingReply === '+PONG')) { isset($this->lockKey) && $this->redis->del($this->lockKey); @@ -362,24 +362,24 @@ protected function lockSession(string $sessionID): bool } // 30 attempts to obtain a lock, in case another request already has it - $lock_key = $this->keyPrefix . $sessionID . ':lock'; - $attempt = 0; + $lockKey = $this->keyPrefix . $sessionID . ':lock'; + $attempt = 0; do { - if (($ttl = $this->redis->ttl($lock_key)) > 0) + if (($ttl = $this->redis->ttl($lockKey)) > 0) { sleep(1); continue; } - if (! $this->redis->setex($lock_key, 300, (string) time())) + if (! $this->redis->setex($lockKey, 300, (string) time())) { $this->logger->error('Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID); return false; } - $this->lockKey = $lock_key; + $this->lockKey = $lockKey; break; } while (++ $attempt < 30); diff --git a/system/Session/Session.php b/system/Session/Session.php index f5ce19b75b64..d9d57dc14510 100644 --- a/system/Session/Session.php +++ b/system/Session/Session.php @@ -252,14 +252,14 @@ public function start() // Is session ID auto-regeneration configured? (ignoring ajax requests) if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) || - strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') && ($regenerate_time = $this->sessionTimeToUpdate) > 0 + strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') && ($regenerateTime = $this->sessionTimeToUpdate) > 0 ) { if (! isset($_SESSION['__ci_last_regenerate'])) { $_SESSION['__ci_last_regenerate'] = time(); } - elseif ($_SESSION['__ci_last_regenerate'] < (time() - $regenerate_time)) + elseif ($_SESSION['__ci_last_regenerate'] < (time() - $regenerateTime)) { $this->regenerate((bool) $this->sessionRegenerateDestroy); } @@ -393,22 +393,22 @@ protected function configure() */ protected function configureSidLength() { - $bits_per_character = (int) (ini_get('session.sid_bits_per_character') !== false + $bitsPerCharacter = (int) (ini_get('session.sid_bits_per_character') !== false ? ini_get('session.sid_bits_per_character') : 4); - $sid_length = (int) (ini_get('session.sid_length') !== false + $sidLength = (int) (ini_get('session.sid_length') !== false ? ini_get('session.sid_length') : 40); - if (($sid_length * $bits_per_character) < 160) + if (($sidLength * $bitsPerCharacter) < 160) { - $bits = ($sid_length * $bits_per_character); + $bits = ($sidLength * $bitsPerCharacter); // Add as many more characters as necessary to reach at least 160 bits - $sid_length += (int) ceil((160 % $bits) / $bits_per_character); - ini_set('session.sid_length', (string) $sid_length); + $sidLength += (int) ceil((160 % $bits) / $bitsPerCharacter); + ini_set('session.sid_length', (string) $sidLength); } // Yes, 4,5,6 are the only known possible values as of 2016-10-27 - switch ($bits_per_character) + switch ($bitsPerCharacter) { case 4: $this->sidRegexp = '[0-9a-f]'; @@ -421,7 +421,7 @@ protected function configureSidLength() break; } - $this->sidRegexp .= '{' . $sid_length . '}'; + $this->sidRegexp .= '{' . $sidLength . '}'; } //-------------------------------------------------------------------- @@ -439,7 +439,7 @@ protected function initVars() return; } - $current_time = time(); + $currentTime = time(); foreach ($_SESSION['__ci_vars'] as $key => &$value) { @@ -449,7 +449,7 @@ protected function initVars() } // Hacky, but 'old' will (implicitly) always be less than time() ;) // DO NOT move this above the 'new' check! - elseif ($value < $current_time) + elseif ($value < $currentTime) { unset($_SESSION[$key], $_SESSION['__ci_vars'][$key]); } @@ -558,14 +558,14 @@ public function get(string $key = null) } $userdata = []; - $_exclude = array_merge( + $exclude = array_merge( ['__ci_vars'], $this->getFlashKeys(), $this->getTempKeys() ); $keys = array_keys($_SESSION); foreach ($keys as $key) { - if (! in_array($key, $_exclude, true)) + if (! in_array($key, $exclude, true)) { $userdata[$key] = $_SESSION[$key]; } diff --git a/system/Test/Mock/MockCommon.php b/system/Test/Mock/MockCommon.php index 21fd54261401..3778ad1bf9ae 100644 --- a/system/Test/Mock/MockCommon.php +++ b/system/Test/Mock/MockCommon.php @@ -23,14 +23,14 @@ function is_cli(bool $new_return = null): bool { // PHPUnit always runs via CLI. - static $return_value = true; + static $returnValue = true; if ($new_return !== null) { - $return_value = $new_return; + $returnValue = $new_return; } - return $return_value; + return $returnValue; } } diff --git a/system/Test/ReflectionHelper.php b/system/Test/ReflectionHelper.php index bb52908603b1..a780e0ae5e8b 100644 --- a/system/Test/ReflectionHelper.php +++ b/system/Test/ReflectionHelper.php @@ -59,13 +59,13 @@ trait ReflectionHelper */ public static function getPrivateMethodInvoker($obj, $method) { - $ref_method = new ReflectionMethod($obj, $method); - $ref_method->setAccessible(true); + $refMethod = new ReflectionMethod($obj, $method); + $refMethod->setAccessible(true); $obj = (gettype($obj) === 'object') ? $obj : null; - return function () use ($obj, $ref_method) { + return function () use ($obj, $refMethod) { $args = func_get_args(); - return $ref_method->invokeArgs($obj, $args); + return $refMethod->invokeArgs($obj, $args); }; } @@ -82,17 +82,17 @@ private static function getAccessibleRefProperty($obj, $property) { if (is_object($obj)) { - $ref_class = new ReflectionObject($obj); + $refClass = new ReflectionObject($obj); } else { - $ref_class = new ReflectionClass($obj); + $refClass = new ReflectionClass($obj); } - $ref_property = $ref_class->getProperty($property); - $ref_property->setAccessible(true); + $refProperty = $refClass->getProperty($property); + $refProperty->setAccessible(true); - return $ref_property; + return $refProperty; } /** @@ -106,8 +106,8 @@ private static function getAccessibleRefProperty($obj, $property) */ public static function setPrivateProperty($obj, $property, $value) { - $ref_property = self::getAccessibleRefProperty($obj, $property); - $ref_property->setValue($obj, $value); + $refProperty = self::getAccessibleRefProperty($obj, $property); + $refProperty->setValue($obj, $value); } /** @@ -121,8 +121,8 @@ public static function setPrivateProperty($obj, $property, $value) */ public static function getPrivateProperty($obj, $property) { - $ref_property = self::getAccessibleRefProperty($obj, $property); - return $ref_property->getValue($obj); + $refProperty = self::getAccessibleRefProperty($obj, $property); + return $refProperty->getValue($obj); } } diff --git a/system/Test/TestLogger.php b/system/Test/TestLogger.php index 450d15b8f021..8fb6bf1cf03f 100644 --- a/system/Test/TestLogger.php +++ b/system/Test/TestLogger.php @@ -23,7 +23,7 @@ public function log($level, $message, array $context = []): bool { // While this requires duplicate work, we want to ensure // we have the final message to test against. - $log_message = $this->interpolate($message, $context); + $logMessage = $this->interpolate($message, $context); // Determine the file and line by finding the first // backtrace that is not part of our logging system. @@ -41,7 +41,7 @@ public function log($level, $message, array $context = []): bool self::$op_logs[] = [ 'level' => $level, - 'message' => $log_message, + 'message' => $logMessage, 'file' => $file, ]; diff --git a/system/Typography/Typography.php b/system/Typography/Typography.php index 8b60a57793cb..5643d7cf4b06 100644 --- a/system/Typography/Typography.php +++ b/system/Typography/Typography.php @@ -124,13 +124,13 @@ public function autoTypography(string $str, bool $reduce_linebreaks = false): st } // HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed - $html_comments = []; + $htmlComments = []; if (strpos($str, '