diff --git a/.github/workflows/test-rector.yml b/.github/workflows/test-rector.yml new file mode 100644 index 000000000000..5a261b19ddb5 --- /dev/null +++ b/.github/workflows/test-rector.yml @@ -0,0 +1,59 @@ +# 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: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Create composer cache directory + run: mkdir -p ${{ steps.composer-cache.outputs.dir }} + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + restore-keys: ${{ runner.os }}-composer- + + - 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/app/Config/Mimes.php b/app/Config/Mimes.php index cfeea777c7f2..ce014db338ac 100644 --- a/app/Config/Mimes.php +++ b/app/Config/Mimes.php @@ -497,19 +497,19 @@ public static function guessTypeFromExtension(string $extension) * Attempts to determine the best file extension for a given mime type. * * @param string $type - * @param string|null $proposed_extension - default extension (in case there is more than one with the same mime type) + * @param string|null $proposedExtension - default extension (in case there is more than one with the same mime type) * * @return string|null The extension determined, or null if unable to match. */ - public static function guessExtensionFromType(string $type, string $proposed_extension = null) + public static function guessExtensionFromType(string $type, string $proposedExtension = null) { $type = trim(strtolower($type), '. '); - $proposed_extension = trim(strtolower($proposed_extension)); + $proposedExtension = trim(strtolower($proposedExtension)); - if ($proposed_extension !== '' && array_key_exists($proposed_extension, static::$mimes) && in_array($type, is_string(static::$mimes[$proposed_extension]) ? [static::$mimes[$proposed_extension]] : static::$mimes[$proposed_extension])) + if ($proposedExtension !== '' && array_key_exists($proposedExtension, static::$mimes) && in_array($type, is_string(static::$mimes[$proposedExtension]) ? [static::$mimes[$proposedExtension]] : static::$mimes[$proposedExtension])) { - return $proposed_extension; + return $proposedExtension; } foreach (static::$mimes as $ext => $types) diff --git a/composer.json b/composer.json index dbbd2661fa90..3bdf2b8d935b 100644 --- a/composer.json +++ b/composer.json @@ -18,9 +18,11 @@ "codeigniter4/codeigniter4-standard": "^1.0", "fzaninotto/faker": "^1.9@dev", "mikey179/vfsstream": "1.6.*", + "nette/utils": "^3.1", "phpstan/phpstan": "^0.12", "phpunit/phpunit": "^8.5", "predis/predis": "^1.1", + "rector/rector-prefixed": "0.8.11", "squizlabs/php_codesniffer": "^3.3" }, "autoload": { @@ -28,6 +30,11 @@ "CodeIgniter\\": "system/" } }, + "autoload-dev": { + "psr-4": { + "Utils\\": "utils" + } + }, "scripts": { "post-update-cmd": [ "@composer dump-autoload", diff --git a/rector.php b/rector.php new file mode 100644 index 000000000000..3ddb5c5c473f --- /dev/null +++ b/rector.php @@ -0,0 +1,29 @@ +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/Autoloader/Autoloader.php', + __DIR__ . '/system/Debug/Toolbar/Views/toolbar.tpl.php', + __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(UnderscoreToCamelCaseVariableNameRector::class); +}; 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..84bde5ac0016 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; @@ -813,7 +813,6 @@ public static function showProgress($thisStep = 1, int $totalSteps = 10) } //-------------------------------------------------------------------- - /** * Takes a string and writes it to the command line, wrapping to a maximum * width. If no maximum width is specified, will wrap to the window's max @@ -825,11 +824,11 @@ public static function showProgress($thisStep = 1, int $totalSteps = 10) * * @param string $string * @param integer $max - * @param integer $pad_left + * @param integer $padLeft * * @return string */ - public static function wrap(string $string = null, int $max = 0, int $pad_left = 0): string + public static function wrap(string $string = null, int $max = 0, int $padLeft = 0): string { if (empty($string)) { @@ -846,20 +845,20 @@ public static function wrap(string $string = null, int $max = 0, int $pad_left = $max = CLI::getWidth(); } - $max = $max - $pad_left; + $max = $max - $padLeft; $lines = wordwrap($string, $max, PHP_EOL); - if ($pad_left > 0) + if ($padLeft > 0) { $lines = explode(PHP_EOL, $lines); $first = true; - array_walk($lines, function (&$line, $index) use ($pad_left, &$first) { + array_walk($lines, function (&$line, $index) use ($padLeft, &$first) { if (! $first) { - $line = str_repeat(' ', $pad_left) . $line; + $line = str_repeat(' ', $padLeft) . $line; } else { @@ -1070,45 +1069,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 +1117,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 +1134,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 +1148,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..651f3c3968ea 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; } //-------------------------------------------------------------------- @@ -373,7 +373,6 @@ protected function writeFile($path, $data, $mode = 'wb') } //-------------------------------------------------------------------- - /** * Delete Files * @@ -382,30 +381,30 @@ protected function writeFile($path, $data, $mode = 'wb') * If the second parameter is set to TRUE, any directories contained * within the supplied base directory will be nuked as well. * - * @param string $path File path - * @param boolean $del_dir Whether to delete any directories found in the path - * @param boolean $htdocs Whether to skip deleting .htaccess and index page files - * @param integer $_level Current directory depth level (default: 0; internal use only) + * @param string $path File path + * @param boolean $delDir Whether to delete any directories found in the path + * @param boolean $htdocs Whether to skip deleting .htaccess and index page files + * @param integer $_level Current directory depth level (default: 0; internal use only) * * @return boolean */ - protected function deleteFiles(string $path, bool $del_dir = false, bool $htdocs = false, int $_level = 0): bool + protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs = false, int $_level = 0): bool { // 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 !== '..') { if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.') { - $this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $del_dir, $htdocs, $_level + 1); + $this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $delDir, $htdocs, $_level + 1); } elseif ($htdocs !== true || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) { @@ -414,13 +413,12 @@ 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; + return ($delDir === true && $_level > 0) ? @rmdir($path) : true; } //-------------------------------------------------------------------- - /** * Get Directory File Information * @@ -429,37 +427,37 @@ protected function deleteFiles(string $path, bool $del_dir = false, bool $htdocs * * Any sub-folders contained within the specified path are read as well. * - * @param string $source_dir Path to source - * @param boolean $top_level_only Look only at the top level directory specified? - * @param boolean $_recursion Internal variable to determine recursion status - do not use in calls + * @param string $sourceDir Path to source + * @param boolean $topLevelOnly Look only at the top level directory specified? + * @param boolean $_recursion Internal variable to determine recursion status - do not use in calls * * @return array|false */ - protected function getDirFileInfo(string $source_dir, bool $top_level_only = true, bool $_recursion = false) + protected function getDirFileInfo(string $sourceDir, bool $topLevelOnly = true, bool $_recursion = false) { static $_filedata = []; - $relative_path = $source_dir; + $relativePath = $sourceDir; - if ($fp = @opendir($source_dir)) + if ($fp = @opendir($sourceDir)) { // reset the array and make sure $source_dir has a trailing slash on the initial call if ($_recursion === false) { - $_filedata = []; - $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $_filedata = []; + $sourceDir = rtrim(realpath($sourceDir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } // Used to be foreach (scandir($source_dir, 1) as $file), but scandir() is simply not as fast while (false !== ($file = readdir($fp))) { - if (is_dir($source_dir . $file) && $file[0] !== '.' && $top_level_only === false) + if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) { - $this->getDirFileInfo($source_dir . $file . DIRECTORY_SEPARATOR, $top_level_only, true); + $this->getDirFileInfo($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true); } elseif ($file[0] !== '.') { - $_filedata[$file] = $this->getFileInfo($source_dir . $file); - $_filedata[$file]['relative_path'] = $relative_path; + $_filedata[$file] = $this->getFileInfo($sourceDir . $file); + $_filedata[$file]['relative_path'] = $relativePath; } } @@ -472,7 +470,6 @@ protected function getDirFileInfo(string $source_dir, bool $top_level_only = tru } //-------------------------------------------------------------------- - /** * Get File Info * @@ -481,24 +478,24 @@ protected function getDirFileInfo(string $source_dir, bool $top_level_only = tru * Options are: name, server_path, size, date, readable, writable, executable, fileperms * Returns FALSE if the file cannot be found. * - * @param string $file Path to file - * @param mixed $returned_values Array or comma separated string of information returned + * @param string $file Path to file + * @param mixed $returnedValues Array or comma separated string of information returned * * @return array|false */ - protected function getFileInfo(string $file, $returned_values = ['name', 'server_path', 'size', 'date']) + protected function getFileInfo(string $file, $returnedValues = ['name', 'server_path', 'size', 'date']) { if (! is_file($file)) { return false; } - if (is_string($returned_values)) + if (is_string($returnedValues)) { - $returned_values = explode(',', $returned_values); + $returnedValues = explode(',', $returnedValues); } - foreach ($returned_values as $key) + foreach ($returnedValues as $key) { switch ($key) { 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..206ea2bc95a7 100644 --- a/system/Common.php +++ b/system/Common.php @@ -594,24 +594,24 @@ function force_https(int $duration = 31536000, RequestInterface $request = null, * be just temporary, but would probably be kept for a few years. * * @link http://www.hardened-php.net/suhosin/ - * @param string $function_name Function to check for + * @param string $functionName Function to check for * @return boolean TRUE if the function exists and is safe to call, * FALSE otherwise. * * @codeCoverageIgnore This is too exotic */ - function function_usable(string $function_name): bool + function function_usable(string $functionName): bool { static $_suhosin_func_blacklist; - if (function_exists($function_name)) + if (function_exists($functionName)) { if (! isset($_suhosin_func_blacklist)) { $_suhosin_func_blacklist = extension_loaded('suhosin') ? explode(',', trim(ini_get('suhosin.executor.func.blacklist'))) : []; } - return ! in_array($function_name, $_suhosin_func_blacklist, true); + return ! in_array($functionName, $_suhosin_func_blacklist, true); } return false; diff --git a/system/Config/BaseService.php b/system/Config/BaseService.php index 34c9a3bb35d0..c7ce12e997c9 100644 --- a/system/Config/BaseService.php +++ b/system/Config/BaseService.php @@ -201,19 +201,18 @@ public static function __callStatic(string $name, array $arguments) } //-------------------------------------------------------------------- - /** * Reset shared instances and mocks for testing. * - * @param boolean $init_autoloader Initializes autoloader instance + * @param boolean $initAutoloader Initializes autoloader instance */ - public static function reset(bool $init_autoloader = false) + public static function reset(bool $initAutoloader = false) { static::$mocks = []; static::$instances = []; - if ($init_autoloader) + if ($initAutoloader) { static::autoloader()->initialize(new Autoload(), new Modules()); } diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index ab3c8205ef1f..43b40461e020 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -745,7 +745,6 @@ public function orWhere($key, $value = null, bool $escape = null) } //-------------------------------------------------------------------- - /** * WHERE, HAVING * @@ -754,7 +753,7 @@ public function orWhere($key, $value = null, bool $escape = null) * @used-by having() * @used-by orHaving() * - * @param string $qb_key 'QBWhere' or 'QBHaving' + * @param string $qbKey 'QBWhere' or 'QBHaving' * @param mixed $key * @param mixed $value * @param string $type @@ -762,7 +761,7 @@ public function orWhere($key, $value = null, bool $escape = null) * * @return BaseBuilder */ - protected function whereHaving(string $qb_key, $key, $value = null, string $type = 'AND ', bool $escape = null) + protected function whereHaving(string $qbKey, $key, $value = null, string $type = 'AND ', bool $escape = null) { if (! is_array($key)) { @@ -774,7 +773,7 @@ protected function whereHaving(string $qb_key, $key, $value = null, string $type foreach ($key as $k => $v) { - $prefix = empty($this->$qb_key) ? $this->groupGetType('') : $this->groupGetType($type); + $prefix = empty($this->$qbKey) ? $this->groupGetType('') : $this->groupGetType($type); if ($v !== null) { @@ -815,7 +814,7 @@ protected function whereHaving(string $qb_key, $key, $value = null, string $type $v = " :$bind:"; } } - elseif (! $this->hasOperator($k) && $qb_key !== 'QBHaving') + elseif (! $this->hasOperator($k) && $qbKey !== 'QBHaving') { // value appears not to have been set, assign the test to IS NULL $k .= ' IS NULL'; @@ -825,7 +824,7 @@ protected function whereHaving(string $qb_key, $key, $value = null, string $type $k = substr($k, 0, $match[0][1]) . ($match[1][0] === '=' ? ' IS NULL' : ' IS NOT NULL'); } - $this->{$qb_key}[] = [ + $this->{$qbKey}[] = [ 'condition' => $prefix . $k . $v, 'escape' => $escape, ]; @@ -1291,16 +1290,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 +1322,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 +1635,7 @@ public function orderBy(string $orderBy, string $direction = '', bool $escape = if ($escape === false) { - $qb_orderBy[] = [ + $qbOrderBy[] = [ 'field' => $orderBy, 'direction' => $direction, 'escape' => false, @@ -1644,10 +1643,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 +1662,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 +2084,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 +2105,7 @@ public function insertBatch(array $set = null, bool $escape = null, int $batchSi $this->resetWrite(); } - return $affected_rows; + return $affectedRows; } //-------------------------------------------------------------------- @@ -2591,9 +2590,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 +2605,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 +2613,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 +2685,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 +2699,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.'); } @@ -2803,20 +2802,19 @@ public function getCompiledDelete(bool $reset = true): string } //-------------------------------------------------------------------- - /** * Delete * * Compiles a delete string and runs the query * - * @param mixed $where The where clause - * @param integer $limit The limit clause - * @param boolean $reset_data + * @param mixed $where The where clause + * @param integer $limit The limit clause + * @param boolean $resetData * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ - public function delete($where = '', int $limit = null, bool $reset_data = true) + public function delete($where = '', int $limit = null, bool $resetData = true) { $table = $this->db->protectIdentifiers($this->QBFrom[0], true, null, false); @@ -2853,7 +2851,7 @@ public function delete($where = '', int $limit = null, bool $reset_data = true) $sql = $this->_limit($sql, true); } - if ($reset_data) + if ($resetData) { $this->resetWrite(); } @@ -2959,23 +2957,22 @@ protected function trackAliases($table) } //-------------------------------------------------------------------- - /** * Compile the SELECT statement * * Generates a query string based on which functions were used. * Should not be called directly. * - * @param mixed $select_override + * @param mixed $selectOverride * * @return string */ - protected function compileSelect($select_override = false): string + protected function compileSelect($selectOverride = false): string { // Write the "select" portion of the query - if ($select_override !== false) + if ($selectOverride !== false) { - $sql = $select_override; + $sql = $selectOverride; } else { @@ -2992,8 +2989,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); @@ -3052,7 +3049,6 @@ protected function compileIgnore(string $statement) } //-------------------------------------------------------------------- - /** * Compile WHERE, HAVING statements * @@ -3062,15 +3058,15 @@ protected function compileIgnore(string $statement) * where(), orWhere(), having(), orHaving are called prior to from(), * join() and prefixTable is added only if needed. * - * @param string $qb_key 'QBWhere' or 'QBHaving' + * @param string $qbKey 'QBWhere' or 'QBHaving' * * @return string SQL statement */ - protected function compileWhereHaving(string $qb_key): string + protected function compileWhereHaving(string $qbKey): string { - if (! empty($this->$qb_key)) + if (! empty($this->$qbKey)) { - foreach ($this->$qb_key as &$qbkey) + foreach ($this->$qbKey as &$qbkey) { // Is this condition already compiled? if (is_string($qbkey)) @@ -3129,8 +3125,8 @@ protected function compileWhereHaving(string $qb_key): string $qbkey = implode('', $conditions); } - return ($qb_key === 'QBHaving' ? "\nHAVING " : "\nWHERE ") - . implode("\n", $this->$qb_key); + return ($qbKey === 'QBHaving' ? "\nHAVING " : "\nWHERE ") + . implode("\n", $this->$qbKey); } return ''; @@ -3328,19 +3324,18 @@ public function resetQuery() } //-------------------------------------------------------------------- - /** * Resets the query builder values. Called by the get() function * - * @param array $qb_reset_items An array of fields to reset + * @param array $qbResetItems An array of fields to reset * * @return void */ - protected function resetRun(array $qb_reset_items) + protected function resetRun(array $qbResetItems) { - foreach ($qb_reset_items as $item => $default_value) + foreach ($qbResetItems as $item => $defaultValue) { - $this->$item = $default_value; + $this->$item = $defaultValue; } } diff --git a/system/Database/BaseConnection.php b/system/Database/BaseConnection.php index c7a3bb202cb6..b8e2e5ee3615 100644 --- a/system/Database/BaseConnection.php +++ b/system/Database/BaseConnection.php @@ -762,21 +762,20 @@ public function transStrict(bool $mode = true) } //-------------------------------------------------------------------- - /** * Start Transaction * - * @param boolean $test_mode = FALSE + * @param boolean $testMode = FALSE * @return boolean */ - public function transStart(bool $test_mode = false): bool + public function transStart(bool $testMode = false): bool { if (! $this->transEnabled) { return false; } - return $this->transBegin($test_mode); + return $this->transBegin($testMode); } //-------------------------------------------------------------------- @@ -826,14 +825,13 @@ public function transStatus(): bool } //-------------------------------------------------------------------- - /** * Begin Transaction * - * @param boolean $test_mode + * @param boolean $testMode * @return boolean */ - public function transBegin(bool $test_mode = false): bool + public function transBegin(bool $testMode = false): bool { if (! $this->transEnabled) { @@ -855,7 +853,7 @@ public function transBegin(bool $test_mode = false): bool // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. - $this->transFailure = ($test_mode === true); + $this->transFailure = ($testMode === true); if ($this->_transBegin()) { @@ -1106,13 +1104,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 +1294,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 +1309,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 +1318,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/BaseUtils.php b/system/Database/BaseUtils.php index 1c5fff1dcc19..ed5778f4cfd1 100644 --- a/system/Database/BaseUtils.php +++ b/system/Database/BaseUtils.php @@ -131,28 +131,26 @@ public function listDatabases() } //-------------------------------------------------------------------- - /** * Determine if a particular database exists * - * @param string $database_name + * @param string $databaseName * @return boolean */ - public function databaseExists(string $database_name): bool + public function databaseExists(string $databaseName): bool { - return in_array($database_name, $this->listDatabases(), true); + return in_array($databaseName, $this->listDatabases(), true); } //-------------------------------------------------------------------- - /** * Optimize Table * - * @param string $table_name + * @param string $tableName * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ - public function optimizeTable(string $table_name) + public function optimizeTable(string $tableName) { if ($this->optimizeTable === false) { @@ -163,7 +161,7 @@ public function optimizeTable(string $table_name) return false; } - $query = $this->db->query(sprintf($this->optimizeTable, $this->db->escapeIdentifiers($table_name))); + $query = $this->db->query(sprintf($this->optimizeTable, $this->db->escapeIdentifiers($tableName))); if ($query !== false) { $query = $query->getResultArray(); @@ -193,9 +191,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 +206,7 @@ public function optimizeDatabase() // Postgre & SQLite3 returns empty array if (empty($res)) { - $key = $table_name; + $key = $tableName; } else { @@ -225,15 +223,14 @@ public function optimizeDatabase() } //-------------------------------------------------------------------- - /** * Repair Table * - * @param string $table_name + * @param string $tableName * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ - public function repairTable(string $table_name) + public function repairTable(string $tableName) { if ($this->repairTable === false) { @@ -244,7 +241,7 @@ public function repairTable(string $table_name) return false; } - $query = $this->db->query(sprintf($this->repairTable, $this->db->escapeIdentifiers($table_name))); + $query = $this->db->query(sprintf($this->repairTable, $this->db->escapeIdentifiers($tableName))); if (is_bool($query)) { return $query; diff --git a/system/Database/Forge.php b/system/Database/Forge.php index ac0235e81bcc..05be7e7ee3df 100644 --- a/system/Database/Forge.php +++ b/system/Database/Forge.php @@ -492,18 +492,17 @@ public function dropForeignKey(string $table, string $foreignName) } //-------------------------------------------------------------------- - /** * Create Table * - * @param string $table Table name - * @param boolean $if_not_exists Whether to add IF NOT EXISTS condition - * @param array $attributes Associative array of table attributes + * @param string $table Table name + * @param boolean $ifNotExists Whether to add IF NOT EXISTS condition + * @param array $attributes Associative array of table attributes * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ - public function createTable(string $table, bool $if_not_exists = false, array $attributes = []) + public function createTable(string $table, bool $ifNotExists = false, array $attributes = []) { if ($table === '') { @@ -517,7 +516,7 @@ public function createTable(string $table, bool $if_not_exists = false, array $a throw new \RuntimeException('Field information is required.'); } - $sql = $this->_createTable($table, $if_not_exists, $attributes); + $sql = $this->_createTable($table, $ifNotExists, $attributes); if (is_bool($sql)) { @@ -556,30 +555,29 @@ public function createTable(string $table, bool $if_not_exists = false, array $a } //-------------------------------------------------------------------- - /** * Create Table * - * @param string $table Table name - * @param boolean $if_not_exists Whether to add 'IF NOT EXISTS' condition - * @param array $attributes Associative array of table attributes + * @param string $table Table name + * @param boolean $ifNotExists Whether to add 'IF NOT EXISTS' condition + * @param array $attributes Associative array of table attributes * * @return mixed */ - protected function _createTable(string $table, bool $if_not_exists, array $attributes) + protected function _createTable(string $table, bool $ifNotExists, array $attributes) { // For any platforms that don't support Create If Not Exists... - if ($if_not_exists === true && $this->createTableIfStr === false) + if ($ifNotExists === true && $this->createTableIfStr === false) { if ($this->db->tableExists($table)) { return true; } - $if_not_exists = false; + $ifNotExists = false; } - $sql = ($if_not_exists) ? sprintf($this->createTableIfStr, $this->db->escapeIdentifiers($table)) + $sql = ($ifNotExists) ? sprintf($this->createTableIfStr, $this->db->escapeIdentifiers($table)) : 'CREATE TABLE'; $columns = $this->_processFields(true); @@ -691,23 +689,22 @@ public function dropTable(string $tableName, bool $ifExists = false, bool $casca } //-------------------------------------------------------------------- - /** * Drop Table * * Generates a platform-specific DROP TABLE string * - * @param string $table Table name - * @param boolean $if_exists Whether to add an IF EXISTS condition - * @param boolean $cascade Whether to add an CASCADE condition + * @param string $table Table name + * @param boolean $ifExists Whether to add an IF EXISTS condition + * @param boolean $cascade Whether to add an CASCADE condition * * @return string|boolean */ - protected function _dropTable(string $table, bool $if_exists, bool $cascade) + protected function _dropTable(string $table, bool $ifExists, bool $cascade) { $sql = 'DROP TABLE'; - if ($if_exists) + if ($ifExists) { if ($this->dropTableIfStr === false) { @@ -726,19 +723,18 @@ protected function _dropTable(string $table, bool $if_exists, bool $cascade) } //-------------------------------------------------------------------- - /** * Rename Table * - * @param string $table_name Old table name - * @param string $new_table_name New table name + * @param string $tableName Old table name + * @param string $newTableName New table name * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ - public function renameTable(string $table_name, string $new_table_name) + public function renameTable(string $tableName, string $newTableName) { - if ($table_name === '' || $new_table_name === '') + if ($tableName === '' || $newTableName === '') { throw new \InvalidArgumentException('A table name is required for that operation.'); } @@ -754,17 +750,17 @@ public function renameTable(string $table_name, string $new_table_name) } $result = $this->db->query(sprintf($this->renameTableStr, - $this->db->escapeIdentifiers($this->db->DBPrefix . $table_name), - $this->db->escapeIdentifiers($this->db->DBPrefix . $new_table_name)) + $this->db->escapeIdentifiers($this->db->DBPrefix . $tableName), + $this->db->escapeIdentifiers($this->db->DBPrefix . $newTableName)) ); if ($result && ! empty($this->db->dataCache['table_names'])) { - $key = array_search(strtolower($this->db->DBPrefix . $table_name), + $key = array_search(strtolower($this->db->DBPrefix . $tableName), array_map('strtolower', $this->db->dataCache['table_names']), true); if ($key !== false) { - $this->db->dataCache['table_names'][$key] = $this->db->DBPrefix . $new_table_name; + $this->db->dataCache['table_names'][$key] = $this->db->DBPrefix . $newTableName; } } @@ -816,19 +812,18 @@ public function addColumn(string $table, $field): bool } //-------------------------------------------------------------------- - /** * Column Drop * - * @param string $table Table name - * @param string|array $column_name Column name Array or comma separated + * @param string $table Table name + * @param string|array $columnName Column name Array or comma separated * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ - public function dropColumn(string $table, $column_name) + public function dropColumn(string $table, $columnName) { - $sql = $this->_alterTable('DROP', $this->db->DBPrefix . $table, $column_name); + $sql = $this->_alterTable('DROP', $this->db->DBPrefix . $table, $columnName); if ($sql === false) { if ($this->db->DBDebug) @@ -895,22 +890,21 @@ public function modifyColumn(string $table, $field): bool } //-------------------------------------------------------------------- - /** * ALTER TABLE * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $fields Column definition + * @param string $alterType ALTER type + * @param string $table Table name + * @param mixed $fields Column definition * * @return string|string[]|false */ - protected function _alterTable(string $alter_type, string $table, $fields) + protected function _alterTable(string $alterType, string $table, $fields) { $sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table) . ' '; // DROP has everything it needs now. - if ($alter_type === 'DROP') + if ($alterType === 'DROP') { if (is_string($fields)) { @@ -924,7 +918,7 @@ protected function _alterTable(string $alter_type, string $table, $fields) return $sql . implode(', ', $fields); } - $sql .= ($alter_type === 'ADD') ? 'ADD ' : $alter_type . ' COLUMN '; + $sql .= ($alterType === 'ADD') ? 'ADD ' : $alterType . ' COLUMN '; $sqls = []; foreach ($fields as $data) @@ -937,15 +931,14 @@ protected function _alterTable(string $alter_type, string $table, $fields) } //-------------------------------------------------------------------- - /** * Process fields * - * @param boolean $create_table + * @param boolean $createTable * * @return array */ - protected function _processFields(bool $create_table = false): array + protected function _processFields(bool $createTable = false): array { $fields = []; @@ -959,7 +952,7 @@ protected function _processFields(bool $create_table = false): array $attributes = array_change_key_case($attributes, CASE_UPPER); - if ($create_table === true && empty($attributes['TYPE'])) + if ($createTable === true && empty($attributes['TYPE'])) { continue; } @@ -983,7 +976,7 @@ protected function _processFields(bool $create_table = false): array // @phpstan-ignore-next-line isset($attributes['TYPE']) && $this->_attributeUnsigned($attributes, $field); - if ($create_table === false) + if ($createTable === false) { if (isset($attributes['AFTER'])) { @@ -1008,7 +1001,7 @@ protected function _processFields(bool $create_table = false): array $field['null'] = ' NOT NULL'; } } - elseif ($create_table === true) + elseif ($createTable === true) { $field['null'] = ' NOT NULL'; } @@ -1300,9 +1293,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..9cbba78e51f5 100644 --- a/system/Database/MySQLi/Forge.php +++ b/system/Database/MySQLi/Forge.php @@ -161,20 +161,19 @@ protected function _createTableAttributes(array $attributes): string } //-------------------------------------------------------------------- - /** * ALTER TABLE * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $field Column definition + * @param string $alterType ALTER type + * @param string $table Table name + * @param mixed $field Column definition * @return string|string[] */ - protected function _alterTable(string $alter_type, string $table, $field) + protected function _alterTable(string $alterType, string $table, $field) { - if ($alter_type === 'DROP') + if ($alterType === 'DROP') { - return parent::_alterTable($alter_type, $table, $field); + return parent::_alterTable($alterType, $table, $field); } $sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table); @@ -182,11 +181,11 @@ protected function _alterTable(string $alter_type, string $table, $field) { if ($data['_literal'] !== false) { - $field[$i] = ($alter_type === 'ADD') ? "\n\tADD " . $data['_literal'] : "\n\tMODIFY " . $data['_literal']; + $field[$i] = ($alterType === 'ADD') ? "\n\tADD " . $data['_literal'] : "\n\tMODIFY " . $data['_literal']; } else { - if ($alter_type === 'ADD') + if ($alterType === 'ADD') { $field[$i]['_literal'] = "\n\tADD "; } @@ -212,11 +211,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 +227,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/Builder.php b/system/Database/Postgre/Builder.php index b8b38a07dc31..25027d49d6ab 100644 --- a/system/Database/Postgre/Builder.php +++ b/system/Database/Postgre/Builder.php @@ -233,7 +233,6 @@ public function replace(array $set = null) } //-------------------------------------------------------------------- - /** * Delete * @@ -241,7 +240,7 @@ public function replace(array $set = null) * * @param mixed $where * @param integer $limit - * @param boolean $reset_data + * @param boolean $resetData * * @return mixed * @throws DatabaseException @@ -249,14 +248,14 @@ public function replace(array $set = null) * @internal param the $mixed limit clause * @internal param $bool */ - public function delete($where = '', int $limit = null, bool $reset_data = true) + public function delete($where = '', int $limit = null, bool $resetData = true) { if (! empty($limit) || ! empty($this->QBLimit)) { throw new DatabaseException('PostgreSQL does not allow LIMITs on DELETE queries.'); } - return parent::delete($where, $limit, $reset_data); + return parent::delete($where, $limit, $resetData); } //-------------------------------------------------------------------- diff --git a/system/Database/Postgre/Forge.php b/system/Database/Postgre/Forge.php index c4c45e3a42da..65395ce3a37a 100644 --- a/system/Database/Postgre/Forge.php +++ b/system/Database/Postgre/Forge.php @@ -97,21 +97,20 @@ protected function _createTableAttributes(array $attributes): string } //-------------------------------------------------------------------- - /** * ALTER TABLE * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $field Column definition + * @param string $alterType ALTER type + * @param string $table Table name + * @param mixed $field Column definition * * @return string|array|boolean */ - protected function _alterTable(string $alter_type, string $table, $field) + protected function _alterTable(string $alterType, string $table, $field) { - if (in_array($alter_type, ['DROP', 'ADD'], true)) + if (in_array($alterType, ['DROP', 'ADD'], true)) { - return parent::_alterTable($alter_type, $table, $field); + return parent::_alterTable($alterType, $table, $field); } $sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table); @@ -232,21 +231,20 @@ protected function _attributeAutoIncrement(array &$attributes, array &$field) } //-------------------------------------------------------------------- - /** * Drop Table * * Generates a platform-specific DROP TABLE string * - * @param string $table Table name - * @param boolean $if_exists Whether to add an IF EXISTS condition + * @param string $table Table name + * @param boolean $ifExists Whether to add an IF EXISTS condition * @param boolean $cascade * * @return string */ - protected function _dropTable(string $table, bool $if_exists, bool $cascade): string + protected function _dropTable(string $table, bool $ifExists, bool $cascade): string { - $sql = parent::_dropTable($table, $if_exists, $cascade); + $sql = parent::_dropTable($table, $ifExists, $cascade); if ($cascade === true) { diff --git a/system/Database/SQLite3/Forge.php b/system/Database/SQLite3/Forge.php index 3591b05595e6..bd4a34273045 100644 --- a/system/Database/SQLite3/Forge.php +++ b/system/Database/SQLite3/Forge.php @@ -145,19 +145,18 @@ public function dropDatabase(string $dbName): bool } //-------------------------------------------------------------------- - /** * ALTER TABLE * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $field Column definition + * @param string $alterType ALTER type + * @param string $table Table name + * @param mixed $field Column definition * * @return string|array|null */ - protected function _alterTable(string $alter_type, string $table, $field) + protected function _alterTable(string $alterType, string $table, $field) { - switch ($alter_type) + switch ($alterType) { case 'DROP': $sqlTable = new Table($this->db, $this); @@ -176,7 +175,7 @@ protected function _alterTable(string $alter_type, string $table, $field) return null; default: - return parent::_alterTable($alter_type, $table, $field); + return parent::_alterTable($alterType, $table, $field); } } 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/Exceptions.php b/system/Debug/Exceptions.php index 3476da6b28d9..46b83690cb41 100644 --- a/system/Debug/Exceptions.php +++ b/system/Debug/Exceptions.php @@ -227,21 +227,20 @@ public function shutdownHandler() } //-------------------------------------------------------------------- - /** * Determines the view to display based on the exception thrown, * whether an HTTP or CLI request, etc. * * @param \Throwable $exception - * @param string $template_path + * @param string $templatePath * * @return string The path and filename of the view file to use */ - protected function determineView(Throwable $exception, string $template_path): string + protected function determineView(Throwable $exception, string $templatePath): string { // Production environments should have a custom exception file. - $view = 'production.php'; - $template_path = rtrim($template_path, '\\/ ') . DIRECTORY_SEPARATOR; + $view = 'production.php'; + $templatePath = rtrim($templatePath, '\\/ ') . DIRECTORY_SEPARATOR; if (str_ireplace(['off', 'none', 'no', 'false', 'null'], '', ini_get('display_errors'))) { @@ -255,7 +254,7 @@ protected function determineView(Throwable $exception, string $template_path): s } // Allow for custom views based upon the status code - if (is_file($template_path . 'error_' . $exception->getCode() . '.php')) + if (is_file($templatePath . 'error_' . $exception->getCode() . '.php')) { return 'error_' . $exception->getCode() . '.php'; } 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/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/Events/Events.php b/system/Events/Events.php index 1c236ee5906b..8f690274ac38 100644 --- a/system/Events/Events.php +++ b/system/Events/Events.php @@ -126,7 +126,6 @@ public static function initialize() } //-------------------------------------------------------------------- - /** * Registers an action to happen on an event. The action can be any sort * of callable: @@ -136,15 +135,15 @@ public static function initialize() * Events::on('create', [$myInstance, 'myMethod']); // Method on an existing instance * Events::on('create', function() {}); // Closure * - * @param string $event_name + * @param string $eventName * @param callable $callback * @param integer $priority */ - public static function on($event_name, $callback, $priority = EVENT_PRIORITY_NORMAL) + public static function on($eventName, $callback, $priority = EVENT_PRIORITY_NORMAL) { - if (! isset(static::$listeners[$event_name])) + if (! isset(static::$listeners[$eventName])) { - static::$listeners[$event_name] = [ + static::$listeners[$eventName] = [ true, // If there's only 1 item, it's sorted. [$priority], [$callback], @@ -152,9 +151,9 @@ public static function on($event_name, $callback, $priority = EVENT_PRIORITY_NOR } else { - static::$listeners[$event_name][0] = false; // Not sorted - static::$listeners[$event_name][1][] = $priority; - static::$listeners[$event_name][2][] = $callback; + static::$listeners[$eventName][0] = false; // Not sorted + static::$listeners[$eventName][1][] = $priority; + static::$listeners[$eventName][2][] = $callback; } } @@ -206,7 +205,6 @@ public static function trigger($eventName, ...$arguments): bool } //-------------------------------------------------------------------- - /** * Returns an array of listeners for a single event. They are * sorted by priority. @@ -214,56 +212,55 @@ public static function trigger($eventName, ...$arguments): bool * If the listener could not be found, returns FALSE, or TRUE if * it was removed. * - * @param string $event_name + * @param string $eventName * * @return array */ - public static function listeners($event_name): array + public static function listeners($eventName): array { - if (! isset(static::$listeners[$event_name])) + if (! isset(static::$listeners[$eventName])) { return []; } // The list is not sorted - if (! static::$listeners[$event_name][0]) + if (! static::$listeners[$eventName][0]) { // Sort it! - array_multisort(static::$listeners[$event_name][1], SORT_NUMERIC, static::$listeners[$event_name][2]); + array_multisort(static::$listeners[$eventName][1], SORT_NUMERIC, static::$listeners[$eventName][2]); // Mark it as sorted already! - static::$listeners[$event_name][0] = true; + static::$listeners[$eventName][0] = true; } - return static::$listeners[$event_name][2]; + return static::$listeners[$eventName][2]; } //-------------------------------------------------------------------- - /** * Removes a single listener from an event. * * If the listener couldn't be found, returns FALSE, else TRUE if * it was removed. * - * @param string $event_name + * @param string $eventName * @param callable $listener * * @return boolean */ - public static function removeListener($event_name, callable $listener): bool + public static function removeListener($eventName, callable $listener): bool { - if (! isset(static::$listeners[$event_name])) + if (! isset(static::$listeners[$eventName])) { return false; } - foreach (static::$listeners[$event_name][2] as $index => $check) + foreach (static::$listeners[$eventName][2] as $index => $check) { if ($check === $listener) { - unset(static::$listeners[$event_name][1][$index]); - unset(static::$listeners[$event_name][2][$index]); + unset(static::$listeners[$eventName][1][$index]); + unset(static::$listeners[$eventName][2][$index]); return true; } @@ -273,20 +270,19 @@ public static function removeListener($event_name, callable $listener): bool } //-------------------------------------------------------------------- - /** * Removes all listeners. * * If the event_name is specified, only listeners for that event will be * removed, otherwise all listeners for all events are removed. * - * @param string|null $event_name + * @param string|null $eventName */ - public static function removeAllListeners($event_name = null) + public static function removeAllListeners($eventName = null) { - if (! is_null($event_name)) + if (! is_null($eventName)) { - unset(static::$listeners[$event_name]); + unset(static::$listeners[$eventName]); } else { diff --git a/system/HTTP/CURLRequest.php b/system/HTTP/CURLRequest.php index 336f22bad093..d01c7e213ab9 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"; @@ -485,16 +485,15 @@ public function send(string $method, string $url) } //-------------------------------------------------------------------- - /** * Takes all headers current part of this request and adds them * to the cURL request. * - * @param array $curl_options + * @param array $curlOptions * * @return array */ - protected function applyRequestHeaders(array $curl_options = []): array + protected function applyRequestHeaders(array $curlOptions = []): array { if (empty($this->headers)) { @@ -508,7 +507,7 @@ protected function applyRequestHeaders(array $curl_options = []): array if (empty($headers)) { - return $curl_options; + return $curlOptions; } $set = []; @@ -518,34 +517,33 @@ protected function applyRequestHeaders(array $curl_options = []): array $set[] = $name . ': ' . $this->getHeaderLine($name); } - $curl_options[CURLOPT_HTTPHEADER] = $set; + $curlOptions[CURLOPT_HTTPHEADER] = $set; - return $curl_options; + return $curlOptions; } //-------------------------------------------------------------------- - /** * Apply method * * @param string $method - * @param array $curl_options + * @param array $curlOptions * * @return array */ - protected function applyMethod(string $method, array $curl_options): array + protected function applyMethod(string $method, array $curlOptions): array { $method = strtoupper($method); - $this->method = $method; - $curl_options[CURLOPT_CUSTOMREQUEST] = $method; + $this->method = $method; + $curlOptions[CURLOPT_CUSTOMREQUEST] = $method; $size = strlen($this->body); // Have content? if ($size > 0) { - return $this->applyBody($curl_options); + return $this->applyBody($curlOptions); } if ($method === 'PUT' || $method === 'POST') @@ -558,29 +556,28 @@ protected function applyMethod(string $method, array $curl_options): array } else if ($method === 'HEAD') { - $curl_options[CURLOPT_NOBODY] = 1; + $curlOptions[CURLOPT_NOBODY] = 1; } - return $curl_options; + return $curlOptions; } //-------------------------------------------------------------------- - /** * Apply body * - * @param array $curl_options + * @param array $curlOptions * * @return array */ - protected function applyBody(array $curl_options = []): array + protected function applyBody(array $curlOptions = []): array { if (! empty($this->body)) { - $curl_options[CURLOPT_POSTFIELDS] = (string) $this->getBody(); + $curlOptions[CURLOPT_POSTFIELDS] = (string) $this->getBody(); } - return $curl_options; + return $curlOptions; } //-------------------------------------------------------------------- @@ -620,29 +617,28 @@ protected function setResponseHeaders(array $headers = []) } //-------------------------------------------------------------------- - /** * Set CURL options * - * @param array $curl_options + * @param array $curlOptions * @param array $config * @return array * @throws \InvalidArgumentException */ - protected function setCURLOptions(array $curl_options = [], array $config = []) + protected function setCURLOptions(array $curlOptions = [], array $config = []) { // Auth Headers if (! empty($config['auth'])) { - $curl_options[CURLOPT_USERPWD] = $config['auth'][0] . ':' . $config['auth'][1]; + $curlOptions[CURLOPT_USERPWD] = $config['auth'][0] . ':' . $config['auth'][1]; if (! empty($config['auth'][2]) && strtolower($config['auth'][2]) === 'digest') { - $curl_options[CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST; + $curlOptions[CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST; } else { - $curl_options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC; + $curlOptions[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC; } } @@ -653,8 +649,8 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) if (is_array($cert)) { - $curl_options[CURLOPT_SSLCERTPASSWD] = $cert[1]; - $cert = $cert[0]; + $curlOptions[CURLOPT_SSLCERTPASSWD] = $cert[1]; + $cert = $cert[0]; } if (! is_file($cert)) @@ -662,7 +658,7 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) throw HTTPException::forSSLCertNotFound($cert); } - $curl_options[CURLOPT_SSLCERT] = $cert; + $curlOptions[CURLOPT_SSLCERT] = $cert; } // SSL Verification @@ -677,20 +673,20 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) throw HTTPException::forInvalidSSLKey($config['ssl_key']); } - $curl_options[CURLOPT_CAINFO] = $file; - $curl_options[CURLOPT_SSL_VERIFYPEER] = 1; + $curlOptions[CURLOPT_CAINFO] = $file; + $curlOptions[CURLOPT_SSL_VERIFYPEER] = 1; } else if (is_bool($config['verify'])) { - $curl_options[CURLOPT_SSL_VERIFYPEER] = $config['verify']; + $curlOptions[CURLOPT_SSL_VERIFYPEER] = $config['verify']; } } // Debug if ($config['debug']) { - $curl_options[CURLOPT_VERBOSE] = 1; - $curl_options[CURLOPT_STDERR] = is_string($config['debug']) ? fopen($config['debug'], 'a+') : fopen('php://stderr', 'w'); + $curlOptions[CURLOPT_VERBOSE] = 1; + $curlOptions[CURLOPT_STDERR] = is_string($config['debug']) ? fopen($config['debug'], 'a+') : fopen('php://stderr', 'w'); } // Decode Content @@ -700,12 +696,12 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) if ($accept) { - $curl_options[CURLOPT_ENCODING] = $accept; + $curlOptions[CURLOPT_ENCODING] = $accept; } else { - $curl_options[CURLOPT_ENCODING] = ''; - $curl_options[CURLOPT_HTTPHEADER] = 'Accept-Encoding'; + $curlOptions[CURLOPT_ENCODING] = ''; + $curlOptions[CURLOPT_HTTPHEADER] = 'Accept-Encoding'; } } @@ -721,16 +717,16 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) if ($config['allow_redirects'] === false) { - $curl_options[CURLOPT_FOLLOWLOCATION] = 0; + $curlOptions[CURLOPT_FOLLOWLOCATION] = 0; } else { - $curl_options[CURLOPT_FOLLOWLOCATION] = 1; - $curl_options[CURLOPT_MAXREDIRS] = $settings['max']; + $curlOptions[CURLOPT_FOLLOWLOCATION] = 1; + $curlOptions[CURLOPT_MAXREDIRS] = $settings['max']; if ($settings['strict'] === true) { - $curl_options[CURLOPT_POSTREDIR] = 1 | 2 | 4; + $curlOptions[CURLOPT_POSTREDIR] = 1 | 2 | 4; } $protocols = 0; @@ -739,21 +735,21 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) $protocols += constant('CURLPROTO_' . strtoupper($proto)); } - $curl_options[CURLOPT_REDIR_PROTOCOLS] = $protocols; + $curlOptions[CURLOPT_REDIR_PROTOCOLS] = $protocols; } } // Timeout - $curl_options[CURLOPT_TIMEOUT_MS] = (float) $config['timeout'] * 1000; + $curlOptions[CURLOPT_TIMEOUT_MS] = (float) $config['timeout'] * 1000; // Connection Timeout - $curl_options[CURLOPT_CONNECTTIMEOUT_MS] = (float) $config['connect_timeout'] * 1000; + $curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = (float) $config['connect_timeout'] * 1000; // Post Data - application/x-www-form-urlencoded if (! empty($config['form_params']) && is_array($config['form_params'])) { - $postFields = http_build_query($config['form_params']); - $curl_options[CURLOPT_POSTFIELDS] = $postFields; + $postFields = http_build_query($config['form_params']); + $curlOptions[CURLOPT_POSTFIELDS] = $postFields; // Ensure content-length is set, since CURL doesn't seem to // calculate it when HTTPHEADER is set. @@ -765,11 +761,11 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) if (! empty($config['multipart']) && is_array($config['multipart'])) { // setting the POSTFIELDS option automatically sets multipart - $curl_options[CURLOPT_POSTFIELDS] = $config['multipart']; + $curlOptions[CURLOPT_POSTFIELDS] = $config['multipart']; } // HTTP Errors - $curl_options[CURLOPT_FAILONERROR] = array_key_exists('http_errors', $config) ? (bool) $config['http_errors'] : true; + $curlOptions[CURLOPT_FAILONERROR] = array_key_exists('http_errors', $config) ? (bool) $config['http_errors'] : true; // JSON if (isset($config['json'])) @@ -786,41 +782,40 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) { if ($config['version'] === 1.0) { - $curl_options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0; + $curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0; } else if ($config['version'] === 1.1) { - $curl_options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; + $curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; } } // Cookie if (isset($config['cookie'])) { - $curl_options[CURLOPT_COOKIEJAR] = $config['cookie']; - $curl_options[CURLOPT_COOKIEFILE] = $config['cookie']; + $curlOptions[CURLOPT_COOKIEJAR] = $config['cookie']; + $curlOptions[CURLOPT_COOKIEFILE] = $config['cookie']; } - return $curl_options; + return $curlOptions; } //-------------------------------------------------------------------- - /** * Does the actual work of initializing cURL, setting the options, * and grabbing the output. * * @codeCoverageIgnore * - * @param array $curl_options + * @param array $curlOptions * * @return string */ - protected function sendRequest(array $curl_options = []): string + protected function sendRequest(array $curlOptions = []): string { $ch = curl_init(); - curl_setopt_array($ch, $curl_options); + curl_setopt_array($ch, $curlOptions); // Send the request and wait for a response. $output = curl_exec($ch); 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..3e23914bcf17 100644 --- a/system/Helpers/filesystem_helper.php +++ b/system/Helpers/filesystem_helper.php @@ -54,22 +54,22 @@ * representation of it. Sub-folders contained with the * directory will be mapped as well. * - * @param string $source_dir Path to source - * @param integer $directory_depth Depth of directories to traverse + * @param string $sourceDir Path to source + * @param integer $directoryDepth Depth of directories to traverse * (0 = fully recursive, 1 = current dir, etc) - * @param boolean $hidden Whether to show hidden files + * @param boolean $hidden Whether to show hidden files * * @return array */ - function directory_map(string $source_dir, int $directory_depth = 0, bool $hidden = false): array + function directory_map(string $sourceDir, int $directoryDepth = 0, bool $hidden = false): array { try { - $fp = opendir($source_dir); + $fp = opendir($sourceDir); - $fileData = []; - $new_depth = $directory_depth - 1; - $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $fileData = []; + $newDepth = $directoryDepth - 1; + $sourceDir = rtrim($sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; while (false !== ($file = readdir($fp))) { @@ -79,11 +79,11 @@ function directory_map(string $source_dir, int $directory_depth = 0, bool $hidde continue; } - is_dir($source_dir . $file) && $file .= DIRECTORY_SEPARATOR; + is_dir($sourceDir . $file) && $file .= DIRECTORY_SEPARATOR; - if (($directory_depth < 1 || $new_depth > 0) && is_dir($source_dir . $file)) + if (($directoryDepth < 1 || $newDepth > 0) && is_dir($sourceDir . $file)) { - $fileData[$file] = directory_map($source_dir . $file, $new_depth, $hidden); + $fileData[$file] = directory_map($sourceDir . $file, $newDepth, $hidden); } else { @@ -157,14 +157,14 @@ function write_file(string $path, string $data, string $mode = 'wb'): bool * If the second parameter is set to true, any directories contained * within the supplied base directory will be nuked as well. * - * @param string $path File path - * @param boolean $del_dir Whether to delete any directories found in the path - * @param boolean $htdocs Whether to skip deleting .htaccess and index page files - * @param boolean $hidden Whether to include hidden files (files beginning with a period) + * @param string $path File path + * @param boolean $delDir Whether to delete any directories found in the path + * @param boolean $htdocs Whether to skip deleting .htaccess and index page files + * @param boolean $hidden Whether to include hidden files (files beginning with a period) * * @return boolean */ - function delete_files(string $path, bool $del_dir = false, bool $htdocs = false, bool $hidden = false): bool + function delete_files(string $path, bool $delDir = false, bool $htdocs = false, bool $hidden = false): bool { $path = realpath($path) ?: $path; $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; @@ -186,7 +186,7 @@ function delete_files(string $path, bool $del_dir = false, bool $htdocs = false, { $isDir = $object->isDir(); - if ($isDir && $del_dir) + if ($isDir && $delDir) { @rmdir($object->getPathname()); continue; @@ -218,23 +218,23 @@ function delete_files(string $path, bool $del_dir = false, bool $htdocs = false, * Reads the specified directory and builds an array containing the filenames. * Any sub-folders contained within the specified path are read as well. * - * @param string $source_dir Path to source - * @param boolean|null $include_path Whether to include the path as part of the filename; false for no path, null for a relative path, true for full path - * @param boolean $hidden Whether to include hidden files (files beginning with a period) + * @param string $sourceDir Path to source + * @param boolean|null $includePath Whether to include the path as part of the filename; false for no path, null for a relative path, true for full path + * @param boolean $hidden Whether to include hidden files (files beginning with a period) * * @return array */ - function get_filenames(string $source_dir, ?bool $include_path = false, bool $hidden = false): array + function get_filenames(string $sourceDir, ?bool $includePath = false, bool $hidden = false): array { $files = []; - $source_dir = realpath($source_dir) ?: $source_dir; - $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $sourceDir = realpath($sourceDir) ?: $sourceDir; + $sourceDir = rtrim($sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; try { foreach (new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($source_dir, RecursiveDirectoryIterator::SKIP_DOTS), + new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ) as $name => $object) { @@ -244,13 +244,13 @@ function get_filenames(string $source_dir, ?bool $include_path = false, bool $hi { continue; } - elseif ($include_path === false) + elseif ($includePath === false) { $files[] = $basename; } - elseif (is_null($include_path)) + elseif (is_null($includePath)) { - $files[] = str_replace($source_dir, '', $name); + $files[] = str_replace($sourceDir, '', $name); } else { @@ -281,38 +281,38 @@ function get_filenames(string $source_dir, ?bool $include_path = false, bool $hi * * Any sub-folders contained within the specified path are read as well. * - * @param string $source_dir Path to source - * @param boolean $top_level_only Look only at the top level directory specified? - * @param boolean $recursion Internal variable to determine recursion status - do not use in calls + * @param string $sourceDir Path to source + * @param boolean $topLevelOnly Look only at the top level directory specified? + * @param boolean $recursion Internal variable to determine recursion status - do not use in calls * * @return array */ - function get_dir_file_info(string $source_dir, bool $top_level_only = true, bool $recursion = false): array + function get_dir_file_info(string $sourceDir, bool $topLevelOnly = true, bool $recursion = false): array { static $fileData = []; - $relative_path = $source_dir; + $relativePath = $sourceDir; try { - $fp = @opendir($source_dir); { + $fp = @opendir($sourceDir); { // reset the array and make sure $source_dir has a trailing slash on the initial call if ($recursion === false) { - $fileData = []; - $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $fileData = []; + $sourceDir = rtrim(realpath($sourceDir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } // Used to be foreach (scandir($source_dir, 1) as $file), but scandir() is simply not as fast while (false !== ($file = readdir($fp))) { - if (is_dir($source_dir . $file) && $file[0] !== '.' && $top_level_only === false) + if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) { - get_dir_file_info($source_dir . $file . DIRECTORY_SEPARATOR, $top_level_only, true); + get_dir_file_info($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true); } elseif ($file[0] !== '.') { - $fileData[$file] = get_file_info($source_dir . $file); - $fileData[$file]['relative_path'] = $relative_path; + $fileData[$file] = get_file_info($sourceDir . $file); + $fileData[$file]['relative_path'] = $relativePath; } } @@ -339,24 +339,24 @@ function get_dir_file_info(string $source_dir, bool $top_level_only = true, bool * Options are: name, server_path, size, date, readable, writable, executable, fileperms * Returns false if the file cannot be found. * - * @param string $file Path to file - * @param mixed $returned_values Array or comma separated string of information returned + * @param string $file Path to file + * @param mixed $returnedValues Array or comma separated string of information returned * * @return array|null */ - function get_file_info(string $file, $returned_values = ['name', 'server_path', 'size', 'date']) + function get_file_info(string $file, $returnedValues = ['name', 'server_path', 'size', 'date']) { if (! is_file($file)) { return null; } - if (is_string($returned_values)) + if (is_string($returnedValues)) { - $returned_values = explode(',', $returned_values); + $returnedValues = explode(',', $returnedValues); } - foreach ($returned_values as $key) + foreach ($returnedValues as $key) { switch ($key) { case 'name': @@ -484,11 +484,11 @@ function octal_permissions(int $perms): string * Set Realpath * * @param string $path - * @param boolean $check_existence Checks to see if the path exists + * @param boolean $checkExistence Checks to see if the path exists * * @return string */ - function set_realpath(string $path, bool $check_existence = false): string + function set_realpath(string $path, bool $checkExistence = false): string { // Security check to make sure the path is NOT a URL. No remote file inclusion! if (preg_match('#^(http:\/\/|https:\/\/|www\.|ftp)#i', $path) || filter_var($path, FILTER_VALIDATE_IP) === $path) @@ -501,7 +501,7 @@ function set_realpath(string $path, bool $check_existence = false): string { $path = realpath($path); } - elseif ($check_existence && ! is_dir($path) && ! is_file($path)) + elseif ($checkExistence && ! is_dir($path) && ! is_file($path)) { throw new InvalidArgumentException('Not a valid path: ' . $path); } diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index 554c54940984..8e834f40fa74 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"; } @@ -604,13 +604,13 @@ function form_button($data = '', string $content = '', $extra = ''): string /** * Form Label Tag * - * @param string $label_text The text to appear onscreen + * @param string $labelText The text to appear onscreen * @param string $id The id the label applies to * @param array $attributes Additional attributes * * @return string */ - function form_label(string $label_text = '', string $id = '', array $attributes = []): string + function form_label(string $labelText = '', string $id = '', array $attributes = []): string { $label = ''; + return $label . '>' . $labelText . ''; } } @@ -679,18 +679,18 @@ function form_datalist(string $name, string $value, array $options): string * Used to produce