diff --git a/.github/mergeable.yml b/.github/mergeable.yml index d23053efa3e2..95766c23fcee 100644 --- a/.github/mergeable.yml +++ b/.github/mergeable.yml @@ -2,40 +2,33 @@ version: 2 mergeable: - - when: issues.opened + - when: issues.opened, issues.reopened validate: - - do: description - and: - - must_include: - regex: '^### PHP Version' - - must_include: - regex: '^### CodeIgniter4 Version' - - do: author - and: - - must_exclude: - regex: 'kenjis' - - must_exclude: - regex: 'lonnieezell' - - must_exclude: - regex: 'MGatner' - - must_exclude: - regex: 'michalsn' - - must_exclude: - regex: 'paulbalandan' - - must_exclude: - regex: 'samsonasik' + - do: or + validate: + - do: and + validate: + - do: description + must_include: + regex: '### PHP Version' + - do: description + must_include: + regex: '### CodeIgniter4 Version' + - do: author + must_include: + regex: ^kenjis|lonnieezell|MGatner|michalsn|paulbalandan|samsonasik$ fail: - do: comment - payload: | - Hi there! :wave: + payload: + body: | + Hi there, @@author! :wave: - It looks like you opened an issue without following the bug report template: + It looks like you opened an issue without following the bug report template: - Bug report ([open an issue](https://github.com/codeigniter4/CodeIgniter4/issues/new?assignees=&labels=bug&projects=&template=bug_report.yml&title=Bug%3A+)) + * Bug report ([open an issue](https://github.com/codeigniter4/CodeIgniter4/issues/new?assignees=&labels=bug&projects=&template=bug_report.yml&title=Bug%3A+)) + * For feature request or support question, please use the [forums](https://forum.codeigniter.com/forum-30.html). - If you are opening a feature request or support question, please do so in the [forums](https://forum.codeigniter.com/forum-30.html). + The current issue will be closed. This is a precaution to save maintainers' time, I hope you'll understand. - The current issue will be closed. This is a precaution to save maintainers' time, I hope you'll understand. - - Sincerely, the mergeable bot πŸ€– + Sincerely, the mergeable bot πŸ€– - do: close diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index a50b126db075..e9240c590917 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -39,7 +39,9 @@ __DIR__ . '/spark', ]); -$overrides = []; +$overrides = [ + 'modernize_strpos' => ['modernize_stripos' => true], +]; $options = [ 'cacheFile' => 'build/.php-cs-fixer.cache', @@ -53,5 +55,5 @@ return Factory::create(new CodeIgniter4(), $overrides, $options)->forLibrary( 'CodeIgniter 4 framework', 'CodeIgniter Foundation', - 'admin@codeigniter.com' + 'admin@codeigniter.com', ); diff --git a/CHANGELOG.md b/CHANGELOG.md index d31f829aec39..200b7adb037c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog +## [v4.5.8](https://github.com/codeigniter4/CodeIgniter4/tree/v4.5.8) (2025-01-19) +[Full Changelog](https://github.com/codeigniter4/CodeIgniter4/compare/v4.5.7...v4.5.8) + +### Security + +* **HTTP** *Validation of header name and value*: Fixed a potential vulnerability on lack of proper header validation + for its name and value. See the [security advisory](https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-x5mq-jjr3-vmx6) + for more information. Credits to @neznaika0 for reporting. +* **Security** fix: ensure csrf token is string by @datlechin in https://github.com/codeigniter4/CodeIgniter4/pull/9365 + +### Fixed Bugs + +* fix: gather affected rows after query call failed by @michalsn in https://github.com/codeigniter4/CodeIgniter4/pull/9363 + +### Refactoring + +* refactor: use more strict result check on preg_match_all() result by @samsonasik in https://github.com/codeigniter4/CodeIgniter4/pull/9361 +* refactor: Fix phpstan if.condNotBoolean by @neznaika0 in https://github.com/codeigniter4/CodeIgniter4/pull/9368 +* refactor: Fix phpstan when delete string key by @neznaika0 in https://github.com/codeigniter4/CodeIgniter4/pull/9369 +* refactor: Fix phpstan greaterOrEqual.invalid by @neznaika0 in https://github.com/codeigniter4/CodeIgniter4/pull/9370 +* refactor: Fix phpstan nullCoalesce by @neznaika0 in https://github.com/codeigniter4/CodeIgniter4/pull/9374 +* refactor: Fix phpstan isset offset by @neznaika0 in https://github.com/codeigniter4/CodeIgniter4/pull/9383 +* refactor: Fix phpstan return.missing by @neznaika0 in https://github.com/codeigniter4/CodeIgniter4/pull/9382 +* refactor: Fix phpstan booleanAnd.rightAlwaysTrue by @neznaika0 in https://github.com/codeigniter4/CodeIgniter4/pull/9367 +* refactor: Fix phpstan codeigniter.configArgumentInstanceof by @neznaika0 in https://github.com/codeigniter4/CodeIgniter4/pull/9390 +* refactor: Use `strtolower` with `str_contains`/`str_**_with` as replacement for `stripos` by @paulbalandan in https://github.com/codeigniter4/CodeIgniter4/pull/9414 + ## [v4.5.7](https://github.com/codeigniter4/CodeIgniter4/tree/v4.5.7) (2024-12-31) [Full Changelog](https://github.com/codeigniter4/CodeIgniter4/compare/v4.5.6...v4.5.7) diff --git a/LICENSE b/LICENSE index 148e7f737ff6..24728f607f02 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,7 @@ The MIT License (MIT) Copyright (c) 2014-2019 British Columbia Institute of Technology -Copyright (c) 2019-2024 CodeIgniter Foundation +Copyright (c) 2019-present CodeIgniter Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/admin/create-new-changelog.php b/admin/create-new-changelog.php index ff333f42693f..cc7f8359a570 100644 --- a/admin/create-new-changelog.php +++ b/admin/create-new-changelog.php @@ -47,7 +47,7 @@ function replace_file_content(string $path, string $pattern, string $replace): v replace_file_content( $changelogIndex, '/\.\. toctree::\n :titlesonly:\n/u', - ".. toctree::\n :titlesonly:\n\n v{$version}" + ".. toctree::\n :titlesonly:\n\n v{$version}", ); // Replace {version} $length = mb_strlen("Version {$version}"); @@ -55,12 +55,12 @@ function replace_file_content(string $path, string $pattern, string $replace): v replace_file_content( $changelog, '/#################\nVersion {version}\n#################/u', - "{$underline}\nVersion {$version}\n{$underline}" + "{$underline}\nVersion {$version}\n{$underline}", ); replace_file_content( $changelog, '/{version}/u', - "{$version}" + "{$version}", ); // Copy upgrading @@ -72,7 +72,7 @@ function replace_file_content(string $path, string $pattern, string $replace): v replace_file_content( $upgradingIndex, '/ backward_compatibility_notes\n/u', - " backward_compatibility_notes\n\n upgrade_{$versionWithoutDots}" + " backward_compatibility_notes\n\n upgrade_{$versionWithoutDots}", ); // Replace {version} $length = mb_strlen("Upgrading from {$versionCurrent} to {$version}"); @@ -80,7 +80,7 @@ function replace_file_content(string $path, string $pattern, string $replace): v replace_file_content( $upgrading, '/##############################\nUpgrading from {version} to {version}\n##############################/u', - "{$underline}\nUpgrading from {$versionCurrent} to {$version}\n{$underline}" + "{$underline}\nUpgrading from {$versionCurrent} to {$version}\n{$underline}", ); // Commits diff --git a/admin/prepare-release.php b/admin/prepare-release.php index c0dcab6866ce..5d66a43b8c86 100644 --- a/admin/prepare-release.php +++ b/admin/prepare-release.php @@ -33,31 +33,31 @@ function replace_file_content(string $path, string $pattern, string $replace): v replace_file_content( './system/CodeIgniter.php', '/public const CI_VERSION = \'.*?\';/u', - "public const CI_VERSION = '{$version}';" + "public const CI_VERSION = '{$version}';", ); // Updates version number in "conf.py". replace_file_content( './user_guide_src/source/conf.py', '/^version = \'.*?\'/mu', - "version = '{$minor}'" + "version = '{$minor}'", ); replace_file_content( './user_guide_src/source/conf.py', '/^release = \'.*?\'/mu', - "release = '{$version}'" + "release = '{$version}'", ); // Updates version number in "phpdoc.dist.xml". replace_file_content( './phpdoc.dist.xml', '!CodeIgniter v.*? API!mu', - "CodeIgniter v{$minor} API" + "CodeIgniter v{$minor} API", ); replace_file_content( './phpdoc.dist.xml', '//mu', - "" + "", ); // Updates release date in changelogs. @@ -65,7 +65,7 @@ function replace_file_content(string $path, string $pattern, string $replace): v replace_file_content( "./user_guide_src/source/changelogs/v{$version}.rst", '/^Release Date: .*/mu', - "Release Date: {$date}" + "Release Date: {$date}", ); // Commits diff --git a/admin/starter/tests/unit/HealthTest.php b/admin/starter/tests/unit/HealthTest.php index f6a5a804802f..b3e480f4b0bf 100644 --- a/admin/starter/tests/unit/HealthTest.php +++ b/admin/starter/tests/unit/HealthTest.php @@ -32,7 +32,7 @@ public function testBaseUrlHasBeenSet(): void $config = new App(); $this->assertTrue( $validation->check($config->baseURL, 'valid_url'), - 'baseURL "' . $config->baseURL . '" in .env is not valid URL' + 'baseURL "' . $config->baseURL . '" in .env is not valid URL', ); } @@ -43,7 +43,7 @@ public function testBaseUrlHasBeenSet(): void // BaseURL in app/Config/App.php is a valid URL? $this->assertTrue( $validation->check($reader->baseURL, 'valid_url'), - 'baseURL "' . $reader->baseURL . '" in app/Config/App.php is not valid URL' + 'baseURL "' . $reader->baseURL . '" in app/Config/App.php is not valid URL', ); } } diff --git a/composer.json b/composer.json index 76362069c615..80fe952c9089 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "phpunit/phpcov": "^9.0.2 || ^10.0", "phpunit/phpunit": "^10.5.16 || ^11.2", "predis/predis": "^1.1 || ^2.0", - "rector/rector": "2.0.4", + "rector/rector": "2.0.6", "shipmonk/phpstan-baseline-per-identifier": "^2.0" }, "replace": { diff --git a/phpdoc.dist.xml b/phpdoc.dist.xml index 5a287a06f294..ec53ca076b8a 100644 --- a/phpdoc.dist.xml +++ b/phpdoc.dist.xml @@ -10,7 +10,7 @@ api/build/ api/cache/ - + system diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 7464323e4078..0e5c9e24f82c 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -11,7 +11,6 @@ failOnWarning="true" cacheDirectory="build/.phpunit.cache"> diff --git a/preload.php b/preload.php index 755df5e4a4ed..0b453122345e 100644 --- a/preload.php +++ b/preload.php @@ -86,7 +86,7 @@ public function load(): void $phpFiles = new RegexIterator( $fullTree, '/.+((? $file) { diff --git a/public/index.php b/public/index.php index 5ec58a7729c3..eb7f5c988838 100644 --- a/public/index.php +++ b/public/index.php @@ -11,7 +11,7 @@ $message = sprintf( 'Your PHP version must be %s or higher to run CodeIgniter. Current version: %s', $minPhpVersion, - PHP_VERSION + PHP_VERSION, ); header('HTTP/1.1 503 Service Unavailable.', true, 503); diff --git a/rector.php b/rector.php index 486685959c70..e5c21c814ab2 100644 --- a/rector.php +++ b/rector.php @@ -62,7 +62,7 @@ ->withCache( // Github action cache or local is_dir('/tmp') ? '/tmp/rector' : null, - FileCacheStorage::class + FileCacheStorage::class, ) // paths to refactor; solid alternative to CLI arguments ->withPaths([ diff --git a/spark b/spark index 992d044c9ee2..856dc3f8a227 100755 --- a/spark +++ b/spark @@ -40,7 +40,7 @@ if (version_compare(PHP_VERSION, $minPhpVersion, '<')) { $message = sprintf( 'Your PHP version must be %s or higher to run CodeIgniter. Current version: %s', $minPhpVersion, - PHP_VERSION + PHP_VERSION, ); exit($message); diff --git a/system/API/ResponseTrait.php b/system/API/ResponseTrait.php index 01ce42860b32..dbfa83dc88dc 100644 --- a/system/API/ResponseTrait.php +++ b/system/API/ResponseTrait.php @@ -319,7 +319,7 @@ protected function format($data = null) $mime = $this->request->negotiate( 'media', $format->getConfig()->supportedResponseFormats, - false + false, ); } diff --git a/system/Autoloader/Autoloader.php b/system/Autoloader/Autoloader.php index b338027c9c8a..50e6eaed2337 100644 --- a/system/Autoloader/Autoloader.php +++ b/system/Autoloader/Autoloader.php @@ -347,7 +347,7 @@ public function sanitizeFilename(string $filename): string throw new InvalidArgumentException( 'The file path contains special characters "' . $chars - . '" that are not allowed: "' . $filename . '"' + . '" that are not allowed: "' . $filename . '"', ); } if ($result === false) { @@ -386,7 +386,7 @@ private function loadComposerNamespaces(ClassLoader $composer, array $composerPa throw new RuntimeException( 'Your Composer version is too old.' . ' Please update Composer (run `composer self-update`) to v2.0.14 or later' - . ' and remove your vendor/ directory, and run `composer update`.' + . ' and remove your vendor/ directory, and run `composer update`.', ); } // This method requires Composer 2.0.14 or later. diff --git a/system/Autoloader/FileLocator.php b/system/Autoloader/FileLocator.php index 8e2564e00941..844ac7fc4cc9 100644 --- a/system/Autoloader/FileLocator.php +++ b/system/Autoloader/FileLocator.php @@ -295,9 +295,9 @@ public function findQualifiedNameFromPath(string $path) str_replace( '/', '\\', - mb_substr($path, mb_strlen($namespace['path'])) + mb_substr($path, mb_strlen($namespace['path'])), ), - '\\' + '\\', ); // Remove the file extension (.php) $className = mb_substr($className, 0, -4); diff --git a/system/BaseModel.php b/system/BaseModel.php index 05c5459d8c4b..a10acef72e2e 100644 --- a/system/BaseModel.php +++ b/system/BaseModel.php @@ -379,7 +379,7 @@ protected function createDataConverter(): void $this->converter = new DataConverter( $this->casts, $this->castHandlers, - $this->db + $this->db, ); } } @@ -1081,7 +1081,7 @@ public function updateBatch(?array $set = null, ?string $index = null, int $batc if ($updateIndex === null) { throw new InvalidArgumentException( 'The index ("' . $index . '") for updateBatch() is missing in the data: ' - . json_encode($row) + . json_encode($row), ); } diff --git a/system/Boot.php b/system/Boot.php index 4b2d20ca95b6..502692249b06 100644 --- a/system/Boot.php +++ b/system/Boot.php @@ -288,7 +288,7 @@ protected static function checkMissingExtensions(): void $message = sprintf( 'The framework needs the following extension(s) installed and loaded: %s.', - implode(', ', $missingExtensions) + implode(', ', $missingExtensions), ); header('HTTP/1.1 503 Service Unavailable.', true, 503); diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index 9a7e1459e40f..b8b90d77ba2d 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -289,7 +289,7 @@ public static function promptByKey($text, array $options, $validation = null): s CLI::isZeroOptions($options); - if ($line = array_shift($text)) { + if (($line = array_shift($text)) !== null) { CLI::write($line); } @@ -348,7 +348,7 @@ public static function promptByMultipleKeys(string $text, array $options): array // return the prompt again if $input contain(s) non-numeric character, except a comma. // And if max from $options less than max from input, // it means user tried to access null value in $options - if ($pattern === 0 || $maxOptions < $maxInput) { + if ($pattern < 1 || $maxOptions < $maxInput) { static::error('Please select correctly.'); CLI::newLine(); @@ -610,11 +610,11 @@ public static function color(string $text, string $foreground, ?string $backgrou $nonColoredText = preg_replace( $pattern, '<<__colored_string__>>', - $text + $text, ); $nonColoredChunks = preg_split( '/<<__colored_string__>>/u', - $nonColoredText + $nonColoredText, ); foreach ($nonColoredChunks as $i => $chunk) { diff --git a/system/CLI/Console.php b/system/CLI/Console.php index 725193d424b5..5cb8b57a0ad3 100644 --- a/system/CLI/Console.php +++ b/system/CLI/Console.php @@ -63,7 +63,7 @@ public function showHeader(bool $suppress = false) 'CodeIgniter v%s Command Line Tool - Server Time: %s UTC%s', CodeIgniter::CI_VERSION, date('Y-m-d H:i:s'), - date('P') + date('P'), ), 'green'); CLI::newLine(); } diff --git a/system/CLI/GeneratorTrait.php b/system/CLI/GeneratorTrait.php index 6a061a36b8b3..1024fa695259 100644 --- a/system/CLI/GeneratorTrait.php +++ b/system/CLI/GeneratorTrait.php @@ -171,7 +171,7 @@ private function generateFile(string $target, string $content): void CLI::prompt( 'Are you sure you want to continue?', ['y', 'n'], - 'required' + 'required', ) === 'n' ) { CLI::newLine(); @@ -193,7 +193,7 @@ private function generateFile(string $target, string $content): void CLI::error( lang('CLI.generator.fileExist', [clean_path($target)]), 'light_gray', - 'red' + 'red', ); CLI::newLine(); @@ -216,7 +216,7 @@ private function generateFile(string $target, string $content): void CLI::error( lang('CLI.generator.fileError', [clean_path($target)]), 'light_gray', - 'red' + 'red', ); CLI::newLine(); @@ -227,7 +227,7 @@ private function generateFile(string $target, string $content): void if ($this->getOption('force') && $isFile) { CLI::write( lang('CLI.generator.fileOverwrite', [clean_path($target)]), - 'yellow' + 'yellow', ); CLI::newLine(); @@ -236,7 +236,7 @@ private function generateFile(string $target, string $content): void CLI::write( lang('CLI.generator.fileCreate', [clean_path($target)]), - 'green' + 'green', ); CLI::newLine(); } @@ -326,10 +326,10 @@ private function normalizeInputClassName(): string '\\', array_map( pascalize(...), - explode('\\', str_replace('/', '\\', trim($class))) - ) + explode('\\', str_replace('/', '\\', trim($class))), + ), ), - '\\/' + '\\/', ); } @@ -351,7 +351,7 @@ protected function renderTemplate(array $data = []): string return view( "CodeIgniter\\Commands\\Generators\\Views\\{$this->template}", $data, - ['debug' => false] + ['debug' => false], ); } } @@ -370,15 +370,15 @@ protected function parseTemplate( string $class, array $search = [], array $replace = [], - array $data = [] + array $data = [], ): string { // Retrieves the namespace part from the fully qualified class name. $namespace = trim( implode( '\\', - array_slice(explode('\\', $class), 0, -1) + array_slice(explode('\\', $class), 0, -1), ), - '\\' + '\\', ); $search[] = '<@php'; $search[] = '{namespace}'; @@ -404,7 +404,7 @@ protected function buildContent(string $class): string && preg_match( '/(?P(?:^use [^;]+;$\n?)+)/m', $template, - $match + $match, ) ) { $imports = explode("\n", trim($match['imports'])); @@ -432,7 +432,7 @@ protected function buildPath(string $class): string CLI::error( lang('CLI.namespaceNotDefined', [$namespace]), 'light_gray', - 'red' + 'red', ); CLI::newLine(); @@ -446,7 +446,7 @@ protected function buildPath(string $class): string . str_replace( '\\', DIRECTORY_SEPARATOR, - trim(str_replace($namespace . '\\', '', $class), '\\') + trim(str_replace($namespace . '\\', '', $class), '\\'), ) . '.php'; return implode( @@ -454,8 +454,8 @@ protected function buildPath(string $class): string array_slice( explode(DIRECTORY_SEPARATOR, $file), 0, - -1 - ) + -1, + ), ) . DIRECTORY_SEPARATOR . $this->basename($file); } @@ -470,9 +470,9 @@ protected function getNamespace(): string str_replace( '/', '\\', - $this->getOption('namespace') ?? APP_NAMESPACE + $this->getOption('namespace') ?? APP_NAMESPACE, ), - '\\' + '\\', ); } diff --git a/system/Cache/Handlers/MemcachedHandler.php b/system/Cache/Handlers/MemcachedHandler.php index e1048004077a..f3bc00f40ba1 100644 --- a/system/Cache/Handlers/MemcachedHandler.php +++ b/system/Cache/Handlers/MemcachedHandler.php @@ -85,7 +85,7 @@ public function initialize() $this->memcached->addServer( $this->config['host'], $this->config['port'], - $this->config['weight'] + $this->config['weight'], ); // attempt to get status of servers @@ -103,7 +103,7 @@ public function initialize() // Check if we can connect to the server $canConnect = $this->memcached->connect( $this->config['host'], - $this->config['port'] + $this->config['port'], ); // If we can't connect, throw a CriticalError exception @@ -116,7 +116,7 @@ public function initialize() $this->config['host'], $this->config['port'], true, - $this->config['weight'] + $this->config['weight'], ); } else { throw new CriticalError('Cache: Not support Memcache(d) extension.'); diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index fc0185033d64..bdf5afe0f22f 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -82,7 +82,7 @@ public function get(string $key) $data = array_combine( ['__ci_type', '__ci_value'], - $this->redis->hmget($key, ['__ci_type', '__ci_value']) + $this->redis->hmget($key, ['__ci_type', '__ci_value']), ); if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) { diff --git a/system/Cache/ResponseCache.php b/system/Cache/ResponseCache.php index 388931813c7c..448e7b83dfd4 100644 --- a/system/Cache/ResponseCache.php +++ b/system/Cache/ResponseCache.php @@ -112,7 +112,7 @@ public function make($request, ResponseInterface $response): bool return $this->cache->save( $this->generateCacheKey($request), serialize(['headers' => $headers, 'output' => $response->getBody()]), - $this->ttl + $this->ttl, ); } diff --git a/system/CodeIgniter.php b/system/CodeIgniter.php index e92a6a10ae8c..7325c1c8431b 100644 --- a/system/CodeIgniter.php +++ b/system/CodeIgniter.php @@ -56,7 +56,7 @@ class CodeIgniter /** * The current version of CodeIgniter Framework */ - public const CI_VERSION = '4.5.7'; + public const CI_VERSION = '4.5.8'; /** * App startup time. @@ -325,7 +325,7 @@ public function run(?RouteCollectionInterface $routes = null, bool $returnRespon if ($this->context === null) { throw new LogicException( 'Context must be set before run() is called. If you are upgrading from 4.1.x, ' - . 'you need to merge `public/index.php` and `spark` file from `vendor/codeigniter4/framework`.' + . 'you need to merge `public/index.php` and `spark` file from `vendor/codeigniter4/framework`.', ); } @@ -799,7 +799,7 @@ public function displayPerformanceMetrics(string $output): string return str_replace( ['{elapsed_time}', '{memory_usage}'], [(string) $this->totalTime, number_format(memory_get_peak_usage() / 1024 / 1024, 3)], - $output + $output, ); } @@ -979,7 +979,7 @@ protected function display404errors(PageNotFoundException $e) // Throws new PageNotFoundException and remove exception message on production. throw PageNotFoundException::forPageNotFound( - (ENVIRONMENT !== 'production' || ! $this->isWeb()) ? $e->getMessage() : null + (ENVIRONMENT !== 'production' || ! $this->isWeb()) ? $e->getMessage() : null, ); } @@ -1064,7 +1064,7 @@ public function storePreviousURL($uri) $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), - $uri->getFragment() + $uri->getFragment(), )); } } diff --git a/system/Commands/Database/ShowTableInfo.php b/system/Commands/Database/ShowTableInfo.php index 147b6eb61446..2367bbff4dff 100644 --- a/system/Commands/Database/ShowTableInfo.php +++ b/system/Commands/Database/ShowTableInfo.php @@ -144,7 +144,7 @@ public function run(array $params) $tableNameNo = CLI::promptByKey( ['Here is the list of your database tables:', 'Which table do you want to see?'], $tables, - 'required' + 'required', ); CLI::newLine(); @@ -174,7 +174,7 @@ private function showDBConfig(): void ]]; CLI::table( $data, - ['hostname', 'database', 'username', 'DBDriver', 'DBPrefix', 'port'] + ['hostname', 'database', 'username', 'DBDriver', 'DBPrefix', 'port'], ); } @@ -272,7 +272,7 @@ private function makeTableRows( string $tableName, int $limitRows, int $limitFieldValue, - ?string $sortField = null + ?string $sortField = null, ): array { $this->tbody = []; @@ -290,7 +290,7 @@ private function makeTableRows( static fn ($item): string => mb_strlen((string) $item) > $limitFieldValue ? mb_substr((string) $item, 0, $limitFieldValue) . '...' : (string) $item, - $row + $row, ); $this->tbody[] = $row; } diff --git a/system/Commands/Encryption/GenerateKey.php b/system/Commands/Encryption/GenerateKey.php index 21a582a06725..a3fdbd4393a9 100644 --- a/system/Commands/Encryption/GenerateKey.php +++ b/system/Commands/Encryption/GenerateKey.php @@ -182,7 +182,7 @@ protected function writeNewEncryptionKeyToFile(string $oldKey, string $newKey): $newFileContents = preg_replace( '/^[#\s]*encryption.key[=\s]*(?:hex2bin\:[a-f0-9]{64}|base64\:(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?)$/m', $replacementKey, - $oldFileContents + $oldFileContents, ); } diff --git a/system/Commands/Generators/CellGenerator.php b/system/Commands/Generators/CellGenerator.php index 57d79ac8902b..04c5bd8adf04 100644 --- a/system/Commands/Generators/CellGenerator.php +++ b/system/Commands/Generators/CellGenerator.php @@ -96,7 +96,7 @@ public function run(array $params) $viewName = preg_replace( '/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', - $viewName + $viewName, ) ?? $viewName; $namespace = substr($className, 0, strrpos($className, '\\') + 1); diff --git a/system/Commands/Generators/CommandGenerator.php b/system/Commands/Generators/CommandGenerator.php index 8c2ebcfb5d44..a0872f63c2ba 100644 --- a/system/Commands/Generators/CommandGenerator.php +++ b/system/Commands/Generators/CommandGenerator.php @@ -115,7 +115,7 @@ protected function prepare(string $class): string $class, ['{group}', '{command}'], [$group, $command], - ['type' => $type] + ['type' => $type], ); } } diff --git a/system/Commands/Generators/ControllerGenerator.php b/system/Commands/Generators/ControllerGenerator.php index c6f54cac2888..287f92f87c30 100644 --- a/system/Commands/Generators/ControllerGenerator.php +++ b/system/Commands/Generators/ControllerGenerator.php @@ -130,7 +130,7 @@ protected function prepare(string $class): string $class, ['{useStatement}', '{extends}'], [$useStatement, $extends], - ['type' => $rest] + ['type' => $rest], ); } } diff --git a/system/Commands/Generators/TestGenerator.php b/system/Commands/Generators/TestGenerator.php index 35019c72b826..7ab6859ed9a9 100644 --- a/system/Commands/Generators/TestGenerator.php +++ b/system/Commands/Generators/TestGenerator.php @@ -102,9 +102,9 @@ protected function getNamespace(): string str_replace( '/', '\\', - $this->getOption('namespace') + $this->getOption('namespace'), ), - '\\' + '\\', ); } @@ -143,7 +143,7 @@ protected function buildPath(string $class): string CLI::error( lang('CLI.namespaceNotDefined', [$namespace]), 'light_gray', - 'red' + 'red', ); CLI::newLine(); @@ -157,7 +157,7 @@ protected function buildPath(string $class): string . str_replace( '\\', DIRECTORY_SEPARATOR, - trim(str_replace($namespace . '\\', '', $class), '\\') + trim(str_replace($namespace . '\\', '', $class), '\\'), ) . '.php'; return implode( @@ -165,8 +165,8 @@ protected function buildPath(string $class): string array_slice( explode(DIRECTORY_SEPARATOR, $file), 0, - -1 - ) + -1, + ), ) . DIRECTORY_SEPARATOR . $this->basename($file); } diff --git a/system/Commands/Translation/LocalizationFinder.php b/system/Commands/Translation/LocalizationFinder.php index e7d4eff69663..3307dab8a4e4 100644 --- a/system/Commands/Translation/LocalizationFinder.php +++ b/system/Commands/Translation/LocalizationFinder.php @@ -70,7 +70,7 @@ public function run(array $params) if (! in_array($optionLocale, config(App::class)->supportedLocales, true)) { CLI::error( 'Error: "' . $optionLocale . '" is not supported. Supported locales: ' - . implode(', ', config(App::class)->supportedLocales) + . implode(', ', config(App::class)->supportedLocales), ); return EXIT_USER_INPUT; @@ -116,7 +116,7 @@ private function process(string $currentDir, string $currentLocale): void [ 'foundLanguageKeys' => $foundLanguageKeys, 'badLanguageKeys' => $badLanguageKeys, - 'countFiles' => $countFiles + 'countFiles' => $countFiles, ] = $this->findLanguageKeysInFiles($files); ksort($foundLanguageKeys); diff --git a/system/Commands/Utilities/ConfigCheck.php b/system/Commands/Utilities/ConfigCheck.php index 7d6dc332ca45..fa84cb287caa 100644 --- a/system/Commands/Utilities/ConfigCheck.php +++ b/system/Commands/Utilities/ConfigCheck.php @@ -109,7 +109,7 @@ public function run(array $params) CLI::write($this->getKintD($config)); } else { CLI::write( - CLI::color($this->getVarDump($config), 'cyan') + CLI::color($this->getVarDump($config), 'cyan'), ); } @@ -150,7 +150,7 @@ private function getVarDump(object $config): string return preg_replace( '!.*system/Commands/Utilities/ConfigCheck.php.*\n!u', '', - $output + $output, ); } } diff --git a/system/Commands/Utilities/Environment.php b/system/Commands/Utilities/Environment.php index 17a08d21d2ce..103591209d1e 100644 --- a/system/Commands/Utilities/Environment.php +++ b/system/Commands/Utilities/Environment.php @@ -151,7 +151,7 @@ private function writeNewEnvironmentToEnvFile(string $newEnv): bool return file_put_contents( $envFile, - preg_replace($pattern, "\nCI_ENVIRONMENT = {$newEnv}", file_get_contents($envFile), -1, $count) + preg_replace($pattern, "\nCI_ENVIRONMENT = {$newEnv}", file_get_contents($envFile), -1, $count), ) !== false && $count > 0; } } diff --git a/system/Commands/Utilities/FilterCheck.php b/system/Commands/Utilities/FilterCheck.php index 56fcdb00b971..a7a8803bd776 100644 --- a/system/Commands/Utilities/FilterCheck.php +++ b/system/Commands/Utilities/FilterCheck.php @@ -100,7 +100,7 @@ public function run(array $params) CLI::color( '"' . strtoupper($method) . ' ' . $route . '"', 'black', - 'light_gray' + 'light_gray', ), ); diff --git a/system/Commands/Utilities/Optimize.php b/system/Commands/Utilities/Optimize.php index fa7612d524a6..2c147de6c3f1 100644 --- a/system/Commands/Utilities/Optimize.php +++ b/system/Commands/Utilities/Optimize.php @@ -110,13 +110,13 @@ private function enableCaching(): void [ 'public bool $configCacheEnabled = false;' => 'public bool $configCacheEnabled = true;', 'public bool $locatorCacheEnabled = false;' => 'public bool $locatorCacheEnabled = true;', - ] + ], ); if ($result) { CLI::write( 'Config Caching and FileLocator Caching are enabled in "app/Config/Optimize.php".', - 'green' + 'green', ); return; diff --git a/system/Commands/Utilities/Routes.php b/system/Commands/Utilities/Routes.php index d7a6c0b55744..2a6122cab01c 100644 --- a/system/Commands/Utilities/Routes.php +++ b/system/Commands/Utilities/Routes.php @@ -133,7 +133,7 @@ public function run(array $params) $collection->getDefaultController(), $collection->getDefaultMethod(), $methods, - $collection->getRegisteredControllers('*') + $collection->getRegisteredControllers('*'), ); $autoRoutes = $autoRouteCollector->get(); @@ -149,7 +149,7 @@ public function run(array $params) $collection->getDefaultMethod(), $methods, $collection->getRegisteredControllers('*'), - $uri + $uri, ); $autoRoutes = [...$autoRoutes, ...$autoRouteCollector->get()]; @@ -159,7 +159,7 @@ public function run(array $params) $autoRouteCollector = new AutoRouteCollector( $collection->getDefaultNamespace(), $collection->getDefaultController(), - $collection->getDefaultMethod() + $collection->getDefaultMethod(), ); $autoRoutes = $autoRouteCollector->get(); diff --git a/system/Commands/Utilities/Routes/AutoRouteCollector.php b/system/Commands/Utilities/Routes/AutoRouteCollector.php index 73009b9c9eb8..3b91d365ac80 100644 --- a/system/Commands/Utilities/Routes/AutoRouteCollector.php +++ b/system/Commands/Utilities/Routes/AutoRouteCollector.php @@ -41,7 +41,7 @@ public function get(): array $output = $reader->read( $class, $this->defaultController, - $this->defaultMethod + $this->defaultMethod, ); foreach ($output as $item) { diff --git a/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php b/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php index f6a4f371858a..f4a5204fb49b 100644 --- a/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php +++ b/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php @@ -36,7 +36,7 @@ public function __construct( private readonly string $defaultMethod, private readonly array $httpMethods, private readonly array $protectedControllers, - private readonly string $prefix = '' + private readonly string $prefix = '', ) { } @@ -59,7 +59,7 @@ public function get(): array $routes = $reader->read( $class, $this->defaultController, - $this->defaultMethod + $this->defaultMethod, ); if ($routes === []) { diff --git a/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php b/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php index 2755a389ffc3..a0a98afc829a 100644 --- a/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php +++ b/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php @@ -33,7 +33,7 @@ final class ControllerMethodReader */ public function __construct( private readonly string $namespace, - private readonly array $httpMethods + private readonly array $httpMethods, ) { $config = config(Routing::class); $this->translateURIDashes = $config->translateURIDashes; @@ -78,7 +78,7 @@ public function read(string $class, string $defaultController = 'Home', string $ $classname, $methodName, $httpVerb, - $method + $method, ); if ($routeForDefaultController !== []) { @@ -193,7 +193,7 @@ private function translateToUri(string $string): string { if ($this->translateUriToCamelCase) { $string = strtolower( - preg_replace('/([a-z\d])([A-Z])/', '$1-$2', $string) + preg_replace('/([a-z\d])([A-Z])/', '$1-$2', $string), ); } elseif ($this->translateURIDashes) { $string = str_replace('_', '-', $string); @@ -214,7 +214,7 @@ private function getRouteForDefaultController( string $classname, string $methodName, string $httpVerb, - ReflectionMethod $method + ReflectionMethod $method, ): array { $output = []; diff --git a/system/Commands/Utilities/Routes/ControllerFinder.php b/system/Commands/Utilities/Routes/ControllerFinder.php index 71de1681b547..400e30e82d2e 100644 --- a/system/Commands/Utilities/Routes/ControllerFinder.php +++ b/system/Commands/Utilities/Routes/ControllerFinder.php @@ -28,7 +28,7 @@ final class ControllerFinder * @param string $namespace namespace to search */ public function __construct( - private readonly string $namespace + private readonly string $namespace, ) { $this->locator = service('locator'); } diff --git a/system/Commands/Utilities/Routes/ControllerMethodReader.php b/system/Commands/Utilities/Routes/ControllerMethodReader.php index b40a832b4f48..cd47085932bb 100644 --- a/system/Commands/Utilities/Routes/ControllerMethodReader.php +++ b/system/Commands/Utilities/Routes/ControllerMethodReader.php @@ -57,7 +57,7 @@ public function read(string $class, string $defaultController = 'Home', string $ $defaultController, $uriByClass, $classname, - $methodName + $methodName, ); $output = [...$output, ...$routeWithoutController]; @@ -89,7 +89,7 @@ public function read(string $class, string $defaultController = 'Home', string $ $defaultController, $uriByClass, $classname, - $methodName + $methodName, ); $output = [...$output, ...$routeWithoutController]; @@ -153,7 +153,7 @@ private function getRouteWithoutController( string $defaultController, string $uriByClass, string $classname, - string $methodName + string $methodName, ): array { if ($classShortname !== $defaultController) { return []; diff --git a/system/Commands/Utilities/Routes/FilterCollector.php b/system/Commands/Utilities/Routes/FilterCollector.php index b646dcb250a1..51b36662f490 100644 --- a/system/Commands/Utilities/Routes/FilterCollector.php +++ b/system/Commands/Utilities/Routes/FilterCollector.php @@ -32,7 +32,7 @@ public function __construct( * * If set to true, route filters are not found. */ - private readonly bool $resetRoutes = false + private readonly bool $resetRoutes = false, ) { } @@ -50,7 +50,7 @@ public function get(string $method, string $uri): array @trigger_error( 'Passing lowercase HTTP method "' . $method . '" is deprecated.' . ' Use uppercase HTTP method like "' . strtoupper($method) . '".', - E_USER_DEPRECATED + E_USER_DEPRECATED, ); } diff --git a/system/Commands/Utilities/Routes/SampleURIGenerator.php b/system/Commands/Utilities/Routes/SampleURIGenerator.php index 45eb2f93201b..a0e5f09bc2cb 100644 --- a/system/Commands/Utilities/Routes/SampleURIGenerator.php +++ b/system/Commands/Utilities/Routes/SampleURIGenerator.php @@ -57,7 +57,7 @@ public function get(string $routeKey): string $sampleUri = str_replace( '{locale}', config(App::class)->defaultLocale, - $routeKey + $routeKey, ); } diff --git a/system/Common.php b/system/Common.php index d5880acf0363..863ff3cdbabb 100644 --- a/system/Common.php +++ b/system/Common.php @@ -146,7 +146,7 @@ function command(string $command) // @codeCoverageIgnoreStart throw new InvalidArgumentException(sprintf( 'Unable to parse input near "... %s ...".', - substr($command, $cursor, 10) + substr($command, $cursor, 10), )); // @codeCoverageIgnoreEnd } @@ -470,7 +470,7 @@ function esc($data, string $context = 'html', ?string $encoding = null) function force_https( int $duration = 31_536_000, ?RequestInterface $request = null, - ?ResponseInterface $response = null + ?ResponseInterface $response = null, ): void { $request ??= service('request'); @@ -1065,7 +1065,7 @@ function slash_item(string $item): ?string 'Cannot convert "%s::$%s" of type "%s" to type "string".', App::class, $item, - gettype($configItem) + gettype($configItem), )); } diff --git a/system/ComposerScripts.php b/system/ComposerScripts.php index 661247dab532..993483c5775a 100644 --- a/system/ComposerScripts.php +++ b/system/ComposerScripts.php @@ -102,7 +102,7 @@ private static function recursiveDelete(string $directory): void /** @var SplFileInfo $file */ foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator(rtrim($directory, '\\/'), FilesystemIterator::SKIP_DOTS), - RecursiveIteratorIterator::CHILD_FIRST + RecursiveIteratorIterator::CHILD_FIRST, ) as $file) { $path = $file->getPathname(); @@ -146,7 +146,7 @@ private static function recursiveMirror(string $originDir, string $targetDir): v /** @var SplFileInfo $file */ foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($originDir, FilesystemIterator::SKIP_DOTS), - RecursiveIteratorIterator::SELF_FIRST + RecursiveIteratorIterator::SELF_FIRST, ) as $file) { $origin = $file->getPathname(); $target = $targetDir . substr($origin, $dirLen); diff --git a/system/Config/DotEnv.php b/system/Config/DotEnv.php index d4a7d9e87389..7e95d1352f00 100644 --- a/system/Config/DotEnv.php +++ b/system/Config/DotEnv.php @@ -164,7 +164,7 @@ protected function sanitizeValue(string $value): string %1$s # and the closing quote .*$ # and discard any string after the closing quote /mx', - $quote + $quote, ); $value = preg_replace($regexPattern, '$1', $value); @@ -206,7 +206,7 @@ function ($matchedPatterns) { return $nestedVariable; }, - $value + $value, ); } diff --git a/system/Config/Factories.php b/system/Config/Factories.php index b845d5825f43..fd7d6a32397b 100644 --- a/system/Config/Factories.php +++ b/system/Config/Factories.php @@ -106,7 +106,7 @@ public static function define(string $component, string $alias, string $classnam } throw new InvalidArgumentException( - 'Already defined in Factories: ' . $component . ' ' . $alias . ' -> ' . self::$aliases[$component][$alias] + 'Already defined in Factories: ' . $component . ' ' . $alias . ' -> ' . self::$aliases[$component][$alias], ); } @@ -448,7 +448,7 @@ public static function reset(?string $component = null) self::$options[$component], self::$aliases[$component], self::$instances[$component], - self::$updated[$component] + self::$updated[$component], ); return; diff --git a/system/Config/Services.php b/system/Config/Services.php index aa8c180a3388..f5c5a2db4a99 100644 --- a/system/Config/Services.php +++ b/system/Config/Services.php @@ -213,7 +213,7 @@ public static function curlrequest(array $options = [], ?ResponseInterface $resp $config, new URI($options['baseURI'] ?? null), $response, - $options + $options, ); } @@ -267,7 +267,7 @@ public static function encrypter(?EncryptionConfig $config = null, $getShared = */ public static function exceptions( ?ExceptionsConfig $config = null, - bool $getShared = true + bool $getShared = true, ) { if ($getShared) { return static::getSharedInstance('exceptions', $config); @@ -569,7 +569,7 @@ public static function incomingrequest(?App $config = null, bool $getShared = tr $config, AppServices::get('uri'), 'php://input', - new UserAgent() + new UserAgent(), ); } @@ -619,7 +619,7 @@ public static function routes(bool $getShared = true) return static::getSharedInstance('routes'); } - return new RouteCollection(AppServices::get('locator'), config(Modules::class), config(Routing::class)); + return new RouteCollection(AppServices::get('locator'), new Modules(), config(Routing::class)); } /** @@ -689,7 +689,7 @@ public static function session(?SessionConfig $config = null, bool $getShared = if (! class_exists($driverName) || ! is_a($driverName, SessionBaseHandler::class, true)) { throw new InvalidArgumentException(sprintf( 'Invalid session handler "%s" provided.', - $driverName + $driverName, )); } @@ -721,7 +721,7 @@ public static function session(?SessionConfig $config = null, bool $getShared = public static function siteurifactory( ?App $config = null, ?Superglobals $superglobals = null, - bool $getShared = true + bool $getShared = true, ) { if ($getShared) { return static::getSharedInstance('siteurifactory', $config, $superglobals); @@ -741,7 +741,7 @@ public static function siteurifactory( public static function superglobals( ?array $server = null, ?array $get = null, - bool $getShared = true + bool $getShared = true, ) { if ($getShared) { return static::getSharedInstance('superglobals', $server, $get); diff --git a/system/DataCaster/Cast/ArrayCast.php b/system/DataCaster/Cast/ArrayCast.php index 4bb0f4c74093..1deddea6fc8e 100644 --- a/system/DataCaster/Cast/ArrayCast.php +++ b/system/DataCaster/Cast/ArrayCast.php @@ -24,7 +24,7 @@ class ArrayCast extends BaseCast implements CastInterface public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): array { if (! is_string($value)) { self::invalidTypeValueError($value); @@ -40,7 +40,7 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): string { return serialize($value); } diff --git a/system/DataCaster/Cast/BaseCast.php b/system/DataCaster/Cast/BaseCast.php index c3df0efee103..afe80982e3ba 100644 --- a/system/DataCaster/Cast/BaseCast.php +++ b/system/DataCaster/Cast/BaseCast.php @@ -20,7 +20,7 @@ abstract class BaseCast implements CastInterface public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): mixed { return $value; } @@ -28,7 +28,7 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): mixed { return $value; } diff --git a/system/DataCaster/Cast/BooleanCast.php b/system/DataCaster/Cast/BooleanCast.php index e4a3fde09345..6554081e155d 100644 --- a/system/DataCaster/Cast/BooleanCast.php +++ b/system/DataCaster/Cast/BooleanCast.php @@ -24,7 +24,7 @@ class BooleanCast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): bool { // For PostgreSQL if ($value === 't') { diff --git a/system/DataCaster/Cast/CSVCast.php b/system/DataCaster/Cast/CSVCast.php index 42dd3709a1db..d77c64c87b57 100644 --- a/system/DataCaster/Cast/CSVCast.php +++ b/system/DataCaster/Cast/CSVCast.php @@ -24,7 +24,7 @@ class CSVCast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): array { if (! is_string($value)) { self::invalidTypeValueError($value); @@ -36,7 +36,7 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): string { if (! is_array($value)) { self::invalidTypeValueError($value); diff --git a/system/DataCaster/Cast/CastInterface.php b/system/DataCaster/Cast/CastInterface.php index ff93dc2860bc..f90f2b227e1d 100644 --- a/system/DataCaster/Cast/CastInterface.php +++ b/system/DataCaster/Cast/CastInterface.php @@ -27,7 +27,7 @@ interface CastInterface public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): mixed; /** @@ -42,6 +42,6 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): mixed; } diff --git a/system/DataCaster/Cast/DatetimeCast.php b/system/DataCaster/Cast/DatetimeCast.php index 83e66d02217c..2953debfbf2e 100644 --- a/system/DataCaster/Cast/DatetimeCast.php +++ b/system/DataCaster/Cast/DatetimeCast.php @@ -28,7 +28,7 @@ class DatetimeCast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): Time { if (! is_string($value)) { self::invalidTypeValueError($value); @@ -56,7 +56,7 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): string { if (! $value instanceof Time) { self::invalidTypeValueError($value); diff --git a/system/DataCaster/Cast/FloatCast.php b/system/DataCaster/Cast/FloatCast.php index 7ced2e2653a7..d2173826265a 100644 --- a/system/DataCaster/Cast/FloatCast.php +++ b/system/DataCaster/Cast/FloatCast.php @@ -24,7 +24,7 @@ class FloatCast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): float { if (! is_float($value) && ! is_string($value)) { self::invalidTypeValueError($value); diff --git a/system/DataCaster/Cast/IntBoolCast.php b/system/DataCaster/Cast/IntBoolCast.php index 56977c842f0e..5aa1f2b2eb93 100644 --- a/system/DataCaster/Cast/IntBoolCast.php +++ b/system/DataCaster/Cast/IntBoolCast.php @@ -24,7 +24,7 @@ final class IntBoolCast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): bool { if (! is_int($value) && ! is_string($value)) { self::invalidTypeValueError($value); @@ -36,7 +36,7 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): int { if (! is_bool($value)) { self::invalidTypeValueError($value); diff --git a/system/DataCaster/Cast/IntegerCast.php b/system/DataCaster/Cast/IntegerCast.php index e16683b1fb8f..f65baf83150f 100644 --- a/system/DataCaster/Cast/IntegerCast.php +++ b/system/DataCaster/Cast/IntegerCast.php @@ -24,7 +24,7 @@ class IntegerCast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): int { if (! is_string($value) && ! is_int($value)) { self::invalidTypeValueError($value); diff --git a/system/DataCaster/Cast/JsonCast.php b/system/DataCaster/Cast/JsonCast.php index 316070aaedee..5ca10b385ba6 100644 --- a/system/DataCaster/Cast/JsonCast.php +++ b/system/DataCaster/Cast/JsonCast.php @@ -28,7 +28,7 @@ class JsonCast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): array|stdClass { if (! is_string($value)) { self::invalidTypeValueError($value); @@ -50,7 +50,7 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): string { try { $output = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); diff --git a/system/DataCaster/Cast/TimestampCast.php b/system/DataCaster/Cast/TimestampCast.php index 52a4d88f9e46..e33938d3e2ba 100644 --- a/system/DataCaster/Cast/TimestampCast.php +++ b/system/DataCaster/Cast/TimestampCast.php @@ -26,7 +26,7 @@ class TimestampCast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): Time { if (! is_int($value) && ! is_string($value)) { self::invalidTypeValueError($value); @@ -38,7 +38,7 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): int { if (! $value instanceof Time) { self::invalidTypeValueError($value); diff --git a/system/DataCaster/Cast/URICast.php b/system/DataCaster/Cast/URICast.php index 63f4d2271a78..f9e2f561a2b2 100644 --- a/system/DataCaster/Cast/URICast.php +++ b/system/DataCaster/Cast/URICast.php @@ -26,7 +26,7 @@ class URICast extends BaseCast public static function get( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): URI { if (! is_string($value)) { self::invalidTypeValueError($value); @@ -38,7 +38,7 @@ public static function get( public static function set( mixed $value, array $params = [], - ?object $helper = null + ?object $helper = null, ): string { if (! $value instanceof URI) { self::invalidTypeValueError($value); diff --git a/system/DataCaster/DataCaster.php b/system/DataCaster/DataCaster.php index 5a6786a03331..47eac2ff7bde 100644 --- a/system/DataCaster/DataCaster.php +++ b/system/DataCaster/DataCaster.php @@ -68,7 +68,7 @@ public function __construct( ?array $castHandlers = null, ?array $types = null, private readonly ?object $helper = null, - private readonly bool $strict = true + private readonly bool $strict = true, ) { $this->castHandlers = array_merge($this->castHandlers, $castHandlers); @@ -83,7 +83,7 @@ public function __construct( && ! is_subclass_of($handler, EntityCastInterface::class) ) { throw new InvalidArgumentException( - 'Invalid class type. It must implement CastInterface. class: ' . $handler + 'Invalid class type. It must implement CastInterface. class: ' . $handler, ); } } @@ -169,7 +169,7 @@ public function castAs(mixed $value, string $field, string $method = 'get'): mix if (! isset($handlers[$type])) { throw new InvalidArgumentException( - 'No such handler for "' . $field . '". Invalid type: ' . $type + 'No such handler for "' . $field . '". Invalid type: ' . $type, ); } diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index 54d9a8980f44..010ac17b195f 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -663,7 +663,7 @@ public function join(string $table, $cond, string $type = '', ?bool $escape = nu } else { // Split multiple conditions // @TODO This does not parse `BETWEEN a AND b` correctly. - if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE)) { + if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE) >= 1) { $conditions = []; $joints = $joints[0]; array_unshift($joints, ['', 0]); @@ -807,7 +807,7 @@ protected function whereHaving(string $qbKey, $key, $value = null, string $type '/\s*(!?=|<>|IS(?:\s+NOT)?)\s*$/i', $k, $match, - PREG_OFFSET_CAPTURE + PREG_OFFSET_CAPTURE, ) ) { $k = substr($k, 0, $match[0][1]); @@ -2022,8 +2022,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri ' = ' . $value : ' = VALUES(' . $value . ')'), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ); $this->QBOptions['sql'] = $sql; @@ -2198,7 +2198,7 @@ protected function formatValues(array $values): array * * @param array|object|null $set a dataset * - * @return false|int|list Number of rows inserted or FALSE on failure, SQL array when testMode + * @return false|int|list Number of rows inserted or FALSE on no data to perform an insert operation, SQL array when testMode */ public function insertBatch($set = null, ?bool $escape = null, int $batchSize = 100) { @@ -2291,10 +2291,10 @@ public function getCompiledInsert(bool $reset = true) $this->removeAlias($this->QBFrom[0]), true, null, - false + false, ), array_keys($this->QBSet), - array_values($this->QBSet) + array_values($this->QBSet), ); if ($reset) { @@ -2328,10 +2328,10 @@ public function insert($set = null, ?bool $escape = null) $this->removeAlias($this->QBFrom[0]), true, $escape, - false + false, ), array_keys($this->QBSet), - array_values($this->QBSet) + array_values($this->QBSet), ); if (! $this->testMode) { @@ -2653,8 +2653,8 @@ protected function _updateBatch(string $table, array $keys, array $values): stri ' = ' . $value : ' = ' . $alias . '.' . $value), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ) . "\n"; $sql .= "FROM (\n{:_table_:}"; @@ -2678,8 +2678,8 @@ protected function _updateBatch(string $table, array $keys, array $values): stri ) ), array_keys($constraints), - $constraints - ) + $constraints, + ), ); $this->QBOptions['sql'] = $sql; @@ -2694,10 +2694,10 @@ protected function _updateBatch(string $table, array $keys, array $values): stri static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . "\n"; } @@ -2924,8 +2924,8 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri ) ), array_keys($constraints), - $constraints - ) + $constraints, + ), ); // convert binds in where @@ -2949,10 +2949,10 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . "\n"; } @@ -3160,7 +3160,7 @@ protected function compileWhereHaving(string $qbKey): string '/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i', $qbkey['condition'], -1, - PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY, ); foreach ($conditions as &$condition) { @@ -3170,11 +3170,12 @@ protected function compileWhereHaving(string $qbKey): string || preg_match( '/^(\(?)(.*)(' . preg_quote($op, '/') . ')\s*(.*(? '(test <= foo)', /* the whole thing */ // 1 => '(', /* optional */ @@ -3184,7 +3185,7 @@ protected function compileWhereHaving(string $qbKey): string // 5 => ')' /* optional */ // ]; - if (isset($matches[4]) && $matches[4] !== '') { + if ($matches[4] !== '') { $protectIdentifiers = false; if (str_contains($matches[4], '.')) { $protectIdentifiers = true; @@ -3435,7 +3436,7 @@ protected function hasOperator(string $str): bool { return preg_match( '/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', - trim($str) + trim($str), ) === 1; } @@ -3469,8 +3470,8 @@ protected function getOperator(string $str, bool $list = false) return preg_match_all( '/' . implode('|', $this->pregOperators) . '/i', $str, - $match - ) ? ($list ? $match[0] : $match[0][0]) : false; + $match, + ) >= 1 ? ($list ? $match[0] : $match[0][0]) : false; } /** @@ -3500,8 +3501,8 @@ private function getOperatorFromWhereKey(string $whereKey) return preg_match_all( '/' . implode('|', $pregOperators) . '/i', $whereKey, - $match - ) ? $match[0] : false; + $match, + ) >= 1 ? $match[0] : false; } /** diff --git a/system/Database/BaseConnection.php b/system/Database/BaseConnection.php index e38c682adb09..b7107d19a34d 100644 --- a/system/Database/BaseConnection.php +++ b/system/Database/BaseConnection.php @@ -424,7 +424,7 @@ public function initialize() $connectionErrors[] = sprintf( 'Main connection [%s]: %s', $this->DBDriver, - $e->getMessage() + $e->getMessage(), ); log_message('error', 'Error connecting to the database: ' . $e); } @@ -450,7 +450,7 @@ public function initialize() 'Failover #%d [%s]: %s', ++$index, $this->DBDriver, - $e->getMessage() + $e->getMessage(), ); log_message('error', 'Error connecting to the database: ' . $e); } @@ -467,7 +467,7 @@ public function initialize() throw new DatabaseException(sprintf( 'Unable to connect to the database.%s%s', PHP_EOL, - implode(PHP_EOL, $connectionErrors) + implode(PHP_EOL, $connectionErrors), )); } } @@ -688,7 +688,7 @@ public function query(string $sql, $binds = null, bool $setEscapeFlags = true, s throw new DatabaseException( $exception->getMessage(), $exception->getCode(), - $exception + $exception, ); } @@ -1220,7 +1220,7 @@ public function escapeIdentifier(string $item): string . str_replace( $this->escapeChar, $this->escapeChar . $this->escapeChar, - $item + $item, ) . $this->escapeChar; } @@ -1277,7 +1277,7 @@ public function escapeIdentifiers($item) return preg_replace( '/' . $this->pregEscapeChar[0] . '?([^' . $this->pregEscapeChar[1] . '\.]+)' . $this->pregEscapeChar[1] . '?\./i', $this->pregEscapeChar[2] . '$1' . $this->pregEscapeChar[3] . '.', - $item + $item, ); } } @@ -1286,7 +1286,7 @@ public function escapeIdentifiers($item) return preg_replace( '/' . $this->pregEscapeChar[0] . '?([^' . $this->pregEscapeChar[1] . '\.]+)' . $this->pregEscapeChar[1] . '?(\.)?/i', $this->pregEscapeChar[2] . '$1' . $this->pregEscapeChar[3] . '$2', - $item + $item, ); } @@ -1386,7 +1386,7 @@ public function escapeString($str, bool $like = false) $this->likeEscapeChar . '%', $this->likeEscapeChar . '_', ], - $str + $str, ); } @@ -1522,7 +1522,7 @@ public function tableExists(string $tableName, bool $cached = true): bool $key = array_search( strtolower($tableName), array_map(strtolower(...), $this->dataCache['table_names']), - true + true, ); // table doesn't exist but still in cache - lets reset cache, it can be rebuilt later diff --git a/system/Database/BaseUtils.php b/system/Database/BaseUtils.php index 27b369c5cb7e..26957ffe01f1 100644 --- a/system/Database/BaseUtils.php +++ b/system/Database/BaseUtils.php @@ -217,7 +217,7 @@ public function getCSVFromResult(ResultInterface $query, string $delim = ',', st $line[] = $enclosure . str_replace( $enclosure, $enclosure . $enclosure, - (string) $item + (string) $item, ) . $enclosure; } diff --git a/system/Database/Forge.php b/system/Database/Forge.php index 974c45848d1c..6bf574818919 100644 --- a/system/Database/Forge.php +++ b/system/Database/Forge.php @@ -234,8 +234,8 @@ public function createDatabase(string $dbName, bool $ifNotExists = false): bool $ifNotExists ? $this->createDatabaseIfStr : $this->createDatabaseStr, $this->db->escapeIdentifier($dbName), $this->db->charset, - $this->db->DBCollat - ) + $this->db->DBCollat, + ), )) { // @codeCoverageIgnoreStart if ($this->db->DBDebug) { @@ -294,7 +294,7 @@ public function dropDatabase(string $dbName): bool } if (! $this->db->query( - sprintf($this->dropDatabaseStr, $this->db->escapeIdentifier($dbName)) + sprintf($this->dropDatabaseStr, $this->db->escapeIdentifier($dbName)), )) { if ($this->db->DBDebug) { throw new DatabaseException('Unable to drop the specified database.'); @@ -307,7 +307,7 @@ public function dropDatabase(string $dbName): bool $key = array_search( strtolower($dbName), array_map(strtolower(...), $this->db->dataCache['db_names']), - true + true, ); if ($key !== false) { unset($this->db->dataCache['db_names'][$key]); @@ -425,7 +425,7 @@ public function addForeignKey( $tableField = '', string $onUpdate = '', string $onDelete = '', - string $fkName = '' + string $fkName = '', ): Forge { $fieldName = (array) $fieldName; $tableField = (array) $tableField; @@ -525,7 +525,7 @@ public function dropForeignKey(string $table, string $foreignName) $sql = sprintf( (string) $this->dropConstraintStr, $this->db->escapeIdentifiers($this->db->DBPrefix . $table), - $this->db->escapeIdentifiers($foreignName) + $this->db->escapeIdentifiers($foreignName), ); if ($sql === '') { @@ -618,7 +618,7 @@ protected function _createTable(string $table, bool $ifNotExists, array $attribu 'CREATE TABLE', $this->db->escapeIdentifiers($table), $processedFields, - $this->_createTableAttributes($attributes) + $this->_createTableAttributes($attributes), ); } @@ -668,7 +668,7 @@ public function dropTable(string $tableName, bool $ifExists = false, bool $casca $key = array_search( strtolower($this->db->DBPrefix . $tableName), array_map(strtolower(...), $this->db->dataCache['table_names']), - true + true, ); if ($key !== false) { @@ -723,14 +723,14 @@ public function renameTable(string $tableName, string $newTableName) $result = $this->db->query(sprintf( $this->renameTableStr, $this->db->escapeIdentifiers($this->db->DBPrefix . $tableName), - $this->db->escapeIdentifiers($this->db->DBPrefix . $newTableName) + $this->db->escapeIdentifiers($this->db->DBPrefix . $newTableName), )); if ($result && ! empty($this->db->dataCache['table_names'])) { $key = array_search( strtolower($this->db->DBPrefix . $tableName), array_map(strtolower(...), $this->db->dataCache['table_names']), - true + true, ); if ($key !== false) { @@ -1061,7 +1061,7 @@ protected function _attributeUnique(array &$attributes, array &$field) protected function _attributeAutoIncrement(array &$attributes, array &$field) { if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true - && stripos($field['type'], 'int') !== false + && str_contains(strtolower($field['type']), 'int') ) { $field['auto_increment'] = ' AUTO_INCREMENT'; } @@ -1112,7 +1112,7 @@ public function processIndexes(string $table): bool $this->fields = array_combine( array_map(static fn ($columnName) => $columnName->name, $fieldData), - array_fill(0, count($fieldData), []) + array_fill(0, count($fieldData), []), ); } diff --git a/system/Database/MigrationRunner.php b/system/Database/MigrationRunner.php index 13919c785372..0411e1593a68 100644 --- a/system/Database/MigrationRunner.php +++ b/system/Database/MigrationRunner.php @@ -605,7 +605,7 @@ protected function addHistory($migration, int $batch) CLI::color(lang('Migrations.added'), 'yellow'), $migration->namespace, $migration->version, - $migration->class + $migration->class, ); } } @@ -625,7 +625,7 @@ protected function removeHistory($history) CLI::color(lang('Migrations.removed'), 'yellow'), $history->namespace, $history->version, - $history->class + $history->class, ); } } diff --git a/system/Database/MySQLi/Builder.php b/system/Database/MySQLi/Builder.php index 8c1de9d9f987..b8d0fa545d4f 100644 --- a/system/Database/MySQLi/Builder.php +++ b/system/Database/MySQLi/Builder.php @@ -106,8 +106,8 @@ protected function _updateBatch(string $table, array $keys, array $values): stri ) ), array_keys($constraints), - $constraints - ) + $constraints, + ), ) . "\n"; $sql .= "SET\n"; @@ -119,8 +119,8 @@ protected function _updateBatch(string $table, array $keys, array $values): stri ' = ' . $value : ' = ' . $alias . '.' . $value), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ); $this->QBOptions['sql'] = $sql; @@ -135,10 +135,10 @@ protected function _updateBatch(string $table, array $keys, array $values): stri static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . "\n"; } diff --git a/system/Database/MySQLi/Connection.php b/system/Database/MySQLi/Connection.php index f98f51fb3e19..fa542e5708bb 100644 --- a/system/Database/MySQLi/Connection.php +++ b/system/Database/MySQLi/Connection.php @@ -116,7 +116,7 @@ public function connect(bool $persistent = false) if ($this->strictOn) { $this->mysqli->options( MYSQLI_INIT_COMMAND, - "SET SESSION sql_mode = CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')" + "SET SESSION sql_mode = CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')", ); } else { $this->mysqli->options( @@ -128,7 +128,7 @@ public function connect(bool $persistent = false) 'STRICT_ALL_TABLES', ''), 'STRICT_TRANS_TABLES,', ''), ',STRICT_TRANS_TABLES', ''), - 'STRICT_TRANS_TABLES', '')" + 'STRICT_TRANS_TABLES', '')", ); } } @@ -175,7 +175,7 @@ public function connect(bool $persistent = false) $ssl['cert'] ?? null, $ssl['ca'] ?? null, $ssl['capath'] ?? null, - $ssl['cipher'] ?? null + $ssl['cipher'] ?? null, ); } @@ -190,7 +190,7 @@ public function connect(bool $persistent = false) $this->database, $port, $socket, - $clientFlags + $clientFlags, )) { // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails if (($clientFlags & MYSQLI_CLIENT_SSL) !== 0 && version_compare($this->mysqli->client_info, 'mysqlnd 5.7.3', '<=') @@ -381,7 +381,7 @@ public function escapeLikeStringDirect($str) return str_replace( [$this->likeEscapeChar, '%', '_'], ['\\' . $this->likeEscapeChar, '\\%', '\\_'], - $str + $str, ); } diff --git a/system/Database/MySQLi/Forge.php b/system/Database/MySQLi/Forge.php index c47ff4ded393..fe207f5267a5 100644 --- a/system/Database/MySQLi/Forge.php +++ b/system/Database/MySQLi/Forge.php @@ -258,7 +258,7 @@ public function dropPrimaryKey(string $table, string $keyName = ''): bool { $sql = sprintf( 'ALTER TABLE %s DROP PRIMARY KEY', - $this->db->escapeIdentifiers($this->db->DBPrefix . $table) + $this->db->escapeIdentifiers($this->db->DBPrefix . $table), ); return $this->db->query($sql); diff --git a/system/Database/OCI8/Builder.php b/system/Database/OCI8/Builder.php index 5a65ffe9b75d..5b586761e2c0 100644 --- a/system/Database/OCI8/Builder.php +++ b/system/Database/OCI8/Builder.php @@ -92,10 +92,10 @@ protected function _insertBatch(string $table, array $keys, array $values): stri static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . " FROM DUAL\n"; } @@ -287,8 +287,8 @@ protected function _updateBatch(string $table, array $keys, array $values): stri ) ), array_keys($constraints), - $constraints - ) + $constraints, + ), ) . ")\n"; $sql .= "WHEN MATCHED THEN UPDATE\n"; @@ -302,8 +302,8 @@ protected function _updateBatch(string $table, array $keys, array $values): stri ' = ' . $value : ' = ' . $alias . '.' . $value), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ); $this->QBOptions['sql'] = $sql; @@ -318,10 +318,10 @@ protected function _updateBatch(string $table, array $keys, array $values): stri static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )) . ' FROM DUAL', - $values - ) + $values, + ), ) . "\n"; } @@ -392,8 +392,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri ) ), array_keys($constraints), - $constraints - ) + $constraints, + ), ) . ")\n"; $sql .= "WHEN MATCHED THEN UPDATE SET\n"; @@ -405,8 +405,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri " = {$value}" : " = {$alias}.{$value}"), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ); $sql .= "\nWHEN NOT MATCHED THEN INSERT (" . implode(', ', $keys) . ")\nVALUES "; @@ -427,10 +427,10 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . " FROM DUAL\n"; } @@ -477,8 +477,8 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri ) ), array_keys($constraints), - $constraints - ) + $constraints, + ), ); // convert binds in where @@ -491,7 +491,7 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri $sql .= ' ' . str_replace( 'WHERE ', 'AND ', - $this->compileWhereHaving('QBWhere') + $this->compileWhereHaving('QBWhere'), ) . ')'; $this->QBOptions['sql'] = $sql; @@ -506,10 +506,10 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . " FROM DUAL\n"; } diff --git a/system/Database/OCI8/Connection.php b/system/Database/OCI8/Connection.php index c59d588ccec1..0ad7b66815e7 100644 --- a/system/Database/OCI8/Connection.php +++ b/system/Database/OCI8/Connection.php @@ -523,7 +523,7 @@ public function storedProcedure(string $procedureName, array $params) $sql = sprintf( 'BEGIN %s (' . substr(str_repeat(',%s', count($params)), 1) . '); END;', $procedureName, - ...array_map(static fn ($row) => $row['name'], $params) + ...array_map(static fn ($row) => $row['name'], $params), ); $this->resetStmtId = false; @@ -554,7 +554,7 @@ protected function bindParams($params) $param['name'], $param['value'], $param['length'] ?? -1, - $param['type'] ?? SQLT_CHR + $param['type'] ?? SQLT_CHR, ); } } diff --git a/system/Database/OCI8/Forge.php b/system/Database/OCI8/Forge.php index 7d81cff8b506..f761045d9784 100644 --- a/system/Database/OCI8/Forge.php +++ b/system/Database/OCI8/Forge.php @@ -112,7 +112,7 @@ protected function _alterTable(string $alterType, string $table, $processedField $fields = array_map( fn ($field) => $this->db->escapeIdentifiers(trim($field)), - is_string($columnNamesToDrop) ? explode(',', $columnNamesToDrop) : $columnNamesToDrop + is_string($columnNamesToDrop) ? explode(',', $columnNamesToDrop) : $columnNamesToDrop, ); return $sql . ' DROP (' . implode(',', $fields) . ') CASCADE CONSTRAINT INVALIDATE'; @@ -184,7 +184,7 @@ protected function _alterTable(string $alterType, string $table, $processedField protected function _attributeAutoIncrement(array &$attributes, array &$field) { if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true - && stripos($field['type'], 'NUMBER') !== false + && str_contains(strtolower($field['type']), 'number') && version_compare($this->db->getVersion(), '12.1', '>=') ) { $field['auto_increment'] = ' GENERATED BY DEFAULT ON NULL AS IDENTITY'; diff --git a/system/Database/Postgre/Builder.php b/system/Database/Postgre/Builder.php index 21fa222c7544..bf6e9416dc2c 100644 --- a/system/Database/Postgre/Builder.php +++ b/system/Database/Postgre/Builder.php @@ -357,8 +357,8 @@ protected function _updateBatch(string $table, array $keys, array $values): stri ' = ' . $value : ' = ' . $that->cast($alias . '.' . $value, $that->getFieldType($table, $key))), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ) . "\n"; $sql .= "FROM (\n{:_table_:}"; @@ -381,8 +381,8 @@ static function ($key, $value) use ($table, $alias, $that): string|RawSql { . $that->cast($alias . '.' . $value, $that->getFieldType($table, $value)); }, array_keys($constraints), - $constraints - ) + $constraints, + ), ); $this->QBOptions['sql'] = $sql; @@ -397,10 +397,10 @@ static function ($key, $value) use ($table, $alias, $that): string|RawSql { static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . "\n"; } @@ -528,8 +528,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri " = {$value}" : " = {$alias}.{$value}"), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ); $this->QBOptions['sql'] = $sql; @@ -584,15 +584,15 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string { return $table . '.' . $key . ' = ' . $that->cast( $alias . '.' . $value, - $that->getFieldType($table, $key) + $that->getFieldType($table, $key), ); } return $table . '.' . $value . ' = ' . $alias . '.' . $value; }, array_keys($constraints), - $constraints - ) + $constraints, + ), ); // convert binds in where @@ -605,7 +605,7 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string { $sql .= ' ' . str_replace( 'WHERE ', 'AND ', - $this->compileWhereHaving('QBWhere') + $this->compileWhereHaving('QBWhere'), ); $this->QBOptions['sql'] = $sql; @@ -620,10 +620,10 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string { static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . "\n"; } diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index ad278145afef..64b85eafb064 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -227,6 +227,10 @@ protected function getDriverFunctionPrefix(): string */ public function affectedRows(): int { + if ($this->resultID === false) { + return 0; + } + return pg_affected_rows($this->resultID); } diff --git a/system/Database/Postgre/Forge.php b/system/Database/Postgre/Forge.php index 704f3e576047..b0a38c90ed23 100644 --- a/system/Database/Postgre/Forge.php +++ b/system/Database/Postgre/Forge.php @@ -154,7 +154,7 @@ protected function _processColumn(array $processedField): string protected function _attributeType(array &$attributes) { // Reset field lengths for data types that don't support it - if (isset($attributes['CONSTRAINT']) && stripos($attributes['TYPE'], 'int') !== false) { + if (isset($attributes['CONSTRAINT']) && str_contains(strtolower($attributes['TYPE']), 'int')) { $attributes['CONSTRAINT'] = null; } diff --git a/system/Database/Query.php b/system/Database/Query.php index 36026817d4d1..f0b75513c6b5 100644 --- a/system/Database/Query.php +++ b/system/Database/Query.php @@ -342,7 +342,7 @@ protected function matchNamedBinds(string $sql, array $binds): string */ protected function matchSimpleBinds(string $sql, array $binds, int $bindCount, int $ml): string { - if ($c = preg_match_all("/'[^']*'/", $sql, $matches)) { + if ($c = preg_match_all("/'[^']*'/", $sql, $matches) >= 1) { $c = preg_match_all('/' . preg_quote($this->bindMarker, '/') . '/i', str_replace($matches[0], str_replace($this->bindMarker, str_repeat(' ', $ml), $matches[0]), $sql, $c), $matches, PREG_OFFSET_CAPTURE); // Bind values' count must match the count of markers in the query diff --git a/system/Database/SQLSRV/Builder.php b/system/Database/SQLSRV/Builder.php index e320069e80bf..ec4d41195626 100644 --- a/system/Database/SQLSRV/Builder.php +++ b/system/Database/SQLSRV/Builder.php @@ -122,7 +122,7 @@ public function join(string $table, $cond, string $type = '', ?bool $escape = nu $cond = ' ON ' . $cond; } else { // Split multiple conditions - if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE)) { + if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE) >= 1) { $conditions = []; $joints = $joints[0]; array_unshift($joints, ['', 0]); @@ -764,8 +764,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri ) ), array_keys($constraints), - $constraints - ) + $constraints, + ), ) . ")\n"; $sql .= "WHEN MATCHED THEN UPDATE SET\n"; @@ -777,8 +777,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri ' = ' . $value : " = {$alias}.{$value}"), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ); $sql .= "\nWHEN NOT MATCHED THEN INSERT (" . implode(', ', $keys) . ")\nVALUES "; @@ -792,8 +792,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri . 'isnull(IDENT_CURRENT(\'' . $fullTableName . '\')+IDENT_INCR(\'' . $fullTableName . "'),1)) ELSE {$alias}.{$columnName} END" : "{$alias}.{$columnName}", - $keys - ) + $keys, + ), ) . ');' ); diff --git a/system/Database/SQLSRV/Connection.php b/system/Database/SQLSRV/Connection.php index 6903f42eebac..26b4983dba0a 100644 --- a/system/Database/SQLSRV/Connection.php +++ b/system/Database/SQLSRV/Connection.php @@ -444,6 +444,10 @@ public function error(): array */ public function affectedRows(): int { + if ($this->resultID === false) { + return 0; + } + return sqlsrv_rows_affected($this->resultID); } diff --git a/system/Database/SQLSRV/Forge.php b/system/Database/SQLSRV/Forge.php index 18d792a6eea8..7b1da6e85ba7 100644 --- a/system/Database/SQLSRV/Forge.php +++ b/system/Database/SQLSRV/Forge.php @@ -134,12 +134,12 @@ public function createDatabase(string $dbName, bool $ifNotExists = false): bool $sql = sprintf( $this->createDatabaseIfStr, $dbName, - $this->db->escapeIdentifier($dbName) + $this->db->escapeIdentifier($dbName), ); } else { $sql = sprintf( $this->createDatabaseStr, - $this->db->escapeIdentifier($dbName) + $this->db->escapeIdentifier($dbName), ); } @@ -360,7 +360,7 @@ protected function _processColumn(array $processedField): string protected function _attributeType(array &$attributes) { // Reset field lengths for data types that don't support it - if (isset($attributes['CONSTRAINT']) && stripos($attributes['TYPE'], 'int') !== false) { + if (isset($attributes['CONSTRAINT']) && str_contains(strtolower($attributes['TYPE']), 'int')) { $attributes['CONSTRAINT'] = null; } @@ -381,8 +381,8 @@ protected function _attributeType(array &$attributes) $maxLength = max( array_map( static fn ($value): int => strlen($value), - $attributes['CONSTRAINT'] - ) + $attributes['CONSTRAINT'], + ), ); $attributes['TYPE'] = 'VARCHAR'; @@ -412,7 +412,7 @@ protected function _attributeType(array &$attributes) */ protected function _attributeAutoIncrement(array &$attributes, array &$field) { - if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true && stripos($field['type'], 'INT') !== false) { + if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true && str_contains(strtolower($field['type']), strtolower('INT'))) { $field['auto_increment'] = ' IDENTITY(1,1)'; } } diff --git a/system/Database/SQLite3/Builder.php b/system/Database/SQLite3/Builder.php index 744b64448fc6..64091cf8a2fb 100644 --- a/system/Database/SQLite3/Builder.php +++ b/system/Database/SQLite3/Builder.php @@ -196,8 +196,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri " = {$value}" : " = {$alias}.{$value}"), array_keys($updateFields), - $updateFields - ) + $updateFields, + ), ); $this->QBOptions['sql'] = $sql; @@ -268,10 +268,10 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri static fn ($value): string => 'SELECT ' . implode(', ', array_map( static fn ($key, $index): string => $index . ' ' . $key, $keys, - $value + $value, )), - $values - ) + $values, + ), ) . "\n"; } diff --git a/system/Database/SQLite3/Forge.php b/system/Database/SQLite3/Forge.php index 03120dd7a0da..31c2a7ed58a6 100644 --- a/system/Database/SQLite3/Forge.php +++ b/system/Database/SQLite3/Forge.php @@ -226,7 +226,7 @@ protected function _attributeAutoIncrement(array &$attributes, array &$field) if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true - && stripos($field['type'], 'int') !== false + && str_contains(strtolower($field['type']), 'int') ) { $field['type'] = 'INTEGER PRIMARY KEY'; $field['default'] = ''; diff --git a/system/Database/SQLite3/Table.php b/system/Database/SQLite3/Table.php index 61d4aee7535b..095d96a2d333 100644 --- a/system/Database/SQLite3/Table.php +++ b/system/Database/SQLite3/Table.php @@ -308,7 +308,7 @@ protected function createTable() $this->keys = array_filter( $this->keys, - static fn ($index): bool => count(array_intersect($index['fields'], $fieldNames)) === count($index['fields']) + static fn ($index): bool => count(array_intersect($index['fields'], $fieldNames)) === count($index['fields']), ); // Unique/Index keys @@ -334,7 +334,7 @@ protected function createTable() $this->forge->addForeignKey( $foreignKey->column_name, trim($foreignKey->foreign_table_name, $this->db->DBPrefix), - $foreignKey->foreign_column_name + $foreignKey->foreign_column_name, ); } @@ -358,15 +358,15 @@ protected function copyData() $exFields = implode( ', ', - array_map(fn ($item) => $this->db->protectIdentifiers($item), $exFields) + array_map(fn ($item) => $this->db->protectIdentifiers($item), $exFields), ); $newFields = implode( ', ', - array_map(fn ($item) => $this->db->protectIdentifiers($item), $newFields) + array_map(fn ($item) => $this->db->protectIdentifiers($item), $newFields), ); $this->db->query( - "INSERT INTO {$this->prefixedTableName}({$newFields}) SELECT {$exFields} FROM {$this->db->DBPrefix}temp_{$this->tableName}" + "INSERT INTO {$this->prefixedTableName}({$newFields}) SELECT {$exFields} FROM {$this->db->DBPrefix}temp_{$this->tableName}", ); } diff --git a/system/Debug/BaseExceptionHandler.php b/system/Debug/BaseExceptionHandler.php index 4305265d2d2c..3966b2ee1bae 100644 --- a/system/Debug/BaseExceptionHandler.php +++ b/system/Debug/BaseExceptionHandler.php @@ -61,7 +61,7 @@ abstract public function handle( RequestInterface $request, ResponseInterface $response, int $statusCode, - int $exitCode + int $exitCode, ); /** @@ -221,7 +221,7 @@ protected static function highlightFile(string $file, int $lineNumber, int $line "{$format} %s\n%s", $n + $start + 1, strip_tags($row), - implode('', $tags[0]) + implode('', $tags[0]), ); } else { $out .= sprintf('' . $format . ' %s', $n + $start + 1, $row) . "\n"; diff --git a/system/Debug/ExceptionHandler.php b/system/Debug/ExceptionHandler.php index d6f97b76a32b..8283e1ff5362 100644 --- a/system/Debug/ExceptionHandler.php +++ b/system/Debug/ExceptionHandler.php @@ -47,7 +47,7 @@ public function handle( RequestInterface $request, ResponseInterface $response, int $statusCode, - int $exitCode + int $exitCode, ): void { // ResponseTrait needs these properties. $this->request = $request; @@ -68,10 +68,10 @@ public function handle( 'HTTP/%s %s %s', $request->getProtocolVersion(), $response->getStatusCode(), - $response->getReasonPhrase() + $response->getReasonPhrase(), ), true, - $statusCode + $statusCode, ); } @@ -129,7 +129,7 @@ public function handle( protected function determineView( Throwable $exception, string $templatePath, - int $statusCode = 500 + int $statusCode = 500, ): string { // Production environments should have a custom exception file. $view = 'production.php'; @@ -138,7 +138,7 @@ protected function determineView( in_array( strtolower(ini_get('display_errors')), ['1', 'true', 'on', 'yes'], - true + true, ) ) { $view = 'error_exception.php'; diff --git a/system/Debug/ExceptionHandlerInterface.php b/system/Debug/ExceptionHandlerInterface.php index d0379e2abd63..05915c638f36 100644 --- a/system/Debug/ExceptionHandlerInterface.php +++ b/system/Debug/ExceptionHandlerInterface.php @@ -27,6 +27,6 @@ public function handle( RequestInterface $request, ResponseInterface $response, int $statusCode, - int $exitCode + int $exitCode, ): void; } diff --git a/system/Debug/Exceptions.php b/system/Debug/Exceptions.php index aa353732c197..3293d75929a3 100644 --- a/system/Debug/Exceptions.php +++ b/system/Debug/Exceptions.php @@ -164,7 +164,7 @@ public function exceptionHandler(Throwable $exception) $this->request, $this->response, $statusCode, - $exitCode + $exitCode, ); return; @@ -270,7 +270,7 @@ protected function determineView(Throwable $exception, string $templatePath): st in_array( strtolower(ini_get('display_errors')), ['1', 'true', 'on', 'yes'], - true + true, ) ) { $view = 'error_exception.php'; @@ -462,7 +462,7 @@ private function handleDeprecationError(string $message, ?string $file = null, ? 'errFile' => clean_path($file ?? ''), 'errLine' => $line ?? 0, 'trace' => self::renderBacktrace($trace), - ] + ], ); return true; @@ -567,7 +567,7 @@ public static function highlightFile(string $file, int $lineNumber, int $lines = "{$format} %s\n%s", $n + $start + 1, strip_tags($row), - implode('', $tags[0]) + implode('', $tags[0]), ); } else { $out .= sprintf('' . $format . ' %s', $n + $start + 1, $row) . "\n"; @@ -611,7 +611,7 @@ private static function renderBacktrace(array $backtrace): string $frame['class'], $frame['type'], $frame['function'], - $args + $args, ); } diff --git a/system/Debug/Toolbar.php b/system/Debug/Toolbar.php index b939e208fd21..9a884b60f5b3 100644 --- a/system/Debug/Toolbar.php +++ b/system/Debug/Toolbar.php @@ -58,7 +58,7 @@ public function __construct(ToolbarConfig $config) log_message( 'critical', 'Toolbar collector does not exist (' . $collector . ').' - . ' Please check $collectors in the app/Config/Toolbar.php file.' + . ' Please check $collectors in the app/Config/Toolbar.php file.', ); continue; @@ -391,7 +391,7 @@ public function prepare(?RequestInterface $request = null, ?ResponseInterface $r $stats['startTime'], $stats['totalTime'], $request, - $response + $response, ); helper('filesystem'); @@ -439,8 +439,8 @@ public function prepare(?RequestInterface $request = null, ?ResponseInterface $r '//', '' . $script, $response->getBody(), - 1 - ) + 1, + ), ); return; @@ -516,7 +516,7 @@ protected function format(string $data, string $format = 'html'): string $history = new History(); $history->setFiles( $debugbarTime[0], - $this->config->maxHistory + $this->config->maxHistory, ); $data['collectors'][] = $history->getAsArray(); diff --git a/system/Debug/Toolbar/Collectors/Database.php b/system/Debug/Toolbar/Collectors/Database.php index 32f7f07091b3..df876422aaf1 100644 --- a/system/Debug/Toolbar/Collectors/Database.php +++ b/system/Debug/Toolbar/Collectors/Database.php @@ -228,7 +228,7 @@ public function getTitleDetails(): string $uniqueCount, $uniqueCount > 1 ? 'of them' : '', $connectionCount, - $connectionCount > 1 ? 's' : '' + $connectionCount > 1 ? 's' : '', ); } diff --git a/system/Debug/Toolbar/Collectors/Routes.php b/system/Debug/Toolbar/Collectors/Routes.php index 561399fbf37f..47c808e7ac40 100644 --- a/system/Debug/Toolbar/Collectors/Routes.php +++ b/system/Debug/Toolbar/Collectors/Routes.php @@ -109,7 +109,7 @@ public function display(): array ' | default: ' . var_export( $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, - true + true, ), ]; } diff --git a/system/Email/Email.php b/system/Email/Email.php index 5d420cc2e99c..17b24c9de575 100644 --- a/system/Email/Email.php +++ b/system/Email/Email.php @@ -1031,7 +1031,7 @@ public function wordWrap($str, $charlim = null) $unwrap = []; - if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches)) { + if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches) >= 1) { for ($i = 0, $c = count($matches[0]); $i < $c; $i++) { $unwrap[] = $matches[1][$i]; $str = str_replace($matches[0][$i], '{{unwrapped' . $i . '}}', $str); @@ -1659,7 +1659,7 @@ protected function unwrapSpecials() $this->finalBody = preg_replace_callback( '/\{unwrap\}(.*?)\{\/unwrap\}/si', $this->removeNLCallback(...), - $this->finalBody + $this->finalBody, ); } @@ -1900,7 +1900,7 @@ protected function SMTPConnect() $this->SMTPPort, $errno, $errstr, - $this->SMTPTimeout + $this->SMTPTimeout, ); if (! is_resource($this->SMTPConnect)) { @@ -1921,7 +1921,7 @@ protected function SMTPConnect() STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT - | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT + | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT, ); if ($crypto !== true) { diff --git a/system/Entity/Entity.php b/system/Entity/Entity.php index ff2fba1f7062..0e54c722e354 100644 --- a/system/Entity/Entity.php +++ b/system/Entity/Entity.php @@ -138,7 +138,7 @@ public function __construct(?array $data = null) array_merge($this->defaultCastHandlers, $this->castHandlers), null, null, - false + false, ); $this->syncOriginal(); @@ -185,7 +185,7 @@ public function toArray(bool $onlyChanged = false, bool $cast = true, bool $recu if (is_array($this->datamap)) { $keys = array_unique( - [...array_diff($keys, $this->datamap), ...array_keys($this->datamap)] + [...array_diff($keys, $this->datamap), ...array_keys($this->datamap)], ); } diff --git a/system/Events/Events.php b/system/Events/Events.php index ad8efed62f9e..97f4e81d0369 100644 --- a/system/Events/Events.php +++ b/system/Events/Events.php @@ -76,7 +76,7 @@ public static function initialize() return; } - $config = config(Modules::class); + $config = new Modules(); $events = APPPATH . 'Config' . DIRECTORY_SEPARATOR . 'Events.php'; $files = []; @@ -212,7 +212,7 @@ public static function removeListener($eventName, callable $listener): bool if ($check === $listener) { unset( static::$listeners[$eventName][1][$index], - static::$listeners[$eventName][2][$index] + static::$listeners[$eventName][2][$index], ); return true; diff --git a/system/Exceptions/FrameworkException.php b/system/Exceptions/FrameworkException.php index 1fe47be49a6b..7ea9e6d7d51f 100644 --- a/system/Exceptions/FrameworkException.php +++ b/system/Exceptions/FrameworkException.php @@ -68,7 +68,7 @@ public static function forMissingExtension(string $extension) // @codeCoverageIgnoreStart $message = sprintf( 'The framework needs the following extension(s) installed and loaded: %s.', - $extension + $extension, ); // @codeCoverageIgnoreEnd } else { diff --git a/system/Files/FileCollection.php b/system/Files/FileCollection.php index 179bbc1d4997..369cea9ddd02 100644 --- a/system/Files/FileCollection.php +++ b/system/Files/FileCollection.php @@ -103,7 +103,7 @@ final protected static function matchFiles(array $files, string $pattern): array $pattern = str_replace( ['#', '.', '*', '?'], ['\#', '\.', '.*', '.'], - $pattern + $pattern, ); $pattern = "#\\A{$pattern}\\z#"; } diff --git a/system/Filters/Filters.php b/system/Filters/Filters.php index fd252fe1fa26..28f712f66114 100644 --- a/system/Filters/Filters.php +++ b/system/Filters/Filters.php @@ -116,7 +116,7 @@ public function __construct($config, RequestInterface $request, ResponseInterfac $this->request = &$request; $this->setResponse($response); - $this->modules = $modules ?? config(Modules::class); + $this->modules = $modules instanceof Modules ? $modules : new Modules(); if ($this->modules->shouldDiscover('filters')) { $this->discoverFilters(); @@ -202,7 +202,7 @@ private function runBefore(array $filterClasses) $result = $class->before( $this->request, - $this->argumentsClass[$className] ?? null + $this->argumentsClass[$className] ?? null, ); if ($result instanceof RequestInterface) { @@ -241,7 +241,7 @@ private function runAfter(array $filterClasses): ResponseInterface $result = $class->after( $this->request, $this->response, - $this->argumentsClass[$className] ?? null + $this->argumentsClass[$className] ?? null, ); if ($result instanceof ResponseInterface) { @@ -648,7 +648,7 @@ protected function processMethods() @trigger_error( 'Setting lowercase HTTP method key "' . strtolower($method) . '" is deprecated.' . ' Use uppercase HTTP method like "' . strtoupper($method) . '".', - E_USER_DEPRECATED + E_USER_DEPRECATED, ); $found = true; @@ -744,7 +744,7 @@ private function registerArguments(string $name, array $arguments, bool $check = if ($check && array_key_exists($name, $this->arguments)) { throw new ConfigException( '"' . $name . '" already has arguments: ' - . (($this->arguments[$name] === null) ? 'null' : implode(',', $this->arguments[$name])) + . (($this->arguments[$name] === null) ? 'null' : implode(',', $this->arguments[$name])), ); } diff --git a/system/Filters/PerformanceMetrics.php b/system/Filters/PerformanceMetrics.php index f2371c7a8d6d..51b3fa9f57d5 100644 --- a/system/Filters/PerformanceMetrics.php +++ b/system/Filters/PerformanceMetrics.php @@ -53,7 +53,7 @@ public function after(RequestInterface $request, ResponseInterface $response, $a (string) $benchmark->getElapsedTime('total_execution'), number_format(memory_get_peak_usage() / 1024 / 1024, 3), ], - $body + $body, ); $response->setBody($output); diff --git a/system/HTTP/CURLRequest.php b/system/HTTP/CURLRequest.php index 90157e4e05d4..9ce664f80865 100644 --- a/system/HTTP/CURLRequest.php +++ b/system/HTTP/CURLRequest.php @@ -342,7 +342,7 @@ protected function prepareURL(string $url): string $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), - $uri->getFragment() + $uri->getFragment(), ); } diff --git a/system/HTTP/Cors.php b/system/HTTP/Cors.php index f7619c9f83a4..2f151a738344 100644 --- a/system/HTTP/Cors.php +++ b/system/HTTP/Cors.php @@ -107,7 +107,7 @@ private function checkWildcard(string $name, int $count): void if (in_array('*', $this->config[$name], true) && $count > 1) { throw new ConfigException( "If wildcard is specified, you must set `'{$name}' => ['*']`." - . ' But using wildcard is not recommended.' + . ' But using wildcard is not recommended.', ); } } @@ -121,7 +121,7 @@ private function checkWildcardAndCredentials(string $name, string $header): void throw new ConfigException( 'When responding to a credentialed request, ' . 'the server must not specify the "*" wildcard for the ' - . $header . ' response-header value.' + . $header . ' response-header value.', ); } } @@ -176,7 +176,7 @@ private function setAllowHeaders(ResponseInterface $response): void $response->setHeader( 'Access-Control-Allow-Headers', - implode(', ', $this->config['allowedHeaders']) + implode(', ', $this->config['allowedHeaders']), ); } @@ -187,7 +187,7 @@ private function setAllowMethods(ResponseInterface $response): void $response->setHeader( 'Access-Control-Allow-Methods', - implode(', ', $this->config['allowedMethods']) + implode(', ', $this->config['allowedMethods']), ); } @@ -223,7 +223,7 @@ private function setExposeHeaders(ResponseInterface $response): void if ($this->config['exposedHeaders'] !== []) { $response->setHeader( 'Access-Control-Expose-Headers', - implode(', ', $this->config['exposedHeaders']) + implode(', ', $this->config['exposedHeaders']), ); } } diff --git a/system/HTTP/Exceptions/RedirectException.php b/system/HTTP/Exceptions/RedirectException.php index 3047bf9603eb..5ebec8e1f7a4 100644 --- a/system/HTTP/Exceptions/RedirectException.php +++ b/system/HTTP/Exceptions/RedirectException.php @@ -45,7 +45,7 @@ public function __construct($message = '', int $code = 0, ?Throwable $previous = throw new InvalidArgumentException( 'RedirectException::__construct() first argument must be a string or ResponseInterface', 0, - $this + $this, ); } @@ -55,7 +55,7 @@ public function __construct($message = '', int $code = 0, ?Throwable $previous = if ($this->response->getHeaderLine('Location') === '' && $this->response->getHeaderLine('Refresh') === '') { throw new LogicException( - 'The Response object passed to RedirectException does not contain a redirect address.' + 'The Response object passed to RedirectException does not contain a redirect address.', ); } @@ -76,7 +76,7 @@ public function getResponse(): ResponseInterface service('logger')->info( 'REDIRECTED ROUTE at ' - . ($this->response->getHeaderLine('Location') ?: substr($this->response->getHeaderLine('Refresh'), 6)) + . ($this->response->getHeaderLine('Location') ?: substr($this->response->getHeaderLine('Refresh'), 6)), ); return $this->response; diff --git a/system/HTTP/Files/FileCollection.php b/system/HTTP/Files/FileCollection.php index add2c3c03f9c..120652e8bd87 100644 --- a/system/HTTP/Files/FileCollection.php +++ b/system/HTTP/Files/FileCollection.php @@ -189,7 +189,7 @@ protected function createFileObject(array $array) $array['type'] ?? null, ($array['size'] ?? null) === null ? null : (int) $array['size'], $array['error'] ?? null, - $array['full_path'] ?? null + $array['full_path'] ?? null, ); } @@ -219,7 +219,7 @@ protected function fixFilesArray(array $data): array $stack = [&$pointer]; $iterator = new RecursiveIteratorIterator( new RecursiveArrayIterator($value), - RecursiveIteratorIterator::SELF_FIRST + RecursiveIteratorIterator::SELF_FIRST, ); foreach ($iterator as $key => $val) { diff --git a/system/HTTP/Files/UploadedFile.php b/system/HTTP/Files/UploadedFile.php index c17a9e5af8e5..b43923026021 100644 --- a/system/HTTP/Files/UploadedFile.php +++ b/system/HTTP/Files/UploadedFile.php @@ -325,7 +325,7 @@ public function guessExtension(): string */ public function getClientExtension(): string { - return pathinfo($this->originalName, PATHINFO_EXTENSION) ?? ''; + return pathinfo($this->originalName, PATHINFO_EXTENSION); } /** diff --git a/system/HTTP/Header.php b/system/HTTP/Header.php index 3832a4413a47..a21f9961536a 100644 --- a/system/HTTP/Header.php +++ b/system/HTTP/Header.php @@ -13,6 +13,7 @@ namespace CodeIgniter\HTTP; +use InvalidArgumentException; use Stringable; /** @@ -54,7 +55,7 @@ class Header implements Stringable */ public function __construct(string $name, $value = null) { - $this->name = $name; + $this->setName($name); $this->setValue($value); } @@ -81,9 +82,12 @@ public function getValue() * Sets the name of the header, overwriting any previous value. * * @return $this + * + * @throws InvalidArgumentException */ public function setName(string $name) { + $this->validateName($name); $this->name = $name; return $this; @@ -95,10 +99,16 @@ public function setName(string $name) * @param array|string>|string|null $value * * @return $this + * + * @throws InvalidArgumentException */ public function setValue($value = null) { - $this->value = is_array($value) ? $value : (string) $value; + $value = is_array($value) ? $value : (string) $value; + + $this->validateValue($value); + + $this->value = $value; return $this; } @@ -110,6 +120,8 @@ public function setValue($value = null) * @param array|string|null $value * * @return $this + * + * @throws InvalidArgumentException */ public function appendValue($value = null) { @@ -117,6 +129,8 @@ public function appendValue($value = null) return $this; } + $this->validateValue($value); + if (! is_array($this->value)) { $this->value = [$this->value]; } @@ -135,6 +149,8 @@ public function appendValue($value = null) * @param array|string|null $value * * @return $this + * + * @throws InvalidArgumentException */ public function prependValue($value = null) { @@ -142,6 +158,8 @@ public function prependValue($value = null) return $this; } + $this->validateValue($value); + if (! is_array($this->value)) { $this->value = [$this->value]; } @@ -193,4 +211,54 @@ public function __toString(): string { return $this->name . ': ' . $this->getValueLine(); } + + /** + * Validate header name. + * + * Regex is based on code from a guzzlehttp/psr7 library. + * + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + * + * @throws InvalidArgumentException + */ + private function validateName(string $name): void + { + if (preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $name) !== 1) { + throw new InvalidArgumentException('The header name is not valid as per RFC 7230.'); + } + } + + /** + * Validate header value. + * + * Regex is based on code from a guzzlehttp/psr7 library. + * + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + * + * @param array|string>|int|string $value + * + * @throws InvalidArgumentException + */ + private function validateValue(array|int|string $value): void + { + if (is_int($value)) { + return; + } + + if (is_array($value)) { + foreach ($value as $key => $val) { + $this->validateValue($key); + $this->validateValue($val); + } + + return; + } + + // The regular expression excludes obs-fold per RFC 7230#3.2.4, as sending folded lines + // is deprecated and rare. This obscure HTTP/1.1 feature is unlikely to impact legitimate + // use cases. Libraries like Guzzle and AMPHP follow the same principle. + if (preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value) !== 1) { + throw new InvalidArgumentException('The header value is not valid as per RFC 7230.'); + } + } } diff --git a/system/HTTP/Message.php b/system/HTTP/Message.php index 71c4429f28ee..6b2a5e8ba2c4 100644 --- a/system/HTTP/Message.php +++ b/system/HTTP/Message.php @@ -119,7 +119,7 @@ public function getHeaderLine(string $name): string if ($this->hasMultipleHeaders($name)) { throw new InvalidArgumentException( 'The header "' . $name . '" already has multiple headers.' - . ' You cannot use getHeaderLine().' + . ' You cannot use getHeaderLine().', ); } diff --git a/system/HTTP/MessageTrait.php b/system/HTTP/MessageTrait.php index 2f6e57a90c57..9ae7737a8e8f 100644 --- a/system/HTTP/MessageTrait.php +++ b/system/HTTP/MessageTrait.php @@ -182,7 +182,7 @@ private function checkMultipleHeaders(string $name): void if ($this->hasMultipleHeaders($name)) { throw new InvalidArgumentException( 'The header "' . $name . '" already has multiple headers.' - . ' You cannot change them. If you really need to change, remove the header first.' + . ' You cannot change them. If you really need to change, remove the header first.', ); } } diff --git a/system/HTTP/Negotiate.php b/system/HTTP/Negotiate.php index 33938c8f0741..ff4d2998766b 100644 --- a/system/HTTP/Negotiate.php +++ b/system/HTTP/Negotiate.php @@ -90,7 +90,7 @@ public function charset(array $supported): string $supported, $this->request->getHeaderLine('accept-charset'), false, - true + true, ); // If no charset is shown as a match, ignore the directive @@ -154,7 +154,7 @@ protected function getBestMatch( ?string $header = null, bool $enforceTypes = false, bool $strictMatch = false, - bool $matchLocales = false + bool $matchLocales = false, ): string { if ($supported === []) { throw HTTPException::forEmptySupportedNegotiations(); @@ -212,7 +212,7 @@ public function parseHeader(string $header): array if (preg_match( '/^(?P.+?)=(?P"|\')?(?P.*?)(?:\k)?$/', $pair, - $param + $param, )) { $parameters[trim($param['name'])] = trim($param['value']); } diff --git a/system/HTTP/OutgoingRequest.php b/system/HTTP/OutgoingRequest.php index e62f07241558..eba5babdf6bb 100644 --- a/system/HTTP/OutgoingRequest.php +++ b/system/HTTP/OutgoingRequest.php @@ -43,7 +43,7 @@ public function __construct( ?URI $uri = null, array $headers = [], $body = null, - string $version = '1.1' + string $version = '1.1', ) { $this->method = $method; $this->uri = $uri; diff --git a/system/HTTP/RequestTrait.php b/system/HTTP/RequestTrait.php index dfa4b663dbaf..39f4269ef1df 100644 --- a/system/HTTP/RequestTrait.php +++ b/system/HTTP/RequestTrait.php @@ -72,7 +72,7 @@ public function getIPAddress(): string if (! empty($proxyIPs) && (! is_array($proxyIPs) || is_int(array_key_first($proxyIPs)))) { throw new ConfigException( - 'You must set an array with Proxy IP address key and HTTP header name value in Config\App::$proxyIPs.' + 'You must set an array with Proxy IP address key and HTTP header name value in Config\App::$proxyIPs.', ); } diff --git a/system/HTTP/ResponseInterface.php b/system/HTTP/ResponseInterface.php index 382a2847c503..58f11a0f9065 100644 --- a/system/HTTP/ResponseInterface.php +++ b/system/HTTP/ResponseInterface.php @@ -341,7 +341,7 @@ public function setCookie( $prefix = '', $secure = false, $httponly = false, - $samesite = null + $samesite = null, ); /** diff --git a/system/HTTP/ResponseTrait.php b/system/HTTP/ResponseTrait.php index eaf60f2b38b4..b23e40a9046b 100644 --- a/system/HTTP/ResponseTrait.php +++ b/system/HTTP/ResponseTrait.php @@ -407,14 +407,14 @@ public function sendHeaders() header( $name . ': ' . $value->getValueLine(), false, - $this->getStatusCode() + $this->getStatusCode(), ); } else { foreach ($value as $header) { header( $name . ': ' . $header->getValueLine(), false, - $this->getStatusCode() + $this->getStatusCode(), ); } } @@ -512,7 +512,7 @@ public function setCookie( $prefix = '', $secure = null, $httponly = null, - $samesite = null + $samesite = null, ) { if ($name instanceof Cookie) { $this->cookieStore = $this->cookieStore->put($name); diff --git a/system/HTTP/SiteURI.php b/system/HTTP/SiteURI.php index 2be70a7773ef..63181b89fead 100644 --- a/system/HTTP/SiteURI.php +++ b/system/HTTP/SiteURI.php @@ -95,7 +95,7 @@ public function __construct( App $configApp, string $relativePath = '', ?string $host = null, - ?string $scheme = null + ?string $scheme = null, ) { $this->indexPage = $configApp->indexPage; @@ -142,7 +142,7 @@ private function parseRelativePath(string $relativePath): array private function determineBaseURL( App $configApp, ?string $host, - ?string $scheme + ?string $scheme, ): URI { $baseURL = $this->normalizeBaseURL($configApp); @@ -199,7 +199,7 @@ private function normalizeBaseURL(App $configApp): string // Validate baseURL if (filter_var($baseURL, FILTER_VALIDATE_URL) === false) { throw new ConfigException( - 'Config\App::$baseURL "' . $baseURL . '" is not a valid URL.' + 'Config\App::$baseURL "' . $baseURL . '" is not a valid URL.', ); } @@ -266,7 +266,7 @@ public function __toString(): string $this->getAuthority(), $this->getPath(), $this->getQuery(), - $this->getFragment() + $this->getFragment(), ); } diff --git a/system/HTTP/URI.php b/system/HTTP/URI.php index 2b386797fecd..c9d634d3846d 100644 --- a/system/HTTP/URI.php +++ b/system/HTTP/URI.php @@ -163,7 +163,7 @@ public static function createURIString( ?string $authority = null, ?string $path = null, ?string $query = null, - ?string $fragment = null + ?string $fragment = null, ): string { $uri = ''; if ($scheme !== null && $scheme !== '') { @@ -638,7 +638,7 @@ public function __toString(): string $this->getAuthority(), $path, // Absolute URIs should use a "/" for an empty path $this->getQuery(), - $this->getFragment() + $this->getFragment(), ); } @@ -1022,7 +1022,7 @@ protected function filterPath(?string $path = null): string $path = preg_replace_callback( '/(?:[^' . static::CHAR_UNRESERVED . ':@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/', static fn (array $matches): string => rawurlencode($matches[0]), - $path + $path, ); return $path; @@ -1170,7 +1170,7 @@ protected function parseStr(string $query): array $params = array_map(static fn (string $chunk): ?string => preg_replace_callback( '/^(?[^&=]+?)(?:\[[^&=]*\])?=(?[^&=]+)/', static fn (array $match): string => str_replace($match['key'], bin2hex($match['key']), $match[0]), - urldecode($chunk) + urldecode($chunk), ), $query); $params = implode('&', $params); diff --git a/system/Helpers/Array/ArrayHelper.php b/system/Helpers/Array/ArrayHelper.php index fc5bc462956e..1b812e6a5123 100644 --- a/system/Helpers/Array/ArrayHelper.php +++ b/system/Helpers/Array/ArrayHelper.php @@ -54,12 +54,12 @@ private static function convertToArray(string $index): array '/(? str_replace('\.', '.', $key), - $segments + $segments, ); } @@ -130,7 +130,7 @@ public static function dotKeyExists(string $index, array $array): bool { if (str_ends_with($index, '*') || str_contains($index, '*.*')) { throw new InvalidArgumentException( - 'You must set key right after "*". Invalid index: "' . $index . '"' + 'You must set key right after "*". Invalid index: "' . $index . '"', ); } @@ -210,7 +210,7 @@ private static function arrayAttachIndexedValue( array $result, array $row, array $indexes, - bool $includeEmpty + bool $includeEmpty, ): array { if (($index = array_shift($indexes)) === null) { $result[] = $row; diff --git a/system/Helpers/cookie_helper.php b/system/Helpers/cookie_helper.php index 27007104e68e..18239fe2ebff 100644 --- a/system/Helpers/cookie_helper.php +++ b/system/Helpers/cookie_helper.php @@ -46,7 +46,7 @@ function set_cookie( string $prefix = '', ?bool $secure = null, ?bool $httpOnly = null, - ?string $sameSite = null + ?string $sameSite = null, ): void { $response = service('response'); $response->setCookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httpOnly, $sameSite); diff --git a/system/Helpers/date_helper.php b/system/Helpers/date_helper.php index c0b4d5ebe17a..c16da6592886 100644 --- a/system/Helpers/date_helper.php +++ b/system/Helpers/date_helper.php @@ -43,7 +43,7 @@ function now(?string $timezone = null): int $year, $hour, $minute, - $second + $second, ); return mktime($hour, $minute, $second, $month, $day, $year); diff --git a/system/Helpers/filesystem_helper.php b/system/Helpers/filesystem_helper.php index d5f2d974e4ad..9c0196b4752f 100644 --- a/system/Helpers/filesystem_helper.php +++ b/system/Helpers/filesystem_helper.php @@ -87,7 +87,7 @@ function directory_mirror(string $originDir, string $targetDir, bool $overwrite */ foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($originDir, FilesystemIterator::SKIP_DOTS), - RecursiveIteratorIterator::SELF_FIRST + RecursiveIteratorIterator::SELF_FIRST, ) as $file) { $origin = $file->getPathname(); $target = $targetDir . substr($origin, $dirLen); @@ -96,7 +96,7 @@ function directory_mirror(string $originDir, string $targetDir, bool $overwrite if (! is_dir($target)) { mkdir($target, 0755); } - } elseif (! is_file($target) || ($overwrite && is_file($target))) { + } elseif ($overwrite || ! is_file($target)) { copy($origin, $target); } } @@ -159,7 +159,7 @@ function delete_files(string $path, bool $delDir = false, bool $htdocs = false, try { foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS), - RecursiveIteratorIterator::CHILD_FIRST + RecursiveIteratorIterator::CHILD_FIRST, ) as $object) { $filename = $object->getFilename(); if (! $hidden && $filename[0] === '.') { @@ -202,7 +202,7 @@ function get_filenames( string $sourceDir, ?bool $includePath = false, bool $hidden = false, - bool $includeDir = true + bool $includeDir = true, ): array { $files = []; @@ -212,7 +212,7 @@ function get_filenames( try { foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS), - RecursiveIteratorIterator::SELF_FIRST + RecursiveIteratorIterator::SELF_FIRST, ) as $name => $object) { $basename = pathinfo($name, PATHINFO_BASENAME); if (! $hidden && $basename[0] === '.') { diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index 679008c9731a..7b89bb9ec173 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -49,10 +49,10 @@ function form_open(string $action = '', $attributes = [], array $hidden = []): s $attributes = stringify_attributes($attributes); - if (stripos($attributes, 'method=') === false) { + if (! str_contains(strtolower($attributes), 'method=')) { $attributes .= ' method="post"'; } - if (stripos($attributes, 'accept-charset=') === false) { + if (! str_contains(strtolower($attributes), 'accept-charset=')) { $config = config(App::class); $attributes .= ' accept-charset="' . strtolower($config->charset) . '"'; } @@ -62,7 +62,7 @@ function form_open(string $action = '', $attributes = [], array $hidden = []): s // Add CSRF field if enabled, but leave it out for GET requests and requests to external websites $before = service('filters')->getFilters()['before']; - if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && str_contains($action, base_url()) && stripos($form, 'method="get"') === false) { + if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && str_contains($action, base_url()) && ! str_contains(strtolower($form), strtolower('method="get"'))) { $form .= csrf_field($csrfId ?? null); } @@ -223,11 +223,11 @@ function form_textarea($data = '', string $value = '', $extra = ''): string } // Unsets default rows and cols if defined in extra field as array or string. - if ((is_array($extra) && array_key_exists('rows', $extra)) || (is_string($extra) && stripos(preg_replace('/\s+/', '', $extra), 'rows=') !== false)) { + if ((is_array($extra) && array_key_exists('rows', $extra)) || (is_string($extra) && str_contains(strtolower(preg_replace('/\s+/', '', $extra)), 'rows='))) { unset($defaults['rows']); } - if ((is_array($extra) && array_key_exists('cols', $extra)) || (is_string($extra) && stripos(preg_replace('/\s+/', '', $extra), 'cols=') !== false)) { + if ((is_array($extra) && array_key_exists('cols', $extra)) || (is_string($extra) && str_contains(strtolower(preg_replace('/\s+/', '', $extra)), 'cols='))) { unset($defaults['cols']); } @@ -248,7 +248,7 @@ function form_multiselect($name = '', array $options = [], array $selected = [], { $extra = stringify_attributes($extra); - if (stripos($extra, 'multiple') === false) { + if (! str_contains(strtolower($extra), strtolower('multiple'))) { $extra .= ' multiple="multiple"'; } @@ -305,7 +305,7 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): } $extra = stringify_attributes($extra); - $multiple = (count($selected) > 1 && stripos($extra, 'multiple') === false) ? ' multiple="multiple"' : ''; + $multiple = (count($selected) > 1 && ! str_contains(strtolower($extra), 'multiple')) ? ' multiple="multiple"' : ''; $form = '