From 3dfd4bcb4c9ba326733ced3ff737e0e5e876fc2a Mon Sep 17 00:00:00 2001 From: kenjis Date: Fri, 6 Sep 2024 13:53:08 +0900 Subject: [PATCH 001/108] docs: fix param types --- user_guide_src/source/helpers/url_helper.rst | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/user_guide_src/source/helpers/url_helper.rst b/user_guide_src/source/helpers/url_helper.rst index 9278539b3aea..6d136855ea47 100644 --- a/user_guide_src/source/helpers/url_helper.rst +++ b/user_guide_src/source/helpers/url_helper.rst @@ -124,7 +124,7 @@ The following functions are available: :param boolean $returnObject: True if you would like a URI instance returned instead of a string. :returns: The URL the user was previously on - :rtype: string|mixed|\\CodeIgniter\\HTTP\\URI + :rtype: string|\\CodeIgniter\\HTTP\\URI Returns the full URL (including segments) of the page the user was previously on. @@ -182,10 +182,10 @@ The following functions are available: .. php:function:: anchor([$uri = ''[, $title = ''[, $attributes = ''[, $altConfig = null]]]]) - :param mixed $uri: URI string or array of URI segments - :param string $title: Anchor title - :param mixed $attributes: HTML attributes - :param \\Config\\App $altConfig: Alternate configuration to use + :param array|string $uri: URI string or array of URI segments + :param string $title: Anchor title + :param array|object|string $attributes: HTML attributes + :param \\Config\\App|null $altConfig: Alternate configuration to use :returns: HTML hyperlink (anchor tag) :rtype: string @@ -222,7 +222,7 @@ The following functions are available: :param string $uri: URI string :param string $title: Anchor title - :param mixed $attributes: HTML attributes + :param array|false|object|string $attributes: HTML attributes :param \\Config\\App $altConfig: Alternate configuration to use :returns: Pop-up hyperlink :rtype: string @@ -262,7 +262,7 @@ The following functions are available: :param string $email: E-mail address :param string $title: Anchor title - :param mixed $attributes: HTML attributes + :param array|object|string $attributes: HTML attributes :returns: A "mail to" hyperlink :rtype: string @@ -281,7 +281,7 @@ The following functions are available: :param string $email: E-mail address :param string $title: Anchor title - :param mixed $attributes: HTML attributes + :param array|object|string $attributes: HTML attributes :returns: A spam-safe "mail to" hyperlink :rtype: string @@ -378,7 +378,7 @@ The following functions are available: .. php:function:: url_to($controller[, ...$args]) :param string $controller: Route name or Controller::method - :param mixed ...$args: One or more parameters to be passed to the route. The last parameter allows you to set the locale. + :param int|string ...$args: One or more parameters to be passed to the route. The last parameter allows you to set the locale. :returns: Absolute URL :rtype: string From 2ef57abe351b9c1488290e944046c86d6ba38bdf Mon Sep 17 00:00:00 2001 From: kenjis Date: Fri, 6 Sep 2024 13:53:24 +0900 Subject: [PATCH 002/108] docs: decorate text --- user_guide_src/source/helpers/url_helper.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/user_guide_src/source/helpers/url_helper.rst b/user_guide_src/source/helpers/url_helper.rst index 6d136855ea47..44e52dd0d8a3 100644 --- a/user_guide_src/source/helpers/url_helper.rst +++ b/user_guide_src/source/helpers/url_helper.rst @@ -21,7 +21,7 @@ The following functions are available: .. php:function:: site_url([$uri = ''[, $protocol = null[, $altConfig = null]]]) :param array|string $uri: URI string or array of URI segments. - :param string $protocol: Protocol, e.g., 'http' or 'https'. If empty string '' is set, a protocol-relative link is returned. + :param string $protocol: Protocol, e.g., ``'http'`` or ``'https'``. If empty string ``''`` is set, a protocol-relative link is returned. :param \\Config\\App $altConfig: Alternate configuration to use. :returns: Site URL :rtype: string @@ -57,7 +57,7 @@ The following functions are available: .. php:function:: base_url([$uri = ''[, $protocol = null]]) :param array|string $uri: URI string or array of URI segments. - :param string $protocol: Protocol, e.g., 'http' or 'https'. If empty string '' is set, a protocol-relative link is returned. + :param string $protocol: Protocol, e.g., ``'http'`` or ``'https'``. If empty string ``''`` is set, a protocol-relative link is returned. :returns: Base URL :rtype: string @@ -292,7 +292,7 @@ The following functions are available: .. php:function:: auto_link($str[, $type = 'both'[, $popup = false]]) :param string $str: Input string - :param string $type: Link type ('email', 'url' or 'both') + :param string $type: Link type (``'email'``, ``'url'`` or ``'both'``) :param bool $popup: Whether to create popup links :returns: Linkified string :rtype: string From b5b2e57fdf7e5a86220690cb5f0732fa506d75a0 Mon Sep 17 00:00:00 2001 From: kenjis Date: Sat, 7 Sep 2024 17:59:37 +0900 Subject: [PATCH 003/108] docs: add changelog and upgrade for v4.5.6 --- user_guide_src/source/changelogs/index.rst | 1 + user_guide_src/source/changelogs/v4.5.6.rst | 35 ++++++++++++ .../source/installation/upgrade_456.rst | 55 +++++++++++++++++++ .../source/installation/upgrading.rst | 1 + 4 files changed, 92 insertions(+) create mode 100644 user_guide_src/source/changelogs/v4.5.6.rst create mode 100644 user_guide_src/source/installation/upgrade_456.rst diff --git a/user_guide_src/source/changelogs/index.rst b/user_guide_src/source/changelogs/index.rst index 702a590e4fbb..a4d102ada233 100644 --- a/user_guide_src/source/changelogs/index.rst +++ b/user_guide_src/source/changelogs/index.rst @@ -12,6 +12,7 @@ See all the changes. .. toctree:: :titlesonly: + v4.5.6 v4.5.5 v4.5.4 v4.5.3 diff --git a/user_guide_src/source/changelogs/v4.5.6.rst b/user_guide_src/source/changelogs/v4.5.6.rst new file mode 100644 index 000000000000..33e3e5a1a0ab --- /dev/null +++ b/user_guide_src/source/changelogs/v4.5.6.rst @@ -0,0 +1,35 @@ +############# +Version 4.5.6 +############# + +Release Date: Unreleased + +**4.5.6 release of CodeIgniter4** + +.. contents:: + :local: + :depth: 3 + +******** +BREAKING +******** + +*************** +Message Changes +*************** + +******* +Changes +******* + +************ +Deprecations +************ + +********** +Bugs Fixed +********** + +See the repo's +`CHANGELOG.md `_ +for a complete list of bugs fixed. diff --git a/user_guide_src/source/installation/upgrade_456.rst b/user_guide_src/source/installation/upgrade_456.rst new file mode 100644 index 000000000000..d0764f3ff6ee --- /dev/null +++ b/user_guide_src/source/installation/upgrade_456.rst @@ -0,0 +1,55 @@ +############################# +Upgrading from 4.5.5 to 4.5.6 +############################# + +Please refer to the upgrade instructions corresponding to your installation method. + +- :ref:`Composer Installation App Starter Upgrading ` +- :ref:`Composer Installation Adding CodeIgniter4 to an Existing Project Upgrading ` +- :ref:`Manual Installation Upgrading ` + +.. contents:: + :local: + :depth: 2 + +********************** +Mandatory File Changes +********************** + +**************** +Breaking Changes +**************** + +********************* +Breaking Enhancements +********************* + +************* +Project Files +************* + +Some files in the **project space** (root, app, public, writable) received updates. Due to +these files being outside of the **system** scope they will not be changed without your intervention. + +.. note:: There are some third-party CodeIgniter modules available to assist + with merging changes to the project space: + `Explore on Packagist `_. + +Content Changes +=============== + +The following files received significant changes (including deprecations or visual adjustments) +and it is recommended that you merge the updated versions with your application: + +Config +------ + +- @TODO + +All Changes +=========== + +This is a list of all files in the **project space** that received changes; +many will be simple comments or formatting that have no effect on the runtime: + +- @TODO diff --git a/user_guide_src/source/installation/upgrading.rst b/user_guide_src/source/installation/upgrading.rst index 39f262288813..0b489abb9101 100644 --- a/user_guide_src/source/installation/upgrading.rst +++ b/user_guide_src/source/installation/upgrading.rst @@ -16,6 +16,7 @@ See also :doc:`./backward_compatibility_notes`. backward_compatibility_notes + upgrade_456 upgrade_455 upgrade_454 upgrade_453 From ee9ae5fbb34c411fb765153f1877a0348ac51063 Mon Sep 17 00:00:00 2001 From: kenjis Date: Sat, 7 Sep 2024 18:09:27 +0900 Subject: [PATCH 004/108] docs: add note --- admin/RELEASE.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/admin/RELEASE.md b/admin/RELEASE.md index 4f199a821177..6e0b812b25a7 100644 --- a/admin/RELEASE.md +++ b/admin/RELEASE.md @@ -12,6 +12,9 @@ - `4.y`: The next minor version. (e.g., `4.6`) - `4.z`: The next next minor version. (e.g., `4.7`) +> [!NOTE] +> Copy this file, and replace the versions above with the actual versions. + ## Merge `develop` branch into next minor version branch `4.y` Before starting release process, if there are commits in `develop` branch that From 2492078509c7738818a2be05319f181ff58cf30b Mon Sep 17 00:00:00 2001 From: kenjis Date: Sat, 7 Sep 2024 18:09:59 +0900 Subject: [PATCH 005/108] docs: move item --- admin/RELEASE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/admin/RELEASE.md b/admin/RELEASE.md index 6e0b812b25a7..61667d612178 100644 --- a/admin/RELEASE.md +++ b/admin/RELEASE.md @@ -87,7 +87,6 @@ Work off direct clones of the repos so the release branches persist for a time. cd CodeIgniter4 git diff --name-status origin/master admin/ ``` -* [ ] Merge any Security Advisory PRs in private forks ## Process @@ -95,6 +94,7 @@ Work off direct clones of the repos so the release branches persist for a time. > been included with their PR, so this process assumes you will not be > generating much new content. +* [ ] Merge any Security Advisory PRs in private forks * [ ] Replace **CHANGELOG.md** with the new version generated above * [ ] Update **user_guide_src/source/changelogs/v4.x.x.rst** * Remove the section titles that have no items From cb4ba98ce6c294662e9bcc8d6c27f3ac15288f8b Mon Sep 17 00:00:00 2001 From: kenjis Date: Sat, 7 Sep 2024 18:10:37 +0900 Subject: [PATCH 006/108] docs: move section --- admin/RELEASE.md | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/admin/RELEASE.md b/admin/RELEASE.md index 61667d612178..30b1f77b7362 100644 --- a/admin/RELEASE.md +++ b/admin/RELEASE.md @@ -38,6 +38,26 @@ If you release a new minor version. "Branch protection rules" to the next minor version. E.g. `4.5` → `4.6` * [ ] Delete the merged `4.y` branch (This closes all PRs to the branch) +## Preparation + +Work off direct clones of the repos so the release branches persist for a time. + +* [ ] Clone both **codeigniter4/CodeIgniter4** and **codeigniter4/userguide** and + resolve any necessary PRs + ```console + rm -rf CodeIgniter4.bk userguide.bk + mv CodeIgniter4 CodeIgniter4.bk + mv userguide userguide.bk + git clone git@github.com:codeigniter4/CodeIgniter4.git + git clone git@github.com:codeigniter4/userguide.git + ``` +* [ ] Vet the **admin/** folders for any removed hidden files (Action deploy scripts + *do not remove these*) + ```console + cd CodeIgniter4 + git diff --name-status origin/master admin/ + ``` + ## Changelog When generating the changelog each Pull Request to be included must have one of @@ -68,26 +88,6 @@ the changelog. Copy the resulting content into **CHANGELOG.md** and adjust the format to match the existing content. -## Preparation - -Work off direct clones of the repos so the release branches persist for a time. - -* [ ] Clone both **codeigniter4/CodeIgniter4** and **codeigniter4/userguide** and - resolve any necessary PRs - ```console - rm -rf CodeIgniter4.bk userguide.bk - mv CodeIgniter4 CodeIgniter4.bk - mv userguide userguide.bk - git clone git@github.com:codeigniter4/CodeIgniter4.git - git clone git@github.com:codeigniter4/userguide.git - ``` -* [ ] Vet the **admin/** folders for any removed hidden files (Action deploy scripts - *do not remove these*) - ```console - cd CodeIgniter4 - git diff --name-status origin/master admin/ - ``` - ## Process > **Note** Most changes that need noting in the User Guide and docs should have From d7bedff4e71c0b4d76888238b13ae369789ecd37 Mon Sep 17 00:00:00 2001 From: kenjis Date: Sat, 7 Sep 2024 18:10:53 +0900 Subject: [PATCH 007/108] docs: use GitHub markdown note format --- admin/RELEASE.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/admin/RELEASE.md b/admin/RELEASE.md index 30b1f77b7362..9ed91e55c183 100644 --- a/admin/RELEASE.md +++ b/admin/RELEASE.md @@ -90,7 +90,8 @@ the existing content. ## Process -> **Note** Most changes that need noting in the User Guide and docs should have +> [!NOTE] +> Most changes that need noting in the User Guide and docs should have > been included with their PR, so this process assumes you will not be > generating much new content. From 22cf15ecf3a306917ef18518aee7f0fc13eddb67 Mon Sep 17 00:00:00 2001 From: kenjis Date: Sun, 8 Sep 2024 11:07:39 +0900 Subject: [PATCH 008/108] docs: improve description for Migration File Names --- user_guide_src/source/dbmgmt/migration.rst | 23 +++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/user_guide_src/source/dbmgmt/migration.rst b/user_guide_src/source/dbmgmt/migration.rst index dec16c5037ff..c0a565381f5a 100644 --- a/user_guide_src/source/dbmgmt/migration.rst +++ b/user_guide_src/source/dbmgmt/migration.rst @@ -22,19 +22,28 @@ include migrations from all namespaces. Migration File Names ******************** -Each Migration is run in numeric order forward or backwards depending on the -method taken. Each migration is numbered using the timestamp when the migration -was created, in **YYYY-MM-DD-HHIISS** format (e.g., **2012-10-31-100537**). This -helps prevent numbering conflicts when working in a team environment. +A migration file name is made up of a timestamp prefix, an underscore (``_``), +and a descriptive name (classname). + +* 2024-09-08-013653_AddBlogTable.php + +Each migration is numbered using the timestamp (**2024-09-08-013653**) when the +migration was created, in **YYYY-MM-DD-HHIISS** format. -Prefix your migration files with the migration number followed by an underscore -and a descriptive name for the migration. The year, month, and date can be separated -from each other by dashes, underscores, or not at all. For example: +The descriptive name (**AddBlogTable**) for the migration is a classname in PHP. +So you must name a valid classname. + +The year, month, date, and time in a prefix can be separated from each other by +dashes (``-``), underscores (``_``), or not at all. For example: * 2012-10-31-100538_AlterBlogTrackViews.php * 2012_10_31_100539_AlterBlogAddTranslations.php * 20121031100537_AddBlog.php +Each Migration is run in numeric order forward or backwards depending on the +method taken. This helps prevent numbering conflicts when working in a team +environment. + ****************** Create a Migration ****************** From 71137925dced6e3d3da5849d29481e8e762ca358 Mon Sep 17 00:00:00 2001 From: kenjis Date: Sun, 8 Sep 2024 11:07:50 +0900 Subject: [PATCH 009/108] docs: add link to section --- user_guide_src/source/dbmgmt/migration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_guide_src/source/dbmgmt/migration.rst b/user_guide_src/source/dbmgmt/migration.rst index c0a565381f5a..278b6e9ba904 100644 --- a/user_guide_src/source/dbmgmt/migration.rst +++ b/user_guide_src/source/dbmgmt/migration.rst @@ -58,7 +58,7 @@ The database connection and the database Forge class are both available to you t ``$this->db`` and ``$this->forge``, respectively. Alternatively, you can use a command-line call to generate a skeleton migration file. -See **make:migration** in :ref:`command-line-tools` for more details. +See `make:migration`_ in :ref:`command-line-tools` for more details. .. note:: Since the migration class is a PHP class, the classname must be unique in every migration file. From e53c32cd714a70e301d0084d2c5b864cceb0092b Mon Sep 17 00:00:00 2001 From: kenjis Date: Sun, 8 Sep 2024 17:38:09 +0900 Subject: [PATCH 010/108] docs: fix typo --- user_guide_src/source/dbmgmt/migration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_guide_src/source/dbmgmt/migration.rst b/user_guide_src/source/dbmgmt/migration.rst index 278b6e9ba904..5a4bc0852cee 100644 --- a/user_guide_src/source/dbmgmt/migration.rst +++ b/user_guide_src/source/dbmgmt/migration.rst @@ -33,7 +33,7 @@ migration was created, in **YYYY-MM-DD-HHIISS** format. The descriptive name (**AddBlogTable**) for the migration is a classname in PHP. So you must name a valid classname. -The year, month, date, and time in a prefix can be separated from each other by +The year, month, day, and time in a prefix can be separated from each other by dashes (``-``), underscores (``_``), or not at all. For example: * 2012-10-31-100538_AlterBlogTrackViews.php From 791fe2feb169b8d45839c44f66fd45c38a782bd9 Mon Sep 17 00:00:00 2001 From: kenjis Date: Sun, 8 Sep 2024 18:15:51 +0900 Subject: [PATCH 011/108] fix: auto_link() converts invalid string like "://codeigniter.com" The scheme is missing, so it is not a valid URL. --- system/Helpers/url_helper.php | 2 +- tests/system/Helpers/URLHelper/MiscUrlTest.php | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/system/Helpers/url_helper.php b/system/Helpers/url_helper.php index d68fea2aad7d..6c11233ff77b 100644 --- a/system/Helpers/url_helper.php +++ b/system/Helpers/url_helper.php @@ -351,7 +351,7 @@ function safe_mailto(string $email, string $title = '', $attributes = ''): strin function auto_link(string $str, string $type = 'both', bool $popup = false): string { // Find and replace any URLs. - if ($type !== 'email' && preg_match_all('#(\w*://|www\.)[a-z0-9]+(-+[a-z0-9]+)*(\.[a-z0-9]+(-+[a-z0-9]+)*)+(/([^\s()<>;]+\w)?/?)?#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { + if ($type !== 'email' && preg_match_all('#([a-z][a-z0-9+\-.]*://|www\.)[a-z0-9]+(-+[a-z0-9]+)*(\.[a-z0-9]+(-+[a-z0-9]+)*)+(/([^\s()<>;]+\w)?/?)?#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { // Set our target HTML if using popup links. $target = ($popup) ? ' target="_blank"' : ''; diff --git a/tests/system/Helpers/URLHelper/MiscUrlTest.php b/tests/system/Helpers/URLHelper/MiscUrlTest.php index 219b5322dbb5..a006ec80c6ae 100644 --- a/tests/system/Helpers/URLHelper/MiscUrlTest.php +++ b/tests/system/Helpers/URLHelper/MiscUrlTest.php @@ -523,7 +523,7 @@ public static function provideAutoLinkUrl(): iterable ], 'test06' => [ 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', - 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', + 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', ], 'test07' => [ 'Visit example.com or email foo@bar.com', @@ -623,7 +623,7 @@ public static function provideAutolinkBoth(): iterable ], 'test06' => [ 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', - 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', + 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', ], 'test07' => [ 'Visit example.com or email foo@bar.com', @@ -675,7 +675,7 @@ public static function provideAutoLinkPopup(): iterable ], 'test06' => [ 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', - 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', + 'This one: ://codeigniter.com must not break this one: http://codeigniter.com', ], 'test07' => [ 'Visit example.com or email foo@bar.com', From 94fe31fc64c885a5e658cc5e7f9275356796f86f Mon Sep 17 00:00:00 2001 From: kenjis Date: Sun, 8 Sep 2024 18:18:50 +0900 Subject: [PATCH 012/108] refactor: break long lines --- system/Helpers/url_helper.php | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/system/Helpers/url_helper.php b/system/Helpers/url_helper.php index 6c11233ff77b..fcfce09f5697 100644 --- a/system/Helpers/url_helper.php +++ b/system/Helpers/url_helper.php @@ -351,7 +351,15 @@ function safe_mailto(string $email, string $title = '', $attributes = ''): strin function auto_link(string $str, string $type = 'both', bool $popup = false): string { // Find and replace any URLs. - if ($type !== 'email' && preg_match_all('#([a-z][a-z0-9+\-.]*://|www\.)[a-z0-9]+(-+[a-z0-9]+)*(\.[a-z0-9]+(-+[a-z0-9]+)*)+(/([^\s()<>;]+\w)?/?)?#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { + if ( + $type !== 'email' + && preg_match_all( + '#([a-z][a-z0-9+\-.]*://|www\.)[a-z0-9]+(-+[a-z0-9]+)*(\.[a-z0-9]+(-+[a-z0-9]+)*)+(/([^\s()<>;]+\w)?/?)?#i', + $str, + $matches, + PREG_OFFSET_CAPTURE | PREG_SET_ORDER + ) + ) { // Set our target HTML if using popup links. $target = ($popup) ? ' target="_blank"' : ''; @@ -370,7 +378,15 @@ function auto_link(string $str, string $type = 'both', bool $popup = false): str } // Find and replace any emails. - if ($type !== 'url' && preg_match_all('#([\w\.\-\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', $str, $matches, PREG_OFFSET_CAPTURE)) { + if ( + $type !== 'url' + && preg_match_all( + '#([\w\.\-\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', + $str, + $matches, + PREG_OFFSET_CAPTURE + ) + ) { foreach (array_reverse($matches[0]) as $match) { if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== false) { $str = substr_replace($str, safe_mailto($match[0]), $match[1], strlen($match[0])); From 377679065f44427cfffb6ed92165a8bf4133f501 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Sep 2024 15:43:31 +0000 Subject: [PATCH 013/108] chore(deps-dev): update rector/rector requirement from 1.2.4 to 1.2.5 Updates the requirements on [rector/rector](https://github.com/rectorphp/rector) to permit the latest version. - [Release notes](https://github.com/rectorphp/rector/releases) - [Commits](https://github.com/rectorphp/rector/compare/1.2.4...1.2.5) --- updated-dependencies: - dependency-name: rector/rector dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c2ed6374b550..5f85a575b3b8 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": "1.2.4" + "rector/rector": "1.2.5" }, "replace": { "codeigniter4/framework": "self.version" From 0a9835b40d230215c480ccda771de2de9a1bdbfa Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Tue, 10 Sep 2024 03:58:56 +0700 Subject: [PATCH 014/108] Fix phpstan --- system/Cache/Handlers/RedisHandler.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index 22f4e43540dd..6cd43506bdb5 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -108,7 +108,7 @@ public function initialize() public function get(string $key) { $key = static::validateKey($key, $this->prefix); - $data = $this->redis->hMGet($key, ['__ci_type', '__ci_value']); + $data = $this->redis->hMget($key, ['__ci_type', '__ci_value']); if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) { return null; @@ -147,7 +147,7 @@ public function save(string $key, $value, int $ttl = 60) return false; } - if (! $this->redis->hMSet($key, ['__ci_type' => $dataType, '__ci_value' => $value])) { + if (! $this->redis->hMset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) { return false; } From 45a002fbc1f3d750f7f81f5fb04af31baee1a777 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Tue, 10 Sep 2024 05:56:06 +0700 Subject: [PATCH 015/108] refactor: enable TypedPropertyFromAssignsRector --- rector.php | 2 ++ system/Config/Factories.php | 8 ++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/rector.php b/rector.php index e16de7bae441..14a079e0ab04 100644 --- a/rector.php +++ b/rector.php @@ -55,6 +55,7 @@ use Rector\TypeDeclaration\Rector\Closure\AddClosureVoidReturnTypeWhereNoReturnRector; use Rector\TypeDeclaration\Rector\Empty_\EmptyOnNullableObjectToInstanceOfRector; use Rector\TypeDeclaration\Rector\Function_\AddFunctionVoidReturnTypeWhereNoReturnRector; +use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector; use Rector\TypeDeclaration\Rector\StmtsAwareInterface\DeclareStrictTypesRector; use Utils\Rector\PassStrictParameterToFunctionParameterRector; use Utils\Rector\RemoveErrorSuppressInTryCatchStmtsRector; @@ -215,6 +216,7 @@ AddClosureVoidReturnTypeWhereNoReturnRector::class, AddFunctionVoidReturnTypeWhereNoReturnRector::class, AddMethodCallBasedStrictParamTypeRector::class, + TypedPropertyFromAssignsRector::class, ]) ->withConfiguredRule(StringClassNameToClassConstantRector::class, [ // keep '\\' prefix string on string '\Foo\Bar' diff --git a/system/Config/Factories.php b/system/Config/Factories.php index d98664a24a7b..be66005a8adf 100644 --- a/system/Config/Factories.php +++ b/system/Config/Factories.php @@ -37,7 +37,7 @@ final class Factories * * @var array> */ - private static $options = []; + private static array $options = []; /** * Explicit options for the Config @@ -65,7 +65,7 @@ final class Factories * * @var array> */ - private static $aliases = []; + private static array $aliases = []; /** * Store for instances of any component that @@ -78,7 +78,7 @@ final class Factories * * @var array> */ - private static $instances = []; + private static array $instances = []; /** * Whether the component instances are updated? @@ -87,7 +87,7 @@ final class Factories * * @internal For caching only */ - private static $updated = []; + private static array $updated = []; /** * Define the class to load. You can *override* the concrete class. From fe65154a4f85883fb558564cb38d412974714775 Mon Sep 17 00:00:00 2001 From: Denny Septian Panggabean Date: Tue, 10 Sep 2024 10:38:56 +0700 Subject: [PATCH 016/108] docs: broken link htmx ajax-header --- user_guide_src/source/general/ajax.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_guide_src/source/general/ajax.rst b/user_guide_src/source/general/ajax.rst index 967e2c280c59..ddc276fdf39a 100644 --- a/user_guide_src/source/general/ajax.rst +++ b/user_guide_src/source/general/ajax.rst @@ -56,7 +56,7 @@ React htmx ==== -You can use `ajax-header `_ extension. +You can use `ajax-header `_ extension. .. code-block:: html From 3f29f2883a279f2d086300e7ddcf89e2b6fe9477 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Tue, 10 Sep 2024 16:18:25 +0700 Subject: [PATCH 017/108] refactor: enable ClosureReturnTypeRector --- rector.php | 2 ++ system/Database/OCI8/Builder.php | 6 +++--- system/Database/OCI8/PreparedQuery.php | 2 +- system/Database/Postgre/Builder.php | 6 +++--- system/Database/Postgre/PreparedQuery.php | 2 +- system/Database/SQLSRV/Builder.php | 4 ++-- system/Database/SQLite3/Builder.php | 2 +- system/Debug/Toolbar/Collectors/Database.php | 2 +- system/Events/Events.php | 2 +- system/HTTP/ContentSecurityPolicy.php | 2 +- system/HTTP/Negotiate.php | 2 +- system/Helpers/Array/ArrayHelper.php | 2 +- system/Router/Router.php | 2 +- system/View/Parser.php | 2 +- tests/system/Commands/Utilities/NamespacesTest.php | 2 +- tests/system/DataConverter/DataConverterTest.php | 4 ++-- tests/system/Debug/TimerTest.php | 2 +- tests/system/Events/EventsTest.php | 6 +++--- tests/system/Test/FeatureTestTraitTest.php | 2 +- tests/system/Validation/ValidationTest.php | 2 +- tests/system/View/ParserTest.php | 6 +++--- 21 files changed, 32 insertions(+), 30 deletions(-) diff --git a/rector.php b/rector.php index 14a079e0ab04..8fd3ab275345 100644 --- a/rector.php +++ b/rector.php @@ -53,6 +53,7 @@ use Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector; use Rector\TypeDeclaration\Rector\ClassMethod\ReturnNeverTypeRector; use Rector\TypeDeclaration\Rector\Closure\AddClosureVoidReturnTypeWhereNoReturnRector; +use Rector\TypeDeclaration\Rector\Closure\ClosureReturnTypeRector; use Rector\TypeDeclaration\Rector\Empty_\EmptyOnNullableObjectToInstanceOfRector; use Rector\TypeDeclaration\Rector\Function_\AddFunctionVoidReturnTypeWhereNoReturnRector; use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector; @@ -217,6 +218,7 @@ AddFunctionVoidReturnTypeWhereNoReturnRector::class, AddMethodCallBasedStrictParamTypeRector::class, TypedPropertyFromAssignsRector::class, + ClosureReturnTypeRector::class, ]) ->withConfiguredRule(StringClassNameToClassConstantRector::class, [ // keep '\\' prefix string on string '\Foo\Bar' diff --git a/system/Database/OCI8/Builder.php b/system/Database/OCI8/Builder.php index 4423a5243a81..24a6bb53b07c 100644 --- a/system/Database/OCI8/Builder.php +++ b/system/Database/OCI8/Builder.php @@ -109,12 +109,12 @@ protected function _replace(string $table, array $keys, array $values): string { $fieldNames = array_map(static fn ($columnName) => trim($columnName, '"'), $keys); - $uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames) { + $uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool { $hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields); return ($index->type === 'PRIMARY') && $hasAllFields; }); - $replaceableFields = array_filter($keys, static function ($columnName) use ($uniqueIndexes) { + $replaceableFields = array_filter($keys, static function ($columnName) use ($uniqueIndexes): bool { foreach ($uniqueIndexes as $index) { if (in_array(trim($columnName, '"'), $index->fields, true)) { return false; @@ -344,7 +344,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri if (empty($constraints)) { $fieldNames = array_map(static fn ($columnName) => trim($columnName, '"'), $keys); - $uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames) { + $uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool { $hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields); return ($index->type === 'PRIMARY' || $index->type === 'UNIQUE') && $hasAllFields; diff --git a/system/Database/OCI8/PreparedQuery.php b/system/Database/OCI8/PreparedQuery.php index c267f8061377..feffc3be50b5 100644 --- a/system/Database/OCI8/PreparedQuery.php +++ b/system/Database/OCI8/PreparedQuery.php @@ -113,7 +113,7 @@ public function parameterize(string $sql): string // Track our current value $count = 0; - return preg_replace_callback('/\?/', static function ($matches) use (&$count) { + return preg_replace_callback('/\?/', static function ($matches) use (&$count): string { return ':' . ($count++); }, $sql); } diff --git a/system/Database/Postgre/Builder.php b/system/Database/Postgre/Builder.php index 0d2dce0957ae..12845a0e4f54 100644 --- a/system/Database/Postgre/Builder.php +++ b/system/Database/Postgre/Builder.php @@ -368,7 +368,7 @@ protected function _updateBatch(string $table, array $keys, array $values): stri $sql .= 'WHERE ' . implode( ' AND ', array_map( - static function ($key, $value) use ($table, $alias, $that) { + static function ($key, $value) use ($table, $alias, $that): string|RawSql { if ($value instanceof RawSql && is_string($key)) { return $table . '.' . $key . ' = ' . $value; } @@ -463,7 +463,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri $constraints = $this->QBOptions['constraints'] ?? []; if (empty($constraints)) { - $allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames) { + $allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool { $hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields); return ($index->type === 'UNIQUE' || $index->type === 'PRIMARY') && $hasAllFields; @@ -575,7 +575,7 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri $sql .= 'WHERE ' . implode( ' AND ', array_map( - static function ($key, $value) use ($table, $alias, $that) { + static function ($key, $value) use ($table, $alias, $that): RawSql|string { if ($value instanceof RawSql) { return $value; } diff --git a/system/Database/Postgre/PreparedQuery.php b/system/Database/Postgre/PreparedQuery.php index fbea6ac14f3a..33a6c8044c7d 100644 --- a/system/Database/Postgre/PreparedQuery.php +++ b/system/Database/Postgre/PreparedQuery.php @@ -119,7 +119,7 @@ public function parameterize(string $sql): string // Track our current value $count = 0; - return preg_replace_callback('/\?/', static function () use (&$count) { + return preg_replace_callback('/\?/', static function () use (&$count): string { $count++; return "\${$count}"; diff --git a/system/Database/SQLSRV/Builder.php b/system/Database/SQLSRV/Builder.php index a6d0b8e85ccd..fcc0b170084f 100644 --- a/system/Database/SQLSRV/Builder.php +++ b/system/Database/SQLSRV/Builder.php @@ -699,7 +699,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri if (empty($constraints)) { $tableIndexes = $this->db->getIndexData($table); - $uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames) { + $uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames): bool { $hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields); return $index->type === 'PRIMARY' && $hasAllFields; @@ -707,7 +707,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri // if no primary found then look for unique - since indexes have no order if ($uniqueIndexes === []) { - $uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames) { + $uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames): bool { $hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields); return $index->type === 'UNIQUE' && $hasAllFields; diff --git a/system/Database/SQLite3/Builder.php b/system/Database/SQLite3/Builder.php index a59270bbc0de..15fc2529aa0d 100644 --- a/system/Database/SQLite3/Builder.php +++ b/system/Database/SQLite3/Builder.php @@ -145,7 +145,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri if (empty($constraints)) { $fieldNames = array_map(static fn ($columnName) => trim($columnName, '`'), $keys); - $allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames) { + $allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool { $hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields); return ($index->type === 'PRIMARY' || $index->type === 'UNIQUE') && $hasAllFields; diff --git a/system/Debug/Toolbar/Collectors/Database.php b/system/Debug/Toolbar/Collectors/Database.php index ee9f829b05b8..1a923a35516b 100644 --- a/system/Debug/Toolbar/Collectors/Database.php +++ b/system/Debug/Toolbar/Collectors/Database.php @@ -148,7 +148,7 @@ protected function formatTimelineData(): array public function display(): array { $data = []; - $data['queries'] = array_map(static function (array $query) { + $data['queries'] = array_map(static function (array $query): array { $isDuplicate = $query['duplicate'] === true; $firstNonSystemLine = ''; diff --git a/system/Events/Events.php b/system/Events/Events.php index a06bd7903e69..61b7f5c3b457 100644 --- a/system/Events/Events.php +++ b/system/Events/Events.php @@ -84,7 +84,7 @@ public static function initialize() $files = service('locator')->search('Config/Events.php'); } - $files = array_filter(array_map(static function (string $file) { + $files = array_filter(array_map(static function (string $file): string|false { if (is_file($file)) { return realpath($file) ?: $file; } diff --git a/system/HTTP/ContentSecurityPolicy.php b/system/HTTP/ContentSecurityPolicy.php index 7582bc467733..d0dda0ad5752 100644 --- a/system/HTTP/ContentSecurityPolicy.php +++ b/system/HTTP/ContentSecurityPolicy.php @@ -713,7 +713,7 @@ protected function generateNonces(ResponseInterface $response) $pattern = '/(' . preg_quote($this->styleNonceTag, '/') . '|' . preg_quote($this->scriptNonceTag, '/') . ')/'; - $body = preg_replace_callback($pattern, function ($match) { + $body = preg_replace_callback($pattern, function ($match): string { $nonce = $match[0] === $this->styleNonceTag ? $this->getStyleNonce() : $this->getScriptNonce(); return "nonce=\"{$nonce}\""; diff --git a/system/HTTP/Negotiate.php b/system/HTTP/Negotiate.php index 67a03a38014d..4f218347738d 100644 --- a/system/HTTP/Negotiate.php +++ b/system/HTTP/Negotiate.php @@ -233,7 +233,7 @@ public function parseHeader(string $header): array } // Sort to get the highest results first - usort($results, static function ($a, $b) { + usort($results, static function ($a, $b): int { if ($a['q'] === $b['q']) { $aAst = substr_count($a['value'], '*'); $bAst = substr_count($b['value'], '*'); diff --git a/system/Helpers/Array/ArrayHelper.php b/system/Helpers/Array/ArrayHelper.php index 76b8e8aedfbe..4bbd34427fa1 100644 --- a/system/Helpers/Array/ArrayHelper.php +++ b/system/Helpers/Array/ArrayHelper.php @@ -307,7 +307,7 @@ public static function recursiveCount(array $array, int $counter = 0): int */ public static function sortValuesByNatural(array &$array, $sortByIndex = null): bool { - return usort($array, static function ($currentValue, $nextValue) use ($sortByIndex) { + return usort($array, static function ($currentValue, $nextValue) use ($sortByIndex): int { if ($sortByIndex !== null) { return strnatcmp((string) $currentValue[$sortByIndex], (string) $nextValue[$sortByIndex]); } diff --git a/system/Router/Router.php b/system/Router/Router.php index d60313f6c032..2bb050de30ae 100644 --- a/system/Router/Router.php +++ b/system/Router/Router.php @@ -433,7 +433,7 @@ protected function checkRoutes(string $uri): bool // Is this route supposed to redirect to another? if ($this->collection->isRedirect($routeKey)) { // replacing matched route groups with references: post/([0-9]+) -> post/$1 - $redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function () { + $redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function (): string { static $i = 1; return '$' . $i++; diff --git a/system/View/Parser.php b/system/View/Parser.php index bbeb00f757c0..6600b0178369 100644 --- a/system/View/Parser.php +++ b/system/View/Parser.php @@ -534,7 +534,7 @@ protected function replaceSingle($pattern, $content, $template, bool $escape = f $content = (string) $content; // Replace the content in the template - return preg_replace_callback($pattern, function ($matches) use ($content, $escape) { + return preg_replace_callback($pattern, function ($matches) use ($content, $escape): string { // Check for {! !} syntax to not escape this one. if ( str_starts_with($matches[0], $this->leftDelimiter . '!') diff --git a/tests/system/Commands/Utilities/NamespacesTest.php b/tests/system/Commands/Utilities/NamespacesTest.php index c32d9280aef4..ffdfa0ddcf8d 100644 --- a/tests/system/Commands/Utilities/NamespacesTest.php +++ b/tests/system/Commands/Utilities/NamespacesTest.php @@ -42,7 +42,7 @@ protected function tearDown(): void */ protected function getBuffer() { - return preg_replace_callback('/(\|\s*[^|]+\s*\|\s*)(.*?)(\s*\|\s*[^|]+\s*\|)/', static function (array $matches) { + return preg_replace_callback('/(\|\s*[^|]+\s*\|\s*)(.*?)(\s*\|\s*[^|]+\s*\|)/', static function (array $matches): string { $matches[2] = str_replace(DIRECTORY_SEPARATOR, '/', $matches[2]); return $matches[1] . $matches[2] . $matches[3]; diff --git a/tests/system/DataConverter/DataConverterTest.php b/tests/system/DataConverter/DataConverterTest.php index 6592f4d801c6..c8975fc114fd 100644 --- a/tests/system/DataConverter/DataConverterTest.php +++ b/tests/system/DataConverter/DataConverterTest.php @@ -570,7 +570,7 @@ public function testReconstructObjectWithClosure(): void 'created_at' => 'datetime', 'updated_at' => 'datetime', ]; - $reconstructor = static function ($array) { + $reconstructor = static function ($array): User { $user = new User(); $user->fill($array); @@ -667,7 +667,7 @@ public function testExtractWithClosure(): void 'created_at' => 'datetime', 'updated_at' => 'datetime', ]; - $extractor = static function ($obj) { + $extractor = static function ($obj): array { $array['id'] = $obj->id; $array['name'] = $obj->name; $array['created_at'] = $obj->created_at; diff --git a/tests/system/Debug/TimerTest.php b/tests/system/Debug/TimerTest.php index eb3cb243b398..09bf0d535bee 100644 --- a/tests/system/Debug/TimerTest.php +++ b/tests/system/Debug/TimerTest.php @@ -144,7 +144,7 @@ public function testRecordFunctionNoReturn(): void public function testRecordFunctionWithReturn(): void { $timer = new Timer(); - $returnValue = $timer->record('longjohn', static function () { + $returnValue = $timer->record('longjohn', static function (): string { usleep(100000); return 'test'; diff --git a/tests/system/Events/EventsTest.php b/tests/system/Events/EventsTest.php index e761c7dff958..db975aaa1825 100644 --- a/tests/system/Events/EventsTest.php +++ b/tests/system/Events/EventsTest.php @@ -121,7 +121,7 @@ public function testCancelEvent(): void // This should cancel the flow of events, and leave // $result = 1. - Events::on('foo', static function ($arg) use (&$result) { + Events::on('foo', static function ($arg) use (&$result): bool { $result = 1; return false; @@ -138,14 +138,14 @@ public function testPriority(): void { $result = 0; - Events::on('foo', static function () use (&$result) { + Events::on('foo', static function () use (&$result): bool { $result = 1; return false; }, EVENT_PRIORITY_NORMAL); // Since this has a higher priority, it will // run first. - Events::on('foo', static function () use (&$result) { + Events::on('foo', static function () use (&$result): bool { $result = 2; return false; diff --git a/tests/system/Test/FeatureTestTraitTest.php b/tests/system/Test/FeatureTestTraitTest.php index 4fd921d6e9a6..be3d590bd15a 100644 --- a/tests/system/Test/FeatureTestTraitTest.php +++ b/tests/system/Test/FeatureTestTraitTest.php @@ -152,7 +152,7 @@ public function testCallValidationTwice(): void [ 'POST', 'section/create', - static function () { + static function (): string { $validation = Services::validation(); $validation->setRule('title', 'title', 'required|min_length[3]'); diff --git a/tests/system/Validation/ValidationTest.php b/tests/system/Validation/ValidationTest.php index 00360f368e66..13991dc45916 100644 --- a/tests/system/Validation/ValidationTest.php +++ b/tests/system/Validation/ValidationTest.php @@ -311,7 +311,7 @@ public function testClosureRuleWithParamError(): void $this->validation->setRules([ 'foo' => [ 'required', - static function ($value, $data, &$error, $field) { + static function ($value, $data, &$error, $field): bool { if ($value !== 'abc') { $error = 'The ' . $field . ' value is not "abc"'; diff --git a/tests/system/View/ParserTest.php b/tests/system/View/ParserTest.php index 0cce9f722ebf..9a9f1fd8d0ac 100644 --- a/tests/system/View/ParserTest.php +++ b/tests/system/View/ParserTest.php @@ -806,7 +806,7 @@ public function testParserPluginClosure(): void public function testParserPluginParams(): void { - $this->parser->addPlugin('growth', static function ($str, array $params) { + $this->parser->addPlugin('growth', static function ($str, array $params): string { $step = $params['step'] ?? 1; $count = $params['count'] ?? 2; @@ -853,7 +853,7 @@ public function testParserSingleTagWithSingleParams(): void public function testParserSingleTagWithQuotedParams(): void { - $this->parser->addPlugin('count', static function (array $params = []) { + $this->parser->addPlugin('count', static function (array $params = []): string { $out = ''; foreach ($params as $index => $param) { @@ -870,7 +870,7 @@ public function testParserSingleTagWithQuotedParams(): void public function testParserSingleTagWithNamedParams(): void { - $this->parser->addPlugin('read_params', static function (array $params = []) { + $this->parser->addPlugin('read_params', static function (array $params = []): string { $out = ''; foreach ($params as $index => $param) { From 8ecbf0da09c1c23d3dcb3403545017b95b09a0d3 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Tue, 10 Sep 2024 16:31:47 +0700 Subject: [PATCH 018/108] Fix cs --- system/Events/Events.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/Events/Events.php b/system/Events/Events.php index 61b7f5c3b457..ad8efed62f9e 100644 --- a/system/Events/Events.php +++ b/system/Events/Events.php @@ -84,7 +84,7 @@ public static function initialize() $files = service('locator')->search('Config/Events.php'); } - $files = array_filter(array_map(static function (string $file): string|false { + $files = array_filter(array_map(static function (string $file): false|string { if (is_file($file)) { return realpath($file) ?: $file; } From 7d2d81c3e48f0f01d0393f845b02c1ae5217ef98 Mon Sep 17 00:00:00 2001 From: kenjis Date: Fri, 13 Sep 2024 17:20:29 +0900 Subject: [PATCH 019/108] docs: fix Project Files changes See https://forum.codeigniter.com/showthread.php?tid=91656&pid=421265#pid421265 --- user_guide_src/source/installation/upgrade_455.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/user_guide_src/source/installation/upgrade_455.rst b/user_guide_src/source/installation/upgrade_455.rst index 74d2bfbf7b2d..2f3694e4a2e4 100644 --- a/user_guide_src/source/installation/upgrade_455.rst +++ b/user_guide_src/source/installation/upgrade_455.rst @@ -32,7 +32,7 @@ and it is recommended that you merge the updated versions with your application: Config ------ -- composer.json +- preload.php All Changes =========== @@ -40,4 +40,4 @@ All Changes This is a list of all files in the **project space** that received changes; many will be simple comments or formatting that have no effect on the runtime: -- composer.json +- preload.php From d6850d479dcab33a16af392839db50202eb91a04 Mon Sep 17 00:00:00 2001 From: kenjis Date: Fri, 13 Sep 2024 17:44:54 +0900 Subject: [PATCH 020/108] chore: update psr/log to 3.0.2 --- system/ThirdParty/PSR/Log/LoggerInterface.php | 1 + 1 file changed, 1 insertion(+) diff --git a/system/ThirdParty/PSR/Log/LoggerInterface.php b/system/ThirdParty/PSR/Log/LoggerInterface.php index 8afabc90c820..cb4cf648b40f 100644 --- a/system/ThirdParty/PSR/Log/LoggerInterface.php +++ b/system/ThirdParty/PSR/Log/LoggerInterface.php @@ -89,6 +89,7 @@ public function debug(string|\Stringable $message, array $context = []): void; /** * Logs with an arbitrary level. * + * @param mixed $level * @param mixed[] $context * * @throws \Psr\Log\InvalidArgumentException From 60aa8e3f5b536dbc46568310c46005c6d0d1466c Mon Sep 17 00:00:00 2001 From: Denny Septian Panggabean Date: Mon, 9 Sep 2024 14:35:32 +0700 Subject: [PATCH 021/108] docs: improve Factories --- user_guide_src/source/concepts/factories.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/user_guide_src/source/concepts/factories.rst b/user_guide_src/source/concepts/factories.rst index f98fd1726e38..4520d3a8cb43 100644 --- a/user_guide_src/source/concepts/factories.rst +++ b/user_guide_src/source/concepts/factories.rst @@ -334,14 +334,14 @@ Set the following property to ``true`` in **app/Config/Optimize.php**:: public bool $configCacheEnabled = true; -Since v4.5.0, you can enable this with the ``spark optimize`` command. +Or you can enable this with the ``spark optimize`` command. .. note:: This property cannot be overridden by :ref:`environment variables `. .. note:: - Prior to v4.5.0, uncomment the following code in **public/index.php**:: + Prior to v4.4.x, uncomment the following code in **public/index.php**:: --- a/public/index.php +++ b/public/index.php From b1d044e3581990d5d5dbf61d8fdf970dd1e462fe Mon Sep 17 00:00:00 2001 From: Denny Septian Panggabean Date: Tue, 10 Sep 2024 09:02:02 +0700 Subject: [PATCH 022/108] fix: only v4.4.x config must set manually --- user_guide_src/source/concepts/factories.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_guide_src/source/concepts/factories.rst b/user_guide_src/source/concepts/factories.rst index 4520d3a8cb43..aaf7df459c6d 100644 --- a/user_guide_src/source/concepts/factories.rst +++ b/user_guide_src/source/concepts/factories.rst @@ -341,7 +341,7 @@ Or you can enable this with the ``spark optimize`` command. :ref:`environment variables `. .. note:: - Prior to v4.4.x, uncomment the following code in **public/index.php**:: + In v4.4.x, uncomment the following code in **public/index.php**:: --- a/public/index.php +++ b/public/index.php From a28b4bcd7cb66c33aaa16686c0053958dc076d53 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Dadashi Date: Tue, 1 Oct 2024 17:13:43 +0330 Subject: [PATCH 023/108] refactor: remove unnecessary `is_countable()` check in `getMethodParams` --- system/Router/RouteCollection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/Router/RouteCollection.php b/system/Router/RouteCollection.php index 8fba39dc03be..231711c48aac 100644 --- a/system/Router/RouteCollection.php +++ b/system/Router/RouteCollection.php @@ -1604,7 +1604,7 @@ private function processArrayCallableSyntax(string $from, array $to): string private function getMethodParams(string $from): string { preg_match_all('/\(.+?\)/', $from, $matches); - $count = is_countable($matches[0]) ? count($matches[0]) : 0; + $count = count($matches[0]); $params = ''; From 86ddfaaf57a4832aa734571aaf62c1aaea78491f Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Wed, 2 Oct 2024 17:20:22 +0700 Subject: [PATCH 024/108] refactor: add more readonly property definitions on AutoRouteCollector and SiteURI --- .../Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php | 2 +- system/HTTP/SiteURI.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php b/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php index 579969346637..4c705fd439b1 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 string $prefix = '' + private readonly string $prefix = '' ) { } diff --git a/system/HTTP/SiteURI.php b/system/HTTP/SiteURI.php index def61b65e17b..ab0cdd19c955 100644 --- a/system/HTTP/SiteURI.php +++ b/system/HTTP/SiteURI.php @@ -41,7 +41,7 @@ class SiteURI extends URI /** * The Index File. */ - private string $indexPage; + private readonly string $indexPage; /** * List of URI segments in baseURL and indexPage. From d385aa0f04b92b9b32ea310180e7296ce044e714 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Oct 2024 15:13:54 +0000 Subject: [PATCH 025/108] chore(deps-dev): update rector/rector requirement from 1.2.5 to 1.2.6 Updates the requirements on [rector/rector](https://github.com/rectorphp/rector) to permit the latest version. - [Release notes](https://github.com/rectorphp/rector/releases) - [Commits](https://github.com/rectorphp/rector/compare/1.2.5...1.2.6) --- updated-dependencies: - dependency-name: rector/rector dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 5f85a575b3b8..1caf40d2c832 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": "1.2.5" + "rector/rector": "1.2.6" }, "replace": { "codeigniter4/framework": "self.version" From 57e8be9ab90722e28f87149eb547a693486ace50 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Dadashi Date: Thu, 3 Oct 2024 20:35:43 +0330 Subject: [PATCH 026/108] refactor: allow `null` for `$key` property to handle buffer cleanup in SodiumHandler --- system/Encryption/Handlers/SodiumHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/Encryption/Handlers/SodiumHandler.php b/system/Encryption/Handlers/SodiumHandler.php index b6c74da76581..c74f2a5f0a48 100644 --- a/system/Encryption/Handlers/SodiumHandler.php +++ b/system/Encryption/Handlers/SodiumHandler.php @@ -26,7 +26,7 @@ class SodiumHandler extends BaseHandler /** * Starter key * - * @var string + * @var string|null Null is used for buffer cleanup. */ protected $key = ''; From 8f4b0dafaad2bd7c860fc3394decdf237b7c7626 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Oct 2024 15:30:18 +0000 Subject: [PATCH 027/108] chore(deps-dev): update rector/rector requirement from 1.2.6 to 1.2.7 Updates the requirements on [rector/rector](https://github.com/rectorphp/rector) to permit the latest version. - [Release notes](https://github.com/rectorphp/rector/releases) - [Commits](https://github.com/rectorphp/rector/compare/1.2.6...1.2.7) --- updated-dependencies: - dependency-name: rector/rector dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 1caf40d2c832..30c422611595 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": "1.2.6" + "rector/rector": "1.2.7" }, "replace": { "codeigniter4/framework": "self.version" From c8b9ea48eb624027353b3ea7a9920b198b55a709 Mon Sep 17 00:00:00 2001 From: Wolf Wortmann <7399618+element-code@users.noreply.github.com> Date: Tue, 15 Oct 2024 08:08:15 +0200 Subject: [PATCH 028/108] fix: change session start log level (#9221) * Change session start log level * Added changelog Signed-off-by: Wolf Wortmann <7399618+element-code@users.noreply.github.com> * Remove PR number from changelog Co-authored-by: Michal Sniatala --------- Signed-off-by: Wolf Wortmann <7399618+element-code@users.noreply.github.com> Co-authored-by: Michal Sniatala --- system/Session/Session.php | 2 +- user_guide_src/source/changelogs/v4.5.6.rst | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/system/Session/Session.php b/system/Session/Session.php index 0aabcbe31d53..b522f63af5f2 100644 --- a/system/Session/Session.php +++ b/system/Session/Session.php @@ -258,7 +258,7 @@ public function start() } $this->initVars(); - $this->logger->info("Session: Class initialized using '" . $this->config->driver . "' driver."); + $this->logger->debug("Session: Class initialized using '" . $this->config->driver . "' driver."); return $this; } diff --git a/user_guide_src/source/changelogs/v4.5.6.rst b/user_guide_src/source/changelogs/v4.5.6.rst index 33e3e5a1a0ab..e454409fc6a8 100644 --- a/user_guide_src/source/changelogs/v4.5.6.rst +++ b/user_guide_src/source/changelogs/v4.5.6.rst @@ -29,6 +29,7 @@ Deprecations ********** Bugs Fixed ********** +- **Session Library:** The session initialization debug message now uses the correct log type "debug" instead of "info". See the repo's `CHANGELOG.md `_ From 7c8216ffbc97eb8a24e6bd7f366f374d7daa84da Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Wed, 16 Oct 2024 02:28:17 +0700 Subject: [PATCH 029/108] Refactor: enable Rector Code Quality level, apply level 9 for SimplifyConditionsRector --- rector.php | 7 ++----- tests/system/Database/Live/UpdateTest.php | 10 +++++----- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/rector.php b/rector.php index 8fd3ab275345..4c15387198d9 100644 --- a/rector.php +++ b/rector.php @@ -12,13 +12,11 @@ */ use Rector\Caching\ValueObject\Storage\FileCacheStorage; -use Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector; use Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector; use Rector\CodeQuality\Rector\Empty_\SimplifyEmptyCheckOnEmptyArrayRector; use Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector; use Rector\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeysRector; use Rector\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector; -use Rector\CodeQuality\Rector\FuncCall\SimplifyStrposLowerRector; use Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector; use Rector\CodeQuality\Rector\FunctionLike\SimplifyUselessVariableRector; use Rector\CodeQuality\Rector\If_\CombineIfRector; @@ -190,7 +188,6 @@ CountArrayToEmptyArrayComparisonRector::class, ChangeNestedForeachIfsToEarlyContinueRector::class, ChangeIfElseValueAssignToEarlyReturnRector::class, - SimplifyStrposLowerRector::class, CombineIfRector::class, SimplifyIfReturnBoolRector::class, InlineIfToExplicitIfRector::class, @@ -203,7 +200,6 @@ RemoveErrorSuppressInTryCatchStmtsRector::class, FuncGetArgsToVariadicParamRector::class, MakeInheritedMethodVisibilitySameAsParentRector::class, - SimplifyEmptyArrayCheckRector::class, SimplifyEmptyCheckOnEmptyArrayRector::class, TernaryEmptyArrayArrayDimFetchToCoalesceRector::class, EmptyOnNullableObjectToInstanceOfRector::class, @@ -223,4 +219,5 @@ ->withConfiguredRule(StringClassNameToClassConstantRector::class, [ // keep '\\' prefix string on string '\Foo\Bar' StringClassNameToClassConstantRector::SHOULD_KEEP_PRE_SLASH => true, - ]); + ]) + ->withCodeQualityLevel(9); diff --git a/tests/system/Database/Live/UpdateTest.php b/tests/system/Database/Live/UpdateTest.php index 8af549fc638e..565c8f83b909 100644 --- a/tests/system/Database/Live/UpdateTest.php +++ b/tests/system/Database/Live/UpdateTest.php @@ -466,7 +466,7 @@ public function testUpdateBatchConstraintsRawSqlAndAlias(): void public function testUpdateBatchUpdateFieldsAndAlias(): void { - if ($this->db->DBDriver === 'SQLite3' && ! (version_compare($this->db->getVersion(), '3.33.0') >= 0)) { + if ($this->db->DBDriver === 'SQLite3' && version_compare($this->db->getVersion(), '3.33.0') < 0) { $this->markTestSkipped('Only SQLite 3.33 and newer can complete this test.'); } @@ -557,7 +557,7 @@ public function testUpdateBatchUpdateFieldsAndAlias(): void public function testUpdateBatchWithoutOnConstraint(): void { - if ($this->db->DBDriver === 'SQLite3' && ! (version_compare($this->db->getVersion(), '3.33.0') >= 0)) { + if ($this->db->DBDriver === 'SQLite3' && version_compare($this->db->getVersion(), '3.33.0') < 0) { $this->markTestSkipped('Only SQLite 3.33 and newer can complete this test.'); } @@ -599,7 +599,7 @@ public function testUpdateBatchWithoutOnConstraint(): void public function testRawSqlConstraint(): void { - if ($this->db->DBDriver === 'SQLite3' && ! (version_compare($this->db->getVersion(), '3.33.0') >= 0)) { + if ($this->db->DBDriver === 'SQLite3' && version_compare($this->db->getVersion(), '3.33.0') < 0) { $this->markTestSkipped('Only SQLite 3.33 and newer can complete this test.'); } @@ -623,7 +623,7 @@ public function testRawSqlConstraint(): void public function testRawSqlConstraintWithKey(): void { - if ($this->db->DBDriver === 'SQLite3' && ! (version_compare($this->db->getVersion(), '3.33.0') >= 0)) { + if ($this->db->DBDriver === 'SQLite3' && version_compare($this->db->getVersion(), '3.33.0') < 0) { $this->markTestSkipped('Only SQLite 3.33 and newer can complete this test.'); } @@ -710,7 +710,7 @@ public function testUpdateBatchWithQuery(): void ]; $this->db->table('user2')->insertBatch($data); - if ($this->db->DBDriver === 'SQLite3' && ! (version_compare($this->db->getVersion(), '3.33.0') >= 0)) { + if ($this->db->DBDriver === 'SQLite3' && version_compare($this->db->getVersion(), '3.33.0') < 0) { $this->markTestSkipped('Only SQLite 3.33 and newer can complete this test.'); } From bb650e12b82e5bd44f4fcd6648e190d5c86e716c Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Wed, 16 Oct 2024 02:56:50 +0700 Subject: [PATCH 030/108] fix invalid doc and regenerate baseline --- phpstan-baseline.php | 12 ------------ tests/system/Helpers/FilesystemHelperTest.php | 2 +- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/phpstan-baseline.php b/phpstan-baseline.php index 1ba751d7c11d..ea228647c992 100644 --- a/phpstan-baseline.php +++ b/phpstan-baseline.php @@ -15145,18 +15145,6 @@ 'count' => 2, 'path' => __DIR__ . '/tests/system/Helpers/FilesystemHelperTest.php', ]; -$ignoreErrors[] = [ - // identifier: property.phpDocType - 'message' => '#^PHPDoc tag @var for property CodeIgniter\\\\Helpers\\\\FilesystemHelperTest\\:\\:\\$structure with type mixed is not subtype of native type array\\.$#', - 'count' => 1, - 'path' => __DIR__ . '/tests/system/Helpers/FilesystemHelperTest.php', -]; -$ignoreErrors[] = [ - // identifier: missingType.iterableValue - 'message' => '#^Property CodeIgniter\\\\Helpers\\\\FilesystemHelperTest\\:\\:\\$structure type has no value type specified in iterable type array\\.$#', - 'count' => 1, - 'path' => __DIR__ . '/tests/system/Helpers/FilesystemHelperTest.php', -]; $ignoreErrors[] = [ // identifier: argument.type 'message' => '#^Parameter \\#2 \\$value of function form_hidden expects array\\|string, null given\\.$#', diff --git a/tests/system/Helpers/FilesystemHelperTest.php b/tests/system/Helpers/FilesystemHelperTest.php index ad169cf3b58b..a8ee76d6ab09 100644 --- a/tests/system/Helpers/FilesystemHelperTest.php +++ b/tests/system/Helpers/FilesystemHelperTest.php @@ -25,7 +25,7 @@ final class FilesystemHelperTest extends CIUnitTestCase { /** - * @var array>>|array>|array>|array|array|mixed + * @var array>>|array>|array>|array|array */ private array $structure; From f53ae7570c9dfe3079986464f676beb7216622f6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 18 Oct 2024 15:09:40 +0000 Subject: [PATCH 031/108] chore(deps-dev): update rector/rector requirement from 1.2.7 to 1.2.8 Updates the requirements on [rector/rector](https://github.com/rectorphp/rector) to permit the latest version. - [Release notes](https://github.com/rectorphp/rector/releases) - [Commits](https://github.com/rectorphp/rector/compare/1.2.7...1.2.8) --- updated-dependencies: - dependency-name: rector/rector dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 30c422611595..e6533a6daea1 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": "1.2.7" + "rector/rector": "1.2.8" }, "replace": { "codeigniter4/framework": "self.version" From 28d76073b0ffa2ff74e216eb32ac8e95e913ec0e Mon Sep 17 00:00:00 2001 From: Michal Sniatala Date: Sun, 20 Oct 2024 08:42:42 +0200 Subject: [PATCH 032/108] fix: pin python version for sphinx (#9224) * dev: pin python version for sphinx * dev: pin python for deploy workflow --- .github/workflows/deploy-distributables.yml | 10 +++++++--- .github/workflows/deploy-userguide-latest.yml | 17 +++++++++++++---- .github/workflows/test-userguide.yml | 17 +++++++++++++---- 3 files changed, 33 insertions(+), 11 deletions(-) diff --git a/.github/workflows/deploy-distributables.yml b/.github/workflows/deploy-distributables.yml index f28a62544fa5..7c0b4e4dd1ce 100644 --- a/.github/workflows/deploy-distributables.yml +++ b/.github/workflows/deploy-distributables.yml @@ -159,11 +159,15 @@ jobs: token: ${{ secrets.ACCESS_TOKEN }} path: userguide + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install Sphinx run: | - sudo apt install python3-sphinx - sudo pip3 install sphinxcontrib-phpdomain - sudo pip3 install sphinx_rtd_theme + python -m pip install --upgrade pip + pip install -r ./source/user_guide_src/requirements.txt - name: Chmod run: chmod +x ./source/.github/scripts/deploy-userguide diff --git a/.github/workflows/deploy-userguide-latest.yml b/.github/workflows/deploy-userguide-latest.yml index c131c80cd735..9188672f907a 100644 --- a/.github/workflows/deploy-userguide-latest.yml +++ b/.github/workflows/deploy-userguide-latest.yml @@ -33,11 +33,20 @@ jobs: php-version: '8.1' coverage: none - # Build the latest User Guide - - name: Build with Sphinx - uses: ammaraskar/sphinx-action@0.4 + - name: Setup Python + uses: actions/setup-python@v5 with: - docs-folder: user_guide_src/ + python-version: '3.12' + + - name: Install Sphinx + run: | + python -m pip install --upgrade pip + pip install -r user_guide_src/requirements.txt + + # Build the latest User Guide + - name: Build Docs with Sphinx + run: make html + working-directory: user_guide_src - name: Add "Edit this page" links run: | diff --git a/.github/workflows/test-userguide.yml b/.github/workflows/test-userguide.yml index b127d77dd344..f1e0d0bd60e6 100644 --- a/.github/workflows/test-userguide.yml +++ b/.github/workflows/test-userguide.yml @@ -26,10 +26,19 @@ jobs: - name: Checkout uses: actions/checkout@v4 + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install Sphinx + run: | + python -m pip install --upgrade pip + pip install -r user_guide_src/requirements.txt + - name: Detect usage of tabs in RST files run: php utils/check_tabs_in_rst.php - - uses: ammaraskar/sphinx-action@0.4 - with: - docs-folder: user_guide_src - build-command: 'make html SPHINXOPTS="-W --keep-going -w /tmp/sphinx-log"' + - name: Build Docs with Sphinx + run: make html SPHINXOPTS="-W --keep-going -w /tmp/sphinx-log" + working-directory: user_guide_src From ff2f756baa70eefd77978ac90fefb8ba1d5d82ea Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Mon, 21 Oct 2024 02:47:51 +0700 Subject: [PATCH 033/108] refactor: enable rector code quality level 14 --- rector.php | 6 +----- system/Config/Services.php | 2 +- system/Images/Handlers/ImageMagickHandler.php | 2 +- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/rector.php b/rector.php index 4c15387198d9..6c24c66e5539 100644 --- a/rector.php +++ b/rector.php @@ -23,9 +23,7 @@ use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector; use Rector\CodeQuality\Rector\If_\ShortenElseIfRector; use Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector; -use Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector; use Rector\CodeQuality\Rector\Ternary\TernaryEmptyArrayArrayDimFetchToCoalesceRector; -use Rector\CodeQuality\Rector\Ternary\UnnecessaryTernaryExpressionRector; use Rector\CodingStyle\Rector\ClassMethod\FuncGetArgsToVariadicParamRector; use Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsParentRector; use Rector\CodingStyle\Rector\FuncCall\CountArrayToEmptyArrayComparisonRector; @@ -189,14 +187,12 @@ ChangeNestedForeachIfsToEarlyContinueRector::class, ChangeIfElseValueAssignToEarlyReturnRector::class, CombineIfRector::class, - SimplifyIfReturnBoolRector::class, InlineIfToExplicitIfRector::class, PreparedValueToEarlyReturnRector::class, ShortenElseIfRector::class, SimplifyIfElseToTernaryRector::class, UnusedForeachValueToArrayKeysRector::class, ChangeArrayPushToArrayAssignRector::class, - UnnecessaryTernaryExpressionRector::class, RemoveErrorSuppressInTryCatchStmtsRector::class, FuncGetArgsToVariadicParamRector::class, MakeInheritedMethodVisibilitySameAsParentRector::class, @@ -220,4 +216,4 @@ // keep '\\' prefix string on string '\Foo\Bar' StringClassNameToClassConstantRector::SHOULD_KEEP_PRE_SLASH => true, ]) - ->withCodeQualityLevel(9); + ->withCodeQualityLevel(14); diff --git a/system/Config/Services.php b/system/Config/Services.php index e37b1278e9a7..1a8843fa39b4 100644 --- a/system/Config/Services.php +++ b/system/Config/Services.php @@ -230,7 +230,7 @@ public static function email($config = null, bool $getShared = true) return static::getSharedInstance('email', $config); } - if (empty($config) || ! (is_array($config) || $config instanceof EmailConfig)) { + if (empty($config) || (! is_array($config) && ! $config instanceof EmailConfig)) { $config = config(EmailConfig::class); } diff --git a/system/Images/Handlers/ImageMagickHandler.php b/system/Images/Handlers/ImageMagickHandler.php index fa226ccf2289..e59f91869851 100644 --- a/system/Images/Handlers/ImageMagickHandler.php +++ b/system/Images/Handlers/ImageMagickHandler.php @@ -42,7 +42,7 @@ public function __construct($config = null) { parent::__construct($config); - if (! (extension_loaded('imagick') || class_exists(Imagick::class))) { + if (! extension_loaded('imagick') && ! class_exists(Imagick::class)) { throw ImageException::forMissingExtension('IMAGICK'); // @codeCoverageIgnore } From 4a7fbd12296da0869dfe68f8622d0b89c56ed67c Mon Sep 17 00:00:00 2001 From: Denny Septian Panggabean <97607754+ddevsr@users.noreply.github.com> Date: Tue, 22 Oct 2024 13:23:28 +0700 Subject: [PATCH 034/108] fix: `getValidated()` when validation multiple asterisk (#9220) * fix: validation multiple asterisk * docs: changelog * Update user_guide_src/source/changelogs/v4.5.6.rst Co-authored-by: Michal Sniatala * tests: multiple asterisk for fail * fix: PHPStan errors appear --------- Co-authored-by: Michal Sniatala --- system/Validation/DotArrayFilter.php | 69 ++++++++---------- tests/system/Validation/ValidationTest.php | 81 +++++++++++++++++++++ user_guide_src/source/changelogs/v4.5.6.rst | 2 + 3 files changed, 114 insertions(+), 38 deletions(-) diff --git a/system/Validation/DotArrayFilter.php b/system/Validation/DotArrayFilter.php index 4d2e1cb19ed2..c7a401e1589a 100644 --- a/system/Validation/DotArrayFilter.php +++ b/system/Validation/DotArrayFilter.php @@ -21,8 +21,6 @@ final class DotArrayFilter /** * Creates a new array with only the elements specified in dot array syntax. * - * This code comes from the dot_array_search() function. - * * @param array $indexes The dot array syntax pattern to use for filtering. * @param array $array The array to filter. * @@ -33,20 +31,14 @@ public static function run(array $indexes, array $array): array $result = []; foreach ($indexes as $index) { - // See https://regex101.com/r/44Ipql/1 - $segments = preg_split( - '/(? str_replace('\.', '.', $key), - $segments - ); - - $result = array_replace_recursive($result, self::filter($segments, $array)); + $segments = preg_split('/(? str_replace('\.', '.', $key), $segments); + + $filteredArray = self::filter($segments, $array); + + if ($filteredArray !== []) { + $result = array_replace_recursive($result, $filteredArray); + } } return $result; @@ -62,53 +54,54 @@ public static function run(array $indexes, array $array): array */ private static function filter(array $indexes, array $array): array { - // If index is empty, returns empty array. + // If there are no indexes left, return an empty array if ($indexes === []) { return []; } - // Grab the current index. + // Get the current index $currentIndex = array_shift($indexes); + // If the current index doesn't exist and is not a wildcard, return an empty array if (! isset($array[$currentIndex]) && $currentIndex !== '*') { return []; } - // Handle Wildcard (*) + // Handle the wildcard '*' at the current level if ($currentIndex === '*') { - $answer = []; + $result = []; + // Iterate over all keys at this level foreach ($array as $key => $value) { - if (! is_array($value)) { - continue; - } - - $result = self::filter($indexes, $value); - - if ($result !== []) { - $answer[$key] = $result; + if ($indexes === []) { + // If no indexes are left, capture the entire value + $result[$key] = $value; + } elseif (is_array($value)) { + // If there are still indexes left, continue filtering recursively + $filtered = self::filter($indexes, $value); + if ($filtered !== []) { + $result[$key] = $filtered; + } } } - return $answer; + return $result; } - // If this is the last index, make sure to return it now, - // and not try to recurse through things. + // If this is the last index, return the value if ($indexes === []) { - return [$currentIndex => $array[$currentIndex]]; + return [$currentIndex => $array[$currentIndex] ?? []]; } - // Do we need to recursively filter this value? - if (is_array($array[$currentIndex]) && $array[$currentIndex] !== []) { - $result = self::filter($indexes, $array[$currentIndex]); + // If the current value is an array, recursively filter it + if (is_array($array[$currentIndex])) { + $filtered = self::filter($indexes, $array[$currentIndex]); - if ($result !== []) { - return [$currentIndex => $result]; + if ($filtered !== []) { + return [$currentIndex => $filtered]; } } - // Otherwise, not found. return []; } } diff --git a/tests/system/Validation/ValidationTest.php b/tests/system/Validation/ValidationTest.php index 13991dc45916..28003dbb6477 100644 --- a/tests/system/Validation/ValidationTest.php +++ b/tests/system/Validation/ValidationTest.php @@ -21,6 +21,7 @@ use CodeIgniter\Validation\Exceptions\ValidationException; use Config\App; use Config\Services; +use Generator; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\ExpectationFailedException; @@ -1826,4 +1827,84 @@ public function testRuleWithAsteriskToMultiDimensionalArray(): void $this->validation->getErrors() ); } + + /** + * @param array $data + * @param array $rules + * @param array $expectedData + * + * @see https://github.com/codeigniter4/CodeIgniter4/issues/9219 + */ + #[DataProvider('provideMultipleAsterisk')] + public function testRuleWithMultipleAsterisk( + array $data = [], + array $rules = [], + bool $expectedCheck = false, + array $expectedData = [] + ): void { + $this->validation->setRules($rules); + + $this->assertSame($expectedCheck, $this->validation->run($data)); + $this->assertSame($expectedData, $this->validation->getValidated()); + } + + public static function provideMultipleAsterisk(): Generator + { + yield 'success' => [ + [ + 'dates' => [ + 23 => [ + 45 => 'Its Mee!', + ], + ], + 'foo' => [ + 'bar' => [ + 'data' => [ + 'name' => 'John Doe', + 'age' => 29, + 'location' => 'Indonesia', + ], + ], + ], + ], + [ + 'dates.*.*' => 'required', + 'foo.*.*.*' => 'required', + ], + true, + [ + 'dates' => [ + 23 => [ + 45 => 'Its Mee!', + ], + ], + 'foo' => [ + 'bar' => [ + 'data' => [ + 'name' => 'John Doe', + 'age' => 29, + 'location' => 'Indonesia', + ], + ], + ], + ], + ]; + + yield 'failed' => [ + [ + 'foo' => [ + 'bar' => [ + 'data' => [ + 'name' => '', + 'age' => 29, + 'location' => 'Indonesia', + ], + ], + ], + ], + ['foo.*.*.*' => 'required'], + false, + [], + ]; + } } diff --git a/user_guide_src/source/changelogs/v4.5.6.rst b/user_guide_src/source/changelogs/v4.5.6.rst index e454409fc6a8..b982f54b38f7 100644 --- a/user_guide_src/source/changelogs/v4.5.6.rst +++ b/user_guide_src/source/changelogs/v4.5.6.rst @@ -31,6 +31,8 @@ Bugs Fixed ********** - **Session Library:** The session initialization debug message now uses the correct log type "debug" instead of "info". +- **Validation:** Fixed the `getValidated()` method that did not return valid data when validation rules used multiple asterisks. + See the repo's `CHANGELOG.md `_ for a complete list of bugs fixed. From 11d97212edf88fa6e089e83811bd19eb1b8926b3 Mon Sep 17 00:00:00 2001 From: grimpirate Date: Tue, 22 Oct 2024 02:25:43 -0400 Subject: [PATCH 035/108] refactor: cleanup `DatabaseHandler::gc()` for session (#9230) * Removal of unneeded operations/variables * Update system/Session/Handlers/DatabaseHandler.php --------- Co-authored-by: Michal Sniatala --- system/Session/Handlers/DatabaseHandler.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/system/Session/Handlers/DatabaseHandler.php b/system/Session/Handlers/DatabaseHandler.php index 2d1d2fbbe97e..d36e9592cec0 100644 --- a/system/Session/Handlers/DatabaseHandler.php +++ b/system/Session/Handlers/DatabaseHandler.php @@ -282,12 +282,9 @@ public function destroy($id): bool #[ReturnTypeWillChange] public function gc($max_lifetime) { - $separator = ' '; - $interval = implode($separator, ['', "{$max_lifetime} second", '']); - return $this->db->table($this->table)->where( 'timestamp <', - "now() - INTERVAL {$interval}", + "now() - INTERVAL {$max_lifetime} second", false )->delete() ? 1 : $this->fail(); } From 70816be6c8c38667b7a6102a29bcd594a8e9853d Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Mon, 28 Oct 2024 22:16:15 +0700 Subject: [PATCH 036/108] refactor: Apply code quality level 15 for Rector --- rector.php | 2 +- system/HTTP/CLIRequest.php | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/rector.php b/rector.php index 6c24c66e5539..913dc7277e41 100644 --- a/rector.php +++ b/rector.php @@ -216,4 +216,4 @@ // keep '\\' prefix string on string '\Foo\Bar' StringClassNameToClassConstantRector::SHOULD_KEEP_PRE_SLASH => true, ]) - ->withCodeQualityLevel(14); + ->withCodeQualityLevel(15); diff --git a/system/HTTP/CLIRequest.php b/system/HTTP/CLIRequest.php index 0b2c57377e65..fbc5165e9a9a 100644 --- a/system/HTTP/CLIRequest.php +++ b/system/HTTP/CLIRequest.php @@ -95,9 +95,7 @@ public function __construct(App $config) */ public function getPath(): string { - $path = implode('/', $this->segments); - - return ($path === '') ? '' : $path; + return implode('/', $this->segments); } /** From dede747236f61d73f6c0c0fac7cf575fb610b184 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Wed, 30 Oct 2024 16:34:36 +0700 Subject: [PATCH 037/108] refactor: enable SimplifyBoolIdenticalTrueRector --- phpstan-baseline.php | 6 ----- rector.php | 2 ++ system/CLI/CLI.php | 2 +- system/Cache/Handlers/FileHandler.php | 4 ++-- system/Config/Services.php | 2 +- system/Database/BaseBuilder.php | 22 +++++++++---------- system/Database/BaseConnection.php | 12 +++++----- system/Database/Forge.php | 14 ++++++------ system/Database/MySQLi/Connection.php | 4 ++-- system/Database/MySQLi/Forge.php | 2 +- system/Database/OCI8/Connection.php | 2 +- system/Database/OCI8/Forge.php | 4 ++-- system/Database/Postgre/Builder.php | 2 +- system/Database/Postgre/Connection.php | 6 ++--- system/Database/Postgre/Forge.php | 4 ++-- system/Database/SQLSRV/Builder.php | 2 +- system/Database/SQLSRV/Connection.php | 2 +- system/Database/SQLSRV/Forge.php | 2 +- system/Database/SQLite3/Connection.php | 4 ++-- system/HTTP/DownloadResponse.php | 2 +- system/Helpers/form_helper.php | 6 ++--- system/Helpers/html_helper.php | 14 ++++++------ system/Helpers/url_helper.php | 2 +- system/Helpers/xml_helper.php | 4 ++-- system/Images/Handlers/ImageMagickHandler.php | 2 +- system/Images/Image.php | 2 +- system/Log/Handlers/FileHandler.php | 3 ++- system/Pager/Pager.php | 2 +- system/Router/AutoRouter.php | 2 +- system/Typography/Typography.php | 2 +- system/Validation/Validation.php | 2 +- 31 files changed, 69 insertions(+), 72 deletions(-) diff --git a/phpstan-baseline.php b/phpstan-baseline.php index ea228647c992..2e6e8b31ec37 100644 --- a/phpstan-baseline.php +++ b/phpstan-baseline.php @@ -7849,12 +7849,6 @@ 'count' => 1, 'path' => __DIR__ . '/system/Log/Handlers/FileHandler.php', ]; -$ignoreErrors[] = [ - // identifier: identical.alwaysTrue - 'message' => '#^Strict comparison using \\=\\=\\= between true and true will always evaluate to true\\.$#', - 'count' => 1, - 'path' => __DIR__ . '/system/Log/Handlers/FileHandler.php', -]; $ignoreErrors[] = [ // identifier: missingType.iterableValue 'message' => '#^Method CodeIgniter\\\\Log\\\\Logger\\:\\:determineFile\\(\\) return type has no value type specified in iterable type array\\.$#', diff --git a/rector.php b/rector.php index 913dc7277e41..89647759b914 100644 --- a/rector.php +++ b/rector.php @@ -19,6 +19,7 @@ use Rector\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector; use Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector; use Rector\CodeQuality\Rector\FunctionLike\SimplifyUselessVariableRector; +use Rector\CodeQuality\Rector\Identical\SimplifyBoolIdenticalTrueRector; use Rector\CodeQuality\Rector\If_\CombineIfRector; use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector; use Rector\CodeQuality\Rector\If_\ShortenElseIfRector; @@ -211,6 +212,7 @@ AddMethodCallBasedStrictParamTypeRector::class, TypedPropertyFromAssignsRector::class, ClosureReturnTypeRector::class, + SimplifyBoolIdenticalTrueRector::class, ]) ->withConfiguredRule(StringClassNameToClassConstantRector::class, [ // keep '\\' prefix string on string '\Foo\Bar' diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index bfe1511eed02..54ca6a5ca97e 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -514,7 +514,7 @@ public static function beep(int $num = 1) */ public static function wait(int $seconds, bool $countdown = false) { - if ($countdown === true) { + if ($countdown) { $time = $seconds; while ($time > 0) { diff --git a/system/Cache/Handlers/FileHandler.php b/system/Cache/Handlers/FileHandler.php index cf45a6544e27..a86a45e83d00 100644 --- a/system/Cache/Handlers/FileHandler.php +++ b/system/Cache/Handlers/FileHandler.php @@ -308,7 +308,7 @@ protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs if ($filename !== '.' && $filename !== '..') { if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.') { $this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $delDir, $htdocs, $_level + 1); - } elseif ($htdocs !== true || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) { + } elseif (! $htdocs || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) { @unlink($path . DIRECTORY_SEPARATOR . $filename); } } @@ -316,7 +316,7 @@ protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs closedir($currentDir); - return ($delDir === true && $_level > 0) ? @rmdir($path) : true; + return ($delDir && $_level > 0) ? @rmdir($path) : true; } /** diff --git a/system/Config/Services.php b/system/Config/Services.php index 1a8843fa39b4..28e521df3f0e 100644 --- a/system/Config/Services.php +++ b/system/Config/Services.php @@ -202,7 +202,7 @@ public static function csp(?CSPConfig $config = null, bool $getShared = true) */ public static function curlrequest(array $options = [], ?ResponseInterface $response = null, ?App $config = null, bool $getShared = true) { - if ($getShared === true) { + if ($getShared) { return static::getSharedInstance('curlrequest', $options, $response, $config); } diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index 9d5a02db9f6e..570340dffb9b 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -579,7 +579,7 @@ public function distinct(bool $val = true) */ public function from($from, bool $overwrite = false): self { - if ($overwrite === true) { + if ($overwrite) { $this->QBFrom = []; $this->db->setAliasedTables([]); } @@ -769,7 +769,7 @@ protected function whereHaving(string $qbKey, $key, $value = null, string $type foreach ($keyValue as $k => $v) { $prefix = empty($this->{$qbKey}) ? $this->groupGetType('') : $this->groupGetType($type); - if ($rawSqlOnly === true) { + if ($rawSqlOnly) { $k = ''; $op = ''; } elseif ($v !== null) { @@ -1150,7 +1150,7 @@ protected function _like($field, string $match = '', string $type = 'AND ', stri $keyValue = ! is_array($field) ? [$field => $match] : $field; foreach ($keyValue as $k => $v) { - if ($insensitiveSearch === true) { + if ($insensitiveSearch) { $v = strtolower($v); } @@ -1187,7 +1187,7 @@ protected function _like($field, string $match = '', string $type = 'AND ', stri */ protected function _like_statement(?string $prefix, string $column, ?string $not, string $bind, bool $insensitiveSearch = false): string { - if ($insensitiveSearch === true) { + if ($insensitiveSearch) { return "{$prefix} LOWER(" . $this->db->escapeIdentifiers($column) . ") {$not} LIKE :{$bind}:"; } @@ -1599,7 +1599,7 @@ public function getCompiledSelect(bool $reset = true): string { $select = $this->compileSelect(); - if ($reset === true) { + if ($reset) { $this->resetSelect(); } @@ -1643,7 +1643,7 @@ public function get(?int $limit = null, int $offset = 0, bool $reset = true) ? $this->getCompiledSelect($reset) : $this->db->query($this->compileSelect(), $this->binds, false); - if ($reset === true) { + if ($reset) { $this->resetSelect(); // Clear our binds so we don't eat up memory @@ -1678,7 +1678,7 @@ public function countAll(bool $reset = true) $query = $query->getRow(); - if ($reset === true) { + if ($reset) { $this->resetSelect(); } @@ -1727,7 +1727,7 @@ public function countAllResults(bool $reset = true) $result = $this->db->query($sql, $this->binds, false); - if ($reset === true) { + if ($reset) { $this->resetSelect(); } elseif (! isset($this->QBOrderBy)) { $this->QBOrderBy = $orderBy; @@ -1781,7 +1781,7 @@ public function getWhere($where = null, ?int $limit = null, ?int $offset = 0, bo ? $this->getCompiledSelect($reset) : $this->db->query($this->compileSelect(), $this->binds, false); - if ($reset === true) { + if ($reset) { $this->resetSelect(); // Clear our binds so we don't eat up memory @@ -2297,7 +2297,7 @@ public function getCompiledInsert(bool $reset = true) array_values($this->QBSet) ); - if ($reset === true) { + if ($reset) { $this->resetWrite(); } @@ -2466,7 +2466,7 @@ public function getCompiledUpdate(bool $reset = true) $sql = $this->_update($this->QBFrom[0], $this->QBSet); - if ($reset === true) { + if ($reset) { $this->resetWrite(); } diff --git a/system/Database/BaseConnection.php b/system/Database/BaseConnection.php index 56340c8decd5..487f01df4ccb 100644 --- a/system/Database/BaseConnection.php +++ b/system/Database/BaseConnection.php @@ -848,7 +848,7 @@ public function transBegin(bool $testMode = false): bool // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. - $this->transFailure = ($testMode === true); + $this->transFailure = ($testMode); if ($this->_transBegin()) { $this->transDepth++; @@ -1124,7 +1124,7 @@ public function protectIdentifiers($item, bool $prefixSingle = false, ?bool $pro $item = preg_replace('/^' . $this->swapPre . '(\S+?)/', $this->DBPrefix . '\\1', $item); } // Do we prefix an item with no segments? - elseif ($prefixSingle === true && ! str_starts_with($item, $this->DBPrefix)) { + elseif ($prefixSingle && ! str_starts_with($item, $this->DBPrefix)) { $item = $this->DBPrefix . $item; } } @@ -1147,7 +1147,7 @@ private function protectDotItem(string $item, string $alias, bool $protectIdenti // NOTE: The ! empty() condition prevents this method // from breaking when QB isn't enabled. if (! empty($this->aliasedTables) && in_array($parts[0], $this->aliasedTables, true)) { - if ($protectIdentifiers === true) { + if ($protectIdentifiers) { foreach ($parts as $key => $val) { if (! in_array($val, $this->reservedIdentifiers, true)) { $parts[$key] = $this->escapeIdentifiers($val); @@ -1198,7 +1198,7 @@ private function protectDotItem(string $item, string $alias, bool $protectIdenti $item = implode('.', $parts); } - if ($protectIdentifiers === true) { + if ($protectIdentifiers) { $item = $this->escapeIdentifiers($item); } @@ -1372,7 +1372,7 @@ public function escapeString($str, bool $like = false) $str = $this->_escapeString($str); // escape LIKE condition wildcards - if ($like === true) { + if ($like) { return str_replace( [ $this->likeEscapeChar, @@ -1501,7 +1501,7 @@ public function listTables(bool $constrainByPrefix = false) */ public function tableExists(string $tableName, bool $cached = true): bool { - if ($cached === true) { + if ($cached) { return in_array($this->protectIdentifiers($tableName, true, false, false), $this->listTables(), true); } diff --git a/system/Database/Forge.php b/system/Database/Forge.php index 595cd6156b5f..735303614b51 100644 --- a/system/Database/Forge.php +++ b/system/Database/Forge.php @@ -449,12 +449,12 @@ public function addForeignKey( */ public function dropKey(string $table, string $keyName, bool $prefixKeyName = true): bool { - $keyName = $this->db->escapeIdentifiers(($prefixKeyName === true ? $this->db->DBPrefix : '') . $keyName); + $keyName = $this->db->escapeIdentifiers(($prefixKeyName ? $this->db->DBPrefix : '') . $keyName); $table = $this->db->escapeIdentifiers($this->db->DBPrefix . $table); $dropKeyAsConstraint = $this->dropKeyAsConstraint($table, $keyName); - if ($dropKeyAsConstraint === true) { + if ($dropKeyAsConstraint) { $sql = sprintf( $this->dropConstraintStr, $table, @@ -559,7 +559,7 @@ public function createTable(string $table, bool $ifNotExists = false, array $att } // If table exists lets stop here - if ($ifNotExists === true && $this->db->tableExists($table, false)) { + if ($ifNotExists && $this->db->tableExists($table, false)) { $this->reset(); return true; @@ -895,7 +895,7 @@ protected function _processFields(bool $createTable = false): array $attributes = array_change_key_case($attributes, CASE_UPPER); - if ($createTable === true && empty($attributes['TYPE'])) { + if ($createTable && empty($attributes['TYPE'])) { continue; } @@ -942,7 +942,7 @@ protected function _processFields(bool $createTable = false): array } else { $field['null'] = ' NOT ' . $this->null; } - } elseif ($createTable === true) { + } elseif ($createTable) { $field['null'] = ' NOT ' . $this->null; } @@ -1085,7 +1085,7 @@ protected function _processPrimaryKeys(string $table, bool $asQuery = false): st } if (isset($this->primaryKeys['fields']) && $this->primaryKeys['fields'] !== []) { - if ($asQuery === true) { + if ($asQuery) { $sql .= 'ALTER TABLE ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $table) . ' ADD '; } else { $sql .= ",\n\t"; @@ -1229,7 +1229,7 @@ protected function _processForeignKeys(string $table, bool $asQuery = false): ar $referenceTableFilled = $this->db->escapeIdentifiers($this->db->DBPrefix . $fkey['referenceTable']); $referenceFieldFilled = implode(', ', $this->db->escapeIdentifiers($fkey['referenceField'])); - if ($asQuery === true) { + if ($asQuery) { $sqls[$index] .= 'ALTER TABLE ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $table) . ' ADD '; } else { $sqls[$index] .= ",\n\t"; diff --git a/system/Database/MySQLi/Connection.php b/system/Database/MySQLi/Connection.php index 068dfba5b9e9..6524d95b41f1 100644 --- a/system/Database/MySQLi/Connection.php +++ b/system/Database/MySQLi/Connection.php @@ -96,7 +96,7 @@ public function connect(bool $persistent = false) $port = null; $socket = $this->hostname; } else { - $hostname = ($persistent === true) ? 'p:' . $this->hostname : $this->hostname; + $hostname = ($persistent) ? 'p:' . $this->hostname : $this->hostname; $port = empty($this->port) ? null : $this->port; $socket = ''; } @@ -399,7 +399,7 @@ protected function _listTables(bool $prefixLimit = false, ?string $tableName = n return $sql . ' LIKE ' . $this->escape($tableName); } - if ($prefixLimit !== false && $this->DBPrefix !== '') { + if ($prefixLimit && $this->DBPrefix !== '') { return $sql . " LIKE '" . $this->escapeLikeStringDirect($this->DBPrefix) . "%'"; } diff --git a/system/Database/MySQLi/Forge.php b/system/Database/MySQLi/Forge.php index 132bde1258cc..3bde0c518daf 100644 --- a/system/Database/MySQLi/Forge.php +++ b/system/Database/MySQLi/Forge.php @@ -222,7 +222,7 @@ protected function _processIndexes(string $table, bool $asQuery = false): array implode('_', $this->keys[$i]['fields']) : $this->keys[$i]['keyName']); - if ($asQuery === true) { + if ($asQuery) { $sqls[$index] = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table) . " ADD {$unique}KEY " . $keyName . ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i]['fields'])) . ')'; diff --git a/system/Database/OCI8/Connection.php b/system/Database/OCI8/Connection.php index 2b870b755b44..c59d588ccec1 100644 --- a/system/Database/OCI8/Connection.php +++ b/system/Database/OCI8/Connection.php @@ -274,7 +274,7 @@ protected function _listTables(bool $prefixLimit = false, ?string $tableName = n return $sql . ' WHERE "TABLE_NAME" LIKE ' . $this->escape($tableName); } - if ($prefixLimit !== false && $this->DBPrefix !== '') { + if ($prefixLimit && $this->DBPrefix !== '') { return $sql . ' WHERE "TABLE_NAME" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . "%' " . sprintf($this->likeEscapeStr, $this->likeEscapeChar); } diff --git a/system/Database/OCI8/Forge.php b/system/Database/OCI8/Forge.php index 5a10363be769..7d81cff8b506 100644 --- a/system/Database/OCI8/Forge.php +++ b/system/Database/OCI8/Forge.php @@ -135,7 +135,7 @@ protected function _alterTable(string $alterType, string $table, $processedField $wantToAddNull = ! str_contains($processedFields[$i]['null'], ' NOT'); $currentNullable = $nullableMap[$processedFields[$i]['name']]; - if ($wantToAddNull === true && $currentNullable === true) { + if ($wantToAddNull && $currentNullable === true) { $processedFields[$i]['null'] = ''; } elseif ($processedFields[$i]['null'] === '' && $currentNullable === false) { // Nullable by default @@ -293,7 +293,7 @@ protected function _dropTable(string $table, bool $ifExists, bool $cascade) { $sql = parent::_dropTable($table, $ifExists, $cascade); - if ($sql !== true && $cascade === true) { + if ($sql !== true && $cascade) { $sql .= ' CASCADE CONSTRAINTS PURGE'; } elseif ($sql !== true) { $sql .= ' PURGE'; diff --git a/system/Database/Postgre/Builder.php b/system/Database/Postgre/Builder.php index 12845a0e4f54..faae0eda8a9b 100644 --- a/system/Database/Postgre/Builder.php +++ b/system/Database/Postgre/Builder.php @@ -293,7 +293,7 @@ protected function _truncate(string $table): string */ protected function _like_statement(?string $prefix, string $column, ?string $not, string $bind, bool $insensitiveSearch = false): string { - $op = $insensitiveSearch === true ? 'ILIKE' : 'LIKE'; + $op = $insensitiveSearch ? 'ILIKE' : 'LIKE'; return "{$prefix} {$column} {$not} {$op} :{$bind}:"; } diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index ec886dbd4d8b..416d6e02f86f 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -74,11 +74,11 @@ public function connect(bool $persistent = false) $this->convertDSN(); } - $this->connID = $persistent === true ? pg_pconnect($this->DSN) : pg_connect($this->DSN); + $this->connID = $persistent ? pg_pconnect($this->DSN) : pg_connect($this->DSN); if ($this->connID !== false) { if ( - $persistent === true + $persistent && pg_connection_status($this->connID) === PGSQL_CONNECTION_BAD && pg_ping($this->connID) === false ) { @@ -289,7 +289,7 @@ protected function _listTables(bool $prefixLimit = false, ?string $tableName = n return $sql . ' AND "table_name" LIKE ' . $this->escape($tableName); } - if ($prefixLimit !== false && $this->DBPrefix !== '') { + if ($prefixLimit && $this->DBPrefix !== '') { return $sql . ' AND "table_name" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . "%' " . sprintf($this->likeEscapeStr, $this->likeEscapeChar); diff --git a/system/Database/Postgre/Forge.php b/system/Database/Postgre/Forge.php index 7a61bed5a57c..b516172737ae 100644 --- a/system/Database/Postgre/Forge.php +++ b/system/Database/Postgre/Forge.php @@ -118,7 +118,7 @@ protected function _alterTable(string $alterType, string $table, $processedField $nullable = false; } $sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name']) - . ($nullable === true ? ' DROP' : ' SET') . ' NOT NULL'; + . ($nullable ? ' DROP' : ' SET') . ' NOT NULL'; if (! empty($field['new_name'])) { $sqls[] = $sql . ' RENAME COLUMN ' . $this->db->escapeIdentifiers($field['name']) @@ -195,7 +195,7 @@ protected function _dropTable(string $table, bool $ifExists, bool $cascade): str { $sql = parent::_dropTable($table, $ifExists, $cascade); - if ($cascade === true) { + if ($cascade) { $sql .= ' CASCADE'; } diff --git a/system/Database/SQLSRV/Builder.php b/system/Database/SQLSRV/Builder.php index fcc0b170084f..c1272cdcf326 100644 --- a/system/Database/SQLSRV/Builder.php +++ b/system/Database/SQLSRV/Builder.php @@ -518,7 +518,7 @@ public function countAll(bool $reset = true) $query = $query->getRow(); - if ($reset === true) { + if ($reset) { $this->resetSelect(); } diff --git a/system/Database/SQLSRV/Connection.php b/system/Database/SQLSRV/Connection.php index 7e008e27c451..7d60ad1cabd1 100644 --- a/system/Database/SQLSRV/Connection.php +++ b/system/Database/SQLSRV/Connection.php @@ -215,7 +215,7 @@ protected function _listTables(bool $prefixLimit = false, ?string $tableName = n return $sql .= ' AND [TABLE_NAME] LIKE ' . $this->escape($tableName); } - if ($prefixLimit === true && $this->DBPrefix !== '') { + if ($prefixLimit && $this->DBPrefix !== '') { $sql .= " AND [TABLE_NAME] LIKE '" . $this->escapeLikeString($this->DBPrefix) . "%' " . sprintf($this->likeEscapeStr, $this->likeEscapeChar); } diff --git a/system/Database/SQLSRV/Forge.php b/system/Database/SQLSRV/Forge.php index cae4eda2a4f5..3bfda3bfe895 100644 --- a/system/Database/SQLSRV/Forge.php +++ b/system/Database/SQLSRV/Forge.php @@ -263,7 +263,7 @@ protected function _alterTable(string $alterType, string $table, $processedField $nullable = false; } $sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name']) - . " {$field['type']}{$field['length']} " . ($nullable === true ? '' : 'NOT') . ' NULL'; + . " {$field['type']}{$field['length']} " . ($nullable ? '' : 'NOT') . ' NULL'; if (! empty($field['comment'])) { $sqls[] = 'EXEC sys.sp_addextendedproperty ' diff --git a/system/Database/SQLite3/Connection.php b/system/Database/SQLite3/Connection.php index 9945d41de11b..a1a03eff61f5 100644 --- a/system/Database/SQLite3/Connection.php +++ b/system/Database/SQLite3/Connection.php @@ -202,7 +202,7 @@ protected function _listTables(bool $prefixLimit = false, ?string $tableName = n return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\'' . ' AND "NAME" NOT LIKE \'sqlite!_%\' ESCAPE \'!\'' - . (($prefixLimit !== false && $this->DBPrefix !== '') + . (($prefixLimit && $this->DBPrefix !== '') ? ' AND "NAME" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . '%\' ' . sprintf($this->likeEscapeStr, $this->likeEscapeChar) : ''); } @@ -359,7 +359,7 @@ protected function _indexData(string $table): array */ protected function _foreignKeyData(string $table): array { - if ($this->supportsForeignKeys() !== true) { + if (! $this->supportsForeignKeys()) { return []; } diff --git a/system/HTTP/DownloadResponse.php b/system/HTTP/DownloadResponse.php index 6b293fbca239..56953823693d 100644 --- a/system/HTTP/DownloadResponse.php +++ b/system/HTTP/DownloadResponse.php @@ -142,7 +142,7 @@ private function setContentTypeByMimeType(): void $mime = null; $charset = ''; - if ($this->setMime === true && ($lastDotPosition = strrpos($this->filename, '.')) !== false) { + if ($this->setMime && ($lastDotPosition = strrpos($this->filename, '.')) !== false) { $mime = Mimes::guessTypeFromExtension(substr($this->filename, $lastDotPosition + 1)); $charset = $this->charset; } diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index 2e5b9f7ca576..422c5f1adbb2 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -582,7 +582,7 @@ function set_select(string $field, string $value = '', bool $default = false): s } if ($input === null) { - return ($default === true) ? ' selected="selected"' : ''; + return ($default) ? ' selected="selected"' : ''; } if (is_array($input)) { @@ -636,7 +636,7 @@ function set_checkbox(string $field, string $value = '', bool $default = false): return ($input === $value) ? ' checked="checked"' : ''; } - return ($default === true) ? ' checked="checked"' : ''; + return ($default) ? ' checked="checked"' : ''; } } @@ -673,7 +673,7 @@ function set_radio(string $field, string $value = '', bool $default = false): st return ((string) $input === $value) ? ' checked="checked"' : ''; } - return ($default === true) ? ' checked="checked"' : ''; + return ($default) ? ' checked="checked"' : ''; } } diff --git a/system/Helpers/html_helper.php b/system/Helpers/html_helper.php index b9e5e5c8ed0e..30733acd5175 100644 --- a/system/Helpers/html_helper.php +++ b/system/Helpers/html_helper.php @@ -113,7 +113,7 @@ function img($src = '', bool $indexPage = false, $attributes = ''): string // Check for a relative URI if (! preg_match('#^([a-z]+:)?//#i', $src['src']) && ! str_starts_with($src['src'], 'data:')) { - if ($indexPage === true) { + if ($indexPage) { $img .= ' src="' . site_url($src['src']) . '"'; } else { $img .= ' src="' . slash_item('baseURL') . $src['src'] . '"'; @@ -207,7 +207,7 @@ function script_tag($src = '', bool $indexPage = false): string foreach ($src as $k => $v) { if ($k === 'src' && ! preg_match('#^([a-z]+:)?//#i', $v)) { - if ($indexPage === true) { + if ($indexPage) { $script .= 'src="' . site_url($v) . '" '; } else { $script .= 'src="' . slash_item('baseURL') . $v . '" '; @@ -302,7 +302,7 @@ function video($src, string $unsupportedMessage = '', string $attributes = '', a if (_has_protocol($src)) { $video .= ' src="' . $src . '"'; - } elseif ($indexPage === true) { + } elseif ($indexPage) { $video .= ' src="' . site_url($src) . '"'; } else { $video .= ' src="' . slash_item('baseURL') . $src . '"'; @@ -349,7 +349,7 @@ function audio($src, string $unsupportedMessage = '', string $attributes = '', a if (_has_protocol($src)) { $audio .= ' src="' . $src . '"'; - } elseif ($indexPage === true) { + } elseif ($indexPage) { $audio .= ' src="' . site_url($src) . '"'; } else { $audio .= ' src="' . slash_item('baseURL') . $src . '"'; @@ -422,7 +422,7 @@ function _media(string $name, array $types = [], string $unsupportedMessage = '' function source(string $src, string $type = 'unknown', string $attributes = '', bool $indexPage = false): string { if (! _has_protocol($src)) { - $src = $indexPage === true ? site_url($src) : slash_item('baseURL') . $src; + $src = $indexPage ? site_url($src) : slash_item('baseURL') . $src; } $source = 'width ?? 0) . 'x' . ($this->height ?? 0) . "{$escape}! \"" . $source . '" "' . $destination . '"'; diff --git a/system/Images/Image.php b/system/Images/Image.php index a2cf51436121..ec6d4b8fa5c0 100644 --- a/system/Images/Image.php +++ b/system/Images/Image.php @@ -116,7 +116,7 @@ public function getProperties(bool $return = false) $mime = 'image/' . ($types[$vals[2]] ?? 'jpg'); - if ($return === true) { + if ($return) { return [ 'width' => $vals[0], 'height' => $vals[1], diff --git a/system/Log/Handlers/FileHandler.php b/system/Log/Handlers/FileHandler.php index 42dd9ceefc0f..64d1485f0f7a 100644 --- a/system/Log/Handlers/FileHandler.php +++ b/system/Log/Handlers/FileHandler.php @@ -76,6 +76,7 @@ public function handle($level, $message): bool $msg = ''; + $newfile = false; if (! is_file($filepath)) { $newfile = true; @@ -117,7 +118,7 @@ public function handle($level, $message): bool flock($fp, LOCK_UN); fclose($fp); - if (isset($newfile) && $newfile === true) { + if ($newfile) { chmod($filepath, $this->filePermissions); } diff --git a/system/Pager/Pager.php b/system/Pager/Pager.php index af0e9accfaee..e5fbb9df5b34 100644 --- a/system/Pager/Pager.php +++ b/system/Pager/Pager.php @@ -288,7 +288,7 @@ public function getPageURI(?int $page = null, string $group = 'default', bool $r $uri->setQueryArray($query); } - return ($returnObject === true) + return ($returnObject) ? $uri : URI::createURIString( $uri->getScheme(), diff --git a/system/Router/AutoRouter.php b/system/Router/AutoRouter.php index 6e9f3248c86e..bb47bf96c89a 100644 --- a/system/Router/AutoRouter.php +++ b/system/Router/AutoRouter.php @@ -260,7 +260,7 @@ public function setDirectory(?string $dir = null, bool $append = false, bool $va } } - if ($append !== true || ($this->directory === null || $this->directory === '')) { + if (! $append || ($this->directory === null || $this->directory === '')) { $this->directory = trim($dir, '/') . '/'; } else { $this->directory .= trim($dir, '/') . '/'; diff --git a/system/Typography/Typography.php b/system/Typography/Typography.php index 89687d72e2d1..c8ca5131171c 100644 --- a/system/Typography/Typography.php +++ b/system/Typography/Typography.php @@ -214,7 +214,7 @@ public function autoTypography(string $str, bool $reduceLinebreaks = false): str ]; // Do we need to reduce empty lines? - if ($reduceLinebreaks === true) { + if ($reduceLinebreaks) { $table['#

\n*

#'] = ''; } else { // If we have empty paragraph tags we add a non-breaking space diff --git a/system/Validation/Validation.php b/system/Validation/Validation.php index a4d817d2a9b4..66ed1f8e48a3 100644 --- a/system/Validation/Validation.php +++ b/system/Validation/Validation.php @@ -456,7 +456,7 @@ private function processPermitEmpty($value, array $rules, array $data) } } - if ($passed === true) { + if ($passed) { return true; } } From 3f8feaa5893e30509fa21edafbdcdb478f3fabd0 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Wed, 30 Oct 2024 16:41:24 +0700 Subject: [PATCH 038/108] refactor: clean up parentheses on assign and ternary --- system/Database/BaseConnection.php | 2 +- system/Database/MySQLi/Connection.php | 2 +- system/Helpers/form_helper.php | 6 +++--- system/Pager/Pager.php | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/system/Database/BaseConnection.php b/system/Database/BaseConnection.php index 487f01df4ccb..65bf6fcdbdac 100644 --- a/system/Database/BaseConnection.php +++ b/system/Database/BaseConnection.php @@ -848,7 +848,7 @@ public function transBegin(bool $testMode = false): bool // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. - $this->transFailure = ($testMode); + $this->transFailure = $testMode; if ($this->_transBegin()) { $this->transDepth++; diff --git a/system/Database/MySQLi/Connection.php b/system/Database/MySQLi/Connection.php index 6524d95b41f1..b1095003e286 100644 --- a/system/Database/MySQLi/Connection.php +++ b/system/Database/MySQLi/Connection.php @@ -96,7 +96,7 @@ public function connect(bool $persistent = false) $port = null; $socket = $this->hostname; } else { - $hostname = ($persistent) ? 'p:' . $this->hostname : $this->hostname; + $hostname = $persistent ? 'p:' . $this->hostname : $this->hostname; $port = empty($this->port) ? null : $this->port; $socket = ''; } diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index 422c5f1adbb2..58cd828e3faa 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -582,7 +582,7 @@ function set_select(string $field, string $value = '', bool $default = false): s } if ($input === null) { - return ($default) ? ' selected="selected"' : ''; + return $default ? ' selected="selected"' : ''; } if (is_array($input)) { @@ -636,7 +636,7 @@ function set_checkbox(string $field, string $value = '', bool $default = false): return ($input === $value) ? ' checked="checked"' : ''; } - return ($default) ? ' checked="checked"' : ''; + return $default ? ' checked="checked"' : ''; } } @@ -673,7 +673,7 @@ function set_radio(string $field, string $value = '', bool $default = false): st return ((string) $input === $value) ? ' checked="checked"' : ''; } - return ($default) ? ' checked="checked"' : ''; + return $default ? ' checked="checked"' : ''; } } diff --git a/system/Pager/Pager.php b/system/Pager/Pager.php index e5fbb9df5b34..3bdc85388c18 100644 --- a/system/Pager/Pager.php +++ b/system/Pager/Pager.php @@ -288,7 +288,7 @@ public function getPageURI(?int $page = null, string $group = 'default', bool $r $uri->setQueryArray($query); } - return ($returnObject) + return $returnObject ? $uri : URI::createURIString( $uri->getScheme(), From 3d0f9f2b30322b542aff810a18697a2a52091259 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9ssica=20Pereira?= <14842802+CosDiabos@users.noreply.github.com> Date: Sun, 3 Nov 2024 18:44:55 +0100 Subject: [PATCH 039/108] fix: Parser - Equal key name replace conflict (#9246) * Parse equal key name replace * fix: parsing equal key name replace for parser * improved code readability Co-authored-by: Mostafa Khudair <59371810+mostafakhudair@users.noreply.github.com> * updated changelog --------- Co-authored-by: Mostafa Khudair <59371810+mostafakhudair@users.noreply.github.com> --- system/View/Parser.php | 33 +++++++++++++---- tests/system/View/ParserTest.php | 40 +++++++++++++++++++++ user_guide_src/source/changelogs/v4.5.6.rst | 2 ++ 3 files changed, 68 insertions(+), 7 deletions(-) diff --git a/system/View/Parser.php b/system/View/Parser.php index 6600b0178369..8a26cf825d3f 100644 --- a/system/View/Parser.php +++ b/system/View/Parser.php @@ -254,20 +254,39 @@ protected function parse(string $template, array $data = [], ?array $options = n // it can potentially modify any template between its tags. $template = $this->parsePlugins($template); - // loop over the data variables, replacing - // the content as we go. + // Parse stack for each parse type (Single and Pairs) + $replaceSingleStack = []; + $replacePairsStack = []; + + // loop over the data variables, saving regex and data + // for later replacement. foreach ($data as $key => $val) { $escape = true; if (is_array($val)) { - $escape = false; - $replace = $this->parsePair($key, $val, $template); + $escape = false; + $replacePairsStack[] = [ + 'replace' => $this->parsePair($key, $val, $template), + 'escape' => $escape, + ]; } else { - $replace = $this->parseSingle($key, (string) $val); + $replaceSingleStack[] = [ + 'replace' => $this->parseSingle($key, (string) $val), + 'escape' => $escape, + ]; } + } + + // Merge both stacks, pairs first + single stacks + // This allows for nested data with the same key to be replaced properly + $replace = array_merge($replacePairsStack, $replaceSingleStack); - foreach ($replace as $pattern => $content) { - $template = $this->replaceSingle($pattern, $content, $template, $escape); + // Loop over each replace array item which + // holds all the data to be replaced + foreach ($replace as $replaceItem) { + // Loop over the actual data to be replaced + foreach ($replaceItem['replace'] as $pattern => $content) { + $template = $this->replaceSingle($pattern, $content, $template, $replaceItem['escape']); } } diff --git a/tests/system/View/ParserTest.php b/tests/system/View/ParserTest.php index 9a9f1fd8d0ac..b3c99a2872ce 100644 --- a/tests/system/View/ParserTest.php +++ b/tests/system/View/ParserTest.php @@ -1061,4 +1061,44 @@ public function testChangeConditionalDelimitersWorkWithJavaScriptCode(): void EOL; $this->assertSame($expected, $this->parser->renderString($template)); } + + /** + * @see https://github.com/codeigniter4/CodeIgniter4/issues/9245 + */ + public function testParseSameArrayKeyName(): void + { + $data = [ + 'type' => 'Super Powers', + 'powers' => [ + [ + 'type' => 'invisibility', + ], + ], + ]; + + $template = '{type} like {powers}{type}{/powers}'; + + $this->parser->setData($data); + $this->assertSame('Super Powers like invisibility', $this->parser->renderString($template)); + } + + public function testParseSameArrayKeyNameNested(): void + { + $data = [ + 'title' => 'My title', + 'similar' => [ + ['items' => [ + [ + 'title' => 'My similar title', + ], + ], + ], + ], + ]; + + $template = '{title} with similar item {similar}{items}{title}{/items}{/similar}'; + + $this->parser->setData($data); + $this->assertSame('My title with similar item My similar title', $this->parser->renderString($template)); + } } diff --git a/user_guide_src/source/changelogs/v4.5.6.rst b/user_guide_src/source/changelogs/v4.5.6.rst index b982f54b38f7..c2f396627442 100644 --- a/user_guide_src/source/changelogs/v4.5.6.rst +++ b/user_guide_src/source/changelogs/v4.5.6.rst @@ -33,6 +33,8 @@ Bugs Fixed - **Validation:** Fixed the `getValidated()` method that did not return valid data when validation rules used multiple asterisks. +- **Parser:** Fixed bug that caused equal key names to be replaced by the key name defined first. + See the repo's `CHANGELOG.md `_ for a complete list of bugs fixed. From fc19b690f847e943fe56ce0898f3f78d04965625 Mon Sep 17 00:00:00 2001 From: Michal Sniatala Date: Sun, 3 Nov 2024 19:48:50 +0100 Subject: [PATCH 040/108] fix: case-insensitivity in the `like()` method when in use with accented characters (#9238) * fix: case-insensitivity in the like() method when in use with accented characters * Update system/Database/BaseBuilder.php Co-authored-by: Pooya Parsa * add more cases for tests * even more tests * fix types * set collation for sqlsrv --------- Co-authored-by: Pooya Parsa --- .github/workflows/reusable-phpunit-test.yml | 2 +- system/Database/BaseBuilder.php | 2 +- system/Database/SQLSRV/Forge.php | 8 +++---- .../20160428212500_Create_test_tables.php | 1 + .../_support/Database/Seeds/CITestSeeder.php | 20 ++++++++++++++++ tests/system/Database/Live/ForgeTest.php | 12 +++++++--- tests/system/Database/Live/GetTest.php | 2 +- tests/system/Database/Live/LikeTest.php | 24 +++++++++++++++++++ user_guide_src/source/changelogs/v4.5.6.rst | 1 + 9 files changed, 62 insertions(+), 10 deletions(-) diff --git a/.github/workflows/reusable-phpunit-test.yml b/.github/workflows/reusable-phpunit-test.yml index 84ade1d08862..9758d6eb5410 100644 --- a/.github/workflows/reusable-phpunit-test.yml +++ b/.github/workflows/reusable-phpunit-test.yml @@ -138,7 +138,7 @@ jobs: steps: - name: Create database for MSSQL Server if: ${{ inputs.db-platform == 'SQLSRV' }} - run: sqlcmd -S 127.0.0.1 -U sa -P 1Secure*Password1 -Q "CREATE DATABASE test" + run: sqlcmd -S 127.0.0.1 -U sa -P 1Secure*Password1 -Q "CREATE DATABASE test COLLATE Latin1_General_100_CS_AS_SC_UTF8" - name: Install latest ImageMagick if: ${{ contains(inputs.extra-extensions, 'imagick') }} diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index 570340dffb9b..892dd903b690 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -1151,7 +1151,7 @@ protected function _like($field, string $match = '', string $type = 'AND ', stri foreach ($keyValue as $k => $v) { if ($insensitiveSearch) { - $v = strtolower($v); + $v = mb_strtolower($v, 'UTF-8'); } $prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type); diff --git a/system/Database/SQLSRV/Forge.php b/system/Database/SQLSRV/Forge.php index 3bfda3bfe895..d121560c9d47 100644 --- a/system/Database/SQLSRV/Forge.php +++ b/system/Database/SQLSRV/Forge.php @@ -212,10 +212,10 @@ protected function _alterTable(string $alterType, string $table, $processedField $sql = <<db->DBDriver === 'SQLSRV') { unset($dataTypeFields['type_timestamp']); + $dataTypeFields['type_text'] = ['type' => 'NVARCHAR(max)', 'null' => true]; } if ($this->db->DBDriver === 'Postgre' || $this->db->DBDriver === 'SQLSRV') { diff --git a/tests/_support/Database/Seeds/CITestSeeder.php b/tests/_support/Database/Seeds/CITestSeeder.php index f8582839cf05..45b70a7fdd19 100644 --- a/tests/_support/Database/Seeds/CITestSeeder.php +++ b/tests/_support/Database/Seeds/CITestSeeder.php @@ -86,6 +86,26 @@ public function run(): void 'key' => 'key', 'value' => 'value', ], + [ + 'key' => 'multibyte characters pl', + 'value' => 'śćźżłąęó', + ], + [ + 'key' => 'multibyte characters fa', + 'value' => 'خٌوب', + ], + [ + 'key' => 'multibyte characters bn', + 'value' => 'টাইপ', + ], + [ + 'key' => 'multibyte characters ko', + 'value' => '캐스팅', + ], + [ + 'key' => 'multibyte characters ml', + 'value' => 'ടൈപ്പ്', + ], ], 'type_test' => [ [ diff --git a/tests/system/Database/Live/ForgeTest.php b/tests/system/Database/Live/ForgeTest.php index 7fccd6b1d298..64d8dbd7e576 100644 --- a/tests/system/Database/Live/ForgeTest.php +++ b/tests/system/Database/Live/ForgeTest.php @@ -1615,9 +1615,15 @@ public function testDropKey(): void public function testAddTextColumnWithConstraint(): void { // some DBMS do not allow a constraint for type TEXT - $this->forge->addColumn('user', [ - 'text_with_constraint' => ['type' => 'text', 'constraint' => 255, 'default' => ''], - ]); + if ($this->db->DBDriver === 'SQLSRV') { + $this->forge->addColumn('user', [ + 'text_with_constraint' => ['type' => 'nvarchar(max)', 'default' => ''], + ]); + } else { + $this->forge->addColumn('user', [ + 'text_with_constraint' => ['type' => 'text', 'constraint' => 255, 'default' => ''], + ]); + } $this->assertTrue($this->db->fieldExists('text_with_constraint', 'user')); diff --git a/tests/system/Database/Live/GetTest.php b/tests/system/Database/Live/GetTest.php index 681af7344183..ce98ebf413e0 100644 --- a/tests/system/Database/Live/GetTest.php +++ b/tests/system/Database/Live/GetTest.php @@ -178,7 +178,7 @@ public function testGetFieldData(): void $this->assertSame('int', $typeTest[0]->type_name); // INTEGER AUTOINC $this->assertSame('varchar', $typeTest[1]->type_name); // VARCHAR $this->assertSame('char', $typeTest[2]->type_name); // CHAR - $this->assertSame('text', $typeTest[3]->type_name); // TEXT + $this->assertSame('nvarchar', $typeTest[3]->type_name); // TEXT $this->assertSame('smallint', $typeTest[4]->type_name); // SMALLINT $this->assertSame('int', $typeTest[5]->type_name); // INTEGER $this->assertSame('float', $typeTest[6]->type_name); // FLOAT diff --git a/tests/system/Database/Live/LikeTest.php b/tests/system/Database/Live/LikeTest.php index 5884f9d01220..9591eef72ea8 100644 --- a/tests/system/Database/Live/LikeTest.php +++ b/tests/system/Database/Live/LikeTest.php @@ -16,6 +16,7 @@ use CodeIgniter\Database\RawSql; use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\DatabaseTestTrait; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use Tests\Support\Database\Seeds\CITestSeeder; @@ -75,6 +76,29 @@ public function testLikeCaseInsensitive(): void $this->assertSame('Developer', $job->name); } + #[DataProvider('provideMultibyteCharacters')] + public function testLikeCaseInsensitiveWithMultibyteCharacter(string $match, string $result): void + { + $wai = $this->db->table('without_auto_increment')->like('value', $match, 'both', null, true)->get(); + $wai = $wai->getRow(); + + $this->assertSame($result, $wai->key); + } + + /** + * @return iterable + */ + public static function provideMultibyteCharacters(): iterable + { + yield from [ + 'polish' => ['ŁĄ', 'multibyte characters pl'], + 'farsi' => ['خٌوب', 'multibyte characters fa'], + 'bengali' => ['টাইপ', 'multibyte characters bn'], + 'korean' => ['캐스팅', 'multibyte characters ko'], + 'malayalam' => ['ടൈപ്പ്', 'multibyte characters ml'], + ]; + } + public function testOrLike(): void { $jobs = $this->db->table('job')->like('name', 'ian') diff --git a/user_guide_src/source/changelogs/v4.5.6.rst b/user_guide_src/source/changelogs/v4.5.6.rst index c2f396627442..44b11b724cb9 100644 --- a/user_guide_src/source/changelogs/v4.5.6.rst +++ b/user_guide_src/source/changelogs/v4.5.6.rst @@ -32,6 +32,7 @@ Bugs Fixed - **Session Library:** The session initialization debug message now uses the correct log type "debug" instead of "info". - **Validation:** Fixed the `getValidated()` method that did not return valid data when validation rules used multiple asterisks. +- **Database:** Fixed the case insensitivity option in the ``like()`` method when dealing with accented characters. - **Parser:** Fixed bug that caused equal key names to be replaced by the key name defined first. From 34358721a0df79d1bf20f3049d0886b88d5251f1 Mon Sep 17 00:00:00 2001 From: maniaba <61078470+maniaba@users.noreply.github.com> Date: Sun, 3 Nov 2024 20:14:42 +0100 Subject: [PATCH 041/108] fix: TypeError for routes when translateURIDashes is enabled (#9209) * fix: TypeError for OPTIONS routes when translateURIDashes is enabled * docs: Update changelog for v4.5.6 --- system/Router/Router.php | 2 +- tests/system/Router/RouterTest.php | 18 ++++++++++++++++++ user_guide_src/source/changelogs/v4.5.6.rst | 2 ++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/system/Router/Router.php b/system/Router/Router.php index 2bb050de30ae..0cd1614991ee 100644 --- a/system/Router/Router.php +++ b/system/Router/Router.php @@ -247,7 +247,7 @@ public function getFilters(): array */ public function controllerName() { - return $this->translateURIDashes + return $this->translateURIDashes && ! $this->controller instanceof Closure ? str_replace('-', '_', $this->controller) : $this->controller; } diff --git a/tests/system/Router/RouterTest.php b/tests/system/Router/RouterTest.php index bb5302e721dc..5d51bf2fd38c 100644 --- a/tests/system/Router/RouterTest.php +++ b/tests/system/Router/RouterTest.php @@ -13,6 +13,7 @@ namespace CodeIgniter\Router; +use Closure; use CodeIgniter\Config\Factories; use CodeIgniter\Config\Services; use CodeIgniter\Exceptions\PageNotFoundException; @@ -69,6 +70,7 @@ private function createRouteCollection(?Routing $routingConfig = null): void 'posts/(:num)/edit' => 'Blog::edit/$1', 'books/(:num)/(:alpha)/(:num)' => 'Blog::show/$3/$1', 'closure/(:num)/(:alpha)' => static fn ($num, $str) => $num . '-' . $str, + 'closure-dash/(:num)/(:alpha)' => static fn ($num, $str) => $num . '-' . $str, '{locale}/pages' => 'App\Pages::list_all', 'test/(:any)/lang/{locale}' => 'App\Pages::list_all', 'admin/admins' => 'App\Admin\Admins::list_all', @@ -216,6 +218,22 @@ public function testClosures(): void $this->assertSame($expects, '123-alpha'); } + public function testClosuresWithTranslateURIDashes(): void + { + $router = new Router($this->collection, $this->request); + $router->setTranslateURIDashes(true); + + $router->handle('closure-dash/123/alpha'); + $closure = $router->controllerName(); + + $this->assertInstanceOf(Closure::class, $closure); + + $expects = $closure(...$router->params()); + + $this->assertIsCallable($router->controllerName()); + $this->assertSame($expects, '123-alpha'); + } + public function testAutoRouteFindsDefaultControllerAndMethod(): void { $this->collection->setAutoRoute(true); diff --git a/user_guide_src/source/changelogs/v4.5.6.rst b/user_guide_src/source/changelogs/v4.5.6.rst index 44b11b724cb9..2ea1f1ce46b7 100644 --- a/user_guide_src/source/changelogs/v4.5.6.rst +++ b/user_guide_src/source/changelogs/v4.5.6.rst @@ -36,6 +36,8 @@ Bugs Fixed - **Parser:** Fixed bug that caused equal key names to be replaced by the key name defined first. +- **Routing:** Fixed a TypeError in `str_replace()` when `Routing::$translateURIDashes` is set to `true` and a route is defined using a closure. + See the repo's `CHANGELOG.md `_ for a complete list of bugs fixed. From 3e672fadc6d5277d085ab17cb850db54ef008859 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Tue, 5 Nov 2024 05:03:14 +0700 Subject: [PATCH 042/108] refactor: enable FlipTypeControlToUseExclusiveTypeRector --- rector.php | 2 ++ system/CodeIgniter.php | 2 +- system/Common.php | 2 +- system/Database/BaseConnection.php | 2 +- system/Database/Migration.php | 2 +- system/Database/Seeder.php | 2 +- system/HTTP/DownloadResponse.php | 4 ++-- system/HTTP/Exceptions/RedirectException.php | 2 +- system/HTTP/Negotiate.php | 2 +- system/HTTP/SiteURI.php | 2 +- system/Log/Handlers/ChromeLoggerHandler.php | 2 +- system/Validation/FileRules.php | 2 +- tests/system/API/ResponseTraitTest.php | 2 +- utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php | 2 +- 14 files changed, 16 insertions(+), 14 deletions(-) diff --git a/rector.php b/rector.php index 89647759b914..be9e45f1e169 100644 --- a/rector.php +++ b/rector.php @@ -19,6 +19,7 @@ use Rector\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector; use Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector; use Rector\CodeQuality\Rector\FunctionLike\SimplifyUselessVariableRector; +use Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector; use Rector\CodeQuality\Rector\Identical\SimplifyBoolIdenticalTrueRector; use Rector\CodeQuality\Rector\If_\CombineIfRector; use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector; @@ -213,6 +214,7 @@ TypedPropertyFromAssignsRector::class, ClosureReturnTypeRector::class, SimplifyBoolIdenticalTrueRector::class, + FlipTypeControlToUseExclusiveTypeRector::class, ]) ->withConfiguredRule(StringClassNameToClassConstantRector::class, [ // keep '\\' prefix string on string '\Foo\Bar' diff --git a/system/CodeIgniter.php b/system/CodeIgniter.php index 48fbc9d77e23..359e3ff7d08d 100644 --- a/system/CodeIgniter.php +++ b/system/CodeIgniter.php @@ -819,7 +819,7 @@ protected function tryToRouteIt(?RouteCollectionInterface $routes = null) { $this->benchmark->start('routing'); - if ($routes === null) { + if (! $routes instanceof RouteCollectionInterface) { $routes = service('routes')->loadRoutes(); } diff --git a/system/Common.php b/system/Common.php index dcc9487c588f..94ecc75e9841 100644 --- a/system/Common.php +++ b/system/Common.php @@ -869,7 +869,7 @@ function _solidus(?DocTypes $docTypesConfig = null): string { static $docTypes = null; - if ($docTypesConfig !== null) { + if ($docTypesConfig instanceof DocTypes) { $docTypes = $docTypesConfig; } diff --git a/system/Database/BaseConnection.php b/system/Database/BaseConnection.php index 65bf6fcdbdac..c60c2e72c680 100644 --- a/system/Database/BaseConnection.php +++ b/system/Database/BaseConnection.php @@ -684,7 +684,7 @@ public function query(string $sql, $binds = null, bool $setEscapeFlags = true, s // Let others do something with this query. Events::trigger('DBQuery', $query); - if ($exception !== null) { + if ($exception instanceof DatabaseException) { throw new DatabaseException( $exception->getMessage(), $exception->getCode(), diff --git a/system/Database/Migration.php b/system/Database/Migration.php index 4386b7448e80..ca9e5e0cf266 100644 --- a/system/Database/Migration.php +++ b/system/Database/Migration.php @@ -45,7 +45,7 @@ public function __construct(?Forge $forge = null) { if (isset($this->DBGroup)) { $this->forge = Database::forge($this->DBGroup); - } elseif ($forge !== null) { + } elseif ($forge instanceof Forge) { $this->forge = $forge; } else { $this->forge = Database::forge(config(Database::class)->defaultGroup); diff --git a/system/Database/Seeder.php b/system/Database/Seeder.php index be7cfcdf8a8c..c70a34b45e9f 100644 --- a/system/Database/Seeder.php +++ b/system/Database/Seeder.php @@ -105,7 +105,7 @@ public function __construct(Database $config, ?BaseConnection $db = null) */ public static function faker(): ?Generator { - if (self::$faker === null && class_exists(Factory::class)) { + if (! self::$faker instanceof Generator && class_exists(Factory::class)) { self::$faker = Factory::create(); } diff --git a/system/HTTP/DownloadResponse.php b/system/HTTP/DownloadResponse.php index 56953823693d..13a1e2b2feaa 100644 --- a/system/HTTP/DownloadResponse.php +++ b/system/HTTP/DownloadResponse.php @@ -85,7 +85,7 @@ public function __construct(string $filename, bool $setMime) */ public function setBinary(string $binary) { - if ($this->file !== null) { + if ($this->file instanceof File) { throw DownloadException::forCannotSetBinary(); } @@ -309,7 +309,7 @@ public function sendBody() return $this->sendBodyByBinary(); } - if ($this->file !== null) { + if ($this->file instanceof File) { return $this->sendBodyByFilePath(); } diff --git a/system/HTTP/Exceptions/RedirectException.php b/system/HTTP/Exceptions/RedirectException.php index 5f2dcd05e3b7..3047bf9603eb 100644 --- a/system/HTTP/Exceptions/RedirectException.php +++ b/system/HTTP/Exceptions/RedirectException.php @@ -69,7 +69,7 @@ public function __construct($message = '', int $code = 0, ?Throwable $previous = public function getResponse(): ResponseInterface { - if (null === $this->response) { + if (! $this->response instanceof ResponseInterface) { $this->response = service('response') ->redirect(base_url($this->getMessage()), 'auto', $this->getCode()); } diff --git a/system/HTTP/Negotiate.php b/system/HTTP/Negotiate.php index 4f218347738d..33938c8f0741 100644 --- a/system/HTTP/Negotiate.php +++ b/system/HTTP/Negotiate.php @@ -39,7 +39,7 @@ class Negotiate */ public function __construct(?RequestInterface $request = null) { - if ($request !== null) { + if ($request instanceof RequestInterface) { assert($request instanceof IncomingRequest); $this->request = $request; diff --git a/system/HTTP/SiteURI.php b/system/HTTP/SiteURI.php index ab0cdd19c955..91b14bc05456 100644 --- a/system/HTTP/SiteURI.php +++ b/system/HTTP/SiteURI.php @@ -421,7 +421,7 @@ public function siteUrl($relativePath = '', ?string $scheme = null, ?App $config $relativePath = $this->stringifyRelativePath($relativePath); // Check current host. - $host = $config === null ? $this->getHost() : null; + $host = ! $config instanceof App ? $this->getHost() : null; $config ??= config(App::class); diff --git a/system/Log/Handlers/ChromeLoggerHandler.php b/system/Log/Handlers/ChromeLoggerHandler.php index 8d39d4c06705..192f7f2951b8 100644 --- a/system/Log/Handlers/ChromeLoggerHandler.php +++ b/system/Log/Handlers/ChromeLoggerHandler.php @@ -156,7 +156,7 @@ protected function format($object) */ public function sendLogs(?ResponseInterface &$response = null) { - if ($response === null) { + if (! $response instanceof ResponseInterface) { $response = Services::response(null, true); } diff --git a/system/Validation/FileRules.php b/system/Validation/FileRules.php index dd8c4290e11d..78d0ce521809 100644 --- a/system/Validation/FileRules.php +++ b/system/Validation/FileRules.php @@ -38,7 +38,7 @@ class FileRules */ public function __construct(?RequestInterface $request = null) { - if ($request === null) { + if (! $request instanceof RequestInterface) { $request = service('request'); } diff --git a/tests/system/API/ResponseTraitTest.php b/tests/system/API/ResponseTraitTest.php index 82229b014bd4..25cccfbfca2a 100644 --- a/tests/system/API/ResponseTraitTest.php +++ b/tests/system/API/ResponseTraitTest.php @@ -87,7 +87,7 @@ private function createRequestAndResponse(string $routePath = '', array $userHea $config = $this->createAppConfig(); $this->createCookieConfig(); - if ($this->request === null) { + if (! $this->request instanceof MockIncomingRequest) { $this->request = new MockIncomingRequest( $config, new SiteURI($config, $routePath), diff --git a/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php b/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php index ec454b0e017f..25d09fadacb6 100644 --- a/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php +++ b/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php @@ -164,7 +164,7 @@ private function processRenameVariable(Node $node): ?Variable private function updateDocblock(string $variableName, string $camelCaseName, ?FunctionLike $functionLike): void { - if ($functionLike === null) { + if (! $functionLike instanceof FunctionLike) { return; } From 9773ed11ad134a79492dc4bdf59384d352df81c5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 5 Nov 2024 15:04:03 +0000 Subject: [PATCH 043/108] chore(deps-dev): update rector/rector requirement from 1.2.8 to 1.2.9 Updates the requirements on [rector/rector](https://github.com/rectorphp/rector) to permit the latest version. - [Release notes](https://github.com/rectorphp/rector/releases) - [Commits](https://github.com/rectorphp/rector/compare/1.2.8...1.2.9) --- updated-dependencies: - dependency-name: rector/rector dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index e6533a6daea1..34178265c11c 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": "1.2.8" + "rector/rector": "1.2.9" }, "replace": { "codeigniter4/framework": "self.version" From e63774d93239d9726d132ff7d7068a31047a363d Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Tue, 5 Nov 2024 22:10:16 +0700 Subject: [PATCH 044/108] skip NarrowUnusedSetUpDefinedPropertyRector as buggy with default value Signed-off-by: Abdul Malik Ikhsan --- rector.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rector.php b/rector.php index be9e45f1e169..a251d6e80595 100644 --- a/rector.php +++ b/rector.php @@ -59,6 +59,7 @@ use Utils\Rector\PassStrictParameterToFunctionParameterRector; use Utils\Rector\RemoveErrorSuppressInTryCatchStmtsRector; use Utils\Rector\UnderscoreToCamelCaseVariableNameRector; +use Rector\PHPUnit\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector; return RectorConfig::configure() ->withPhpSets(php81: true) @@ -176,6 +177,9 @@ // Unnecessary (string) is inserted NullToStrictStringFuncCallArgRector::class, + + // buggy with default value + NarrowUnusedSetUpDefinedPropertyRector::class, ]) // auto import fully qualified class names ->withImportNames(removeUnusedImports: true) From a933bf79bd2c2f0460fe92b2d5a9216d9d51e32d Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Tue, 5 Nov 2024 22:11:19 +0700 Subject: [PATCH 045/108] run cs fix on rector.php Signed-off-by: Abdul Malik Ikhsan --- rector.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rector.php b/rector.php index a251d6e80595..6a4a37835fc4 100644 --- a/rector.php +++ b/rector.php @@ -43,6 +43,7 @@ use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector; use Rector\Php80\Rector\FunctionLike\MixedTypeRector; use Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector; +use Rector\PHPUnit\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector; use Rector\PHPUnit\CodeQuality\Rector\Class_\YieldDataProviderRector; use Rector\PHPUnit\Set\PHPUnitSetList; use Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector; @@ -59,7 +60,6 @@ use Utils\Rector\PassStrictParameterToFunctionParameterRector; use Utils\Rector\RemoveErrorSuppressInTryCatchStmtsRector; use Utils\Rector\UnderscoreToCamelCaseVariableNameRector; -use Rector\PHPUnit\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector; return RectorConfig::configure() ->withPhpSets(php81: true) From 17813089a2bcb827d43c13e5f8109b36a5fd03d2 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Wed, 6 Nov 2024 05:44:07 +0700 Subject: [PATCH 046/108] refactor: Move property to local variable on usage only in setUp() method in tests --- tests/system/CLI/ConsoleTest.php | 6 ++---- tests/system/Cache/Handlers/MemcachedHandlerTest.php | 6 ++---- tests/system/CodeIgniterTest.php | 1 - tests/system/Config/DotEnvTest.php | 5 ++--- tests/system/ControllerTest.php | 7 +++---- tests/system/Files/FileWithVfsTest.php | 5 ++--- tests/system/HTTP/Files/FileMovingTest.php | 10 ++++------ tests/system/Helpers/CookieHelperTest.php | 5 ++--- tests/system/Images/BaseHandlerTest.php | 10 ++++------ tests/system/Images/ImageTest.php | 5 ++--- tests/system/Log/Handlers/FileHandlerTest.php | 6 ++---- tests/system/Publisher/PublisherOutputTest.php | 9 ++------- tests/system/View/CellTest.php | 5 ++--- 13 files changed, 29 insertions(+), 51 deletions(-) diff --git a/tests/system/CLI/ConsoleTest.php b/tests/system/CLI/ConsoleTest.php index cabe2152b684..c6773a07894f 100644 --- a/tests/system/CLI/ConsoleTest.php +++ b/tests/system/CLI/ConsoleTest.php @@ -30,14 +30,12 @@ final class ConsoleTest extends CIUnitTestCase { use StreamFilterTrait; - private DotEnv $env; - protected function setUp(): void { parent::setUp(); - $this->env = new DotEnv(ROOTPATH); - $this->env->load(); + $env = new DotEnv(ROOTPATH); + $env->load(); // Set environment values that would otherwise stop the framework from functioning during tests. if (! isset($_SERVER['app.baseURL'])) { diff --git a/tests/system/Cache/Handlers/MemcachedHandlerTest.php b/tests/system/Cache/Handlers/MemcachedHandlerTest.php index 4aad8288401c..45a44b64feff 100644 --- a/tests/system/Cache/Handlers/MemcachedHandlerTest.php +++ b/tests/system/Cache/Handlers/MemcachedHandlerTest.php @@ -25,8 +25,6 @@ #[Group('CacheLive')] final class MemcachedHandlerTest extends AbstractHandlerTestCase { - private Cache $config; - private static function getKeyArray() { return [ @@ -44,9 +42,9 @@ protected function setUp(): void $this->markTestSkipped('Memcached extension not loaded.'); } - $this->config = new Cache(); + $config = new Cache(); - $this->handler = new MemcachedHandler($this->config); + $this->handler = new MemcachedHandler($config); $this->handler->initialize(); } diff --git a/tests/system/CodeIgniterTest.php b/tests/system/CodeIgniterTest.php index d87d0d8661ba..2928777271fd 100644 --- a/tests/system/CodeIgniterTest.php +++ b/tests/system/CodeIgniterTest.php @@ -47,7 +47,6 @@ final class CodeIgniterTest extends CIUnitTestCase { private CodeIgniter $codeigniter; - protected $routes; #[WithoutErrorHandler] protected function setUp(): void diff --git a/tests/system/Config/DotEnvTest.php b/tests/system/Config/DotEnvTest.php index b2f8e8e947b7..6fd287be6ad5 100644 --- a/tests/system/Config/DotEnvTest.php +++ b/tests/system/Config/DotEnvTest.php @@ -32,7 +32,6 @@ final class DotEnvTest extends CIUnitTestCase { private ?vfsStreamDirectory $root; - private string $path; private string $fixturesFolder; #[WithoutErrorHandler] @@ -42,8 +41,8 @@ protected function setUp(): void $this->root = vfsStream::setup(); $this->fixturesFolder = $this->root->url(); - $this->path = TESTPATH . 'system/Config/fixtures'; - vfsStream::copyFromFileSystem($this->path, $this->root); + $path = TESTPATH . 'system/Config/fixtures'; + vfsStream::copyFromFileSystem($path, $this->root); $file = 'unreadable.env'; $path = rtrim($this->fixturesFolder, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file; diff --git a/tests/system/ControllerTest.php b/tests/system/ControllerTest.php index add07fc20dd4..ffdcd9589f8a 100644 --- a/tests/system/ControllerTest.php +++ b/tests/system/ControllerTest.php @@ -40,7 +40,6 @@ #[Group('Others')] final class ControllerTest extends CIUnitTestCase { - private App $config; private ?Controller $controller = null; /** @@ -59,9 +58,9 @@ protected function setUp(): void { parent::setUp(); - $this->config = new App(); - $this->request = new IncomingRequest($this->config, new SiteURI($this->config), null, new UserAgent()); - $this->response = new Response($this->config); + $config = new App(); + $this->request = new IncomingRequest($config, new SiteURI($config), null, new UserAgent()); + $this->response = new Response($config); $this->logger = Services::logger(); } diff --git a/tests/system/Files/FileWithVfsTest.php b/tests/system/Files/FileWithVfsTest.php index 9a1075ad9a1c..a6c26383d187 100644 --- a/tests/system/Files/FileWithVfsTest.php +++ b/tests/system/Files/FileWithVfsTest.php @@ -26,7 +26,6 @@ final class FileWithVfsTest extends CIUnitTestCase { // For VFS stuff private ?vfsStreamDirectory $root = null; - private string $path; private string $start; private File $file; @@ -35,8 +34,8 @@ protected function setUp(): void parent::setUp(); $this->root = vfsStream::setup(); - $this->path = '_support/Files/'; - vfsStream::copyFromFileSystem(TESTPATH . $this->path, $this->root); + $path = '_support/Files/'; + vfsStream::copyFromFileSystem(TESTPATH . $path, $this->root); $this->start = $this->root->url() . '/'; $this->file = new File($this->start . 'able/apple.php'); } diff --git a/tests/system/HTTP/Files/FileMovingTest.php b/tests/system/HTTP/Files/FileMovingTest.php index c07116970b5a..9624ecd78a06 100644 --- a/tests/system/HTTP/Files/FileMovingTest.php +++ b/tests/system/HTTP/Files/FileMovingTest.php @@ -26,8 +26,6 @@ final class FileMovingTest extends CIUnitTestCase { private ?vfsStreamDirectory $root; - private string $path; - private string $start; private string $destination; protected function setUp(): void @@ -35,11 +33,11 @@ protected function setUp(): void parent::setUp(); $this->root = vfsStream::setup(); - $this->path = '_support/Files/'; - vfsStream::copyFromFileSystem(TESTPATH . $this->path, $this->root); - $this->start = $this->root->url() . '/'; + $path = '_support/Files/'; + vfsStream::copyFromFileSystem(TESTPATH . $path, $this->root); + $start = $this->root->url() . '/'; - $this->destination = $this->start . 'destination'; + $this->destination = $start . 'destination'; if (is_dir($this->destination)) { rmdir($this->destination); } diff --git a/tests/system/Helpers/CookieHelperTest.php b/tests/system/Helpers/CookieHelperTest.php index 619a21717f86..b672e4da9104 100644 --- a/tests/system/Helpers/CookieHelperTest.php +++ b/tests/system/Helpers/CookieHelperTest.php @@ -33,7 +33,6 @@ #[Group('Others')] final class CookieHelperTest extends CIUnitTestCase { - private IncomingRequest $request; private string $name; private string $value; private int $expire; @@ -51,8 +50,8 @@ protected function setUp(): void Services::injectMock('response', new MockResponse(new App())); $this->response = Services::response(); - $this->request = new IncomingRequest(new App(), new SiteURI(new App()), null, new UserAgent()); - Services::injectMock('request', $this->request); + $request = new IncomingRequest(new App(), new SiteURI(new App()), null, new UserAgent()); + Services::injectMock('request', $request); helper('cookie'); } diff --git a/tests/system/Images/BaseHandlerTest.php b/tests/system/Images/BaseHandlerTest.php index 7332eba9031f..17bc3c00eb70 100644 --- a/tests/system/Images/BaseHandlerTest.php +++ b/tests/system/Images/BaseHandlerTest.php @@ -19,7 +19,6 @@ use CodeIgniter\Images\Handlers\BaseHandler; use CodeIgniter\Test\CIUnitTestCase; use org\bovigo\vfs\vfsStream; -use org\bovigo\vfs\vfsStreamDirectory; use PHPUnit\Framework\Attributes\Group; /** @@ -35,7 +34,6 @@ #[Group('Others')] final class BaseHandlerTest extends CIUnitTestCase { - private vfsStreamDirectory $root; private string $origin; private string $start; private string $path; @@ -47,10 +45,10 @@ protected function setUp(): void } // create virtual file system - $this->root = vfsStream::setup(); + $root = vfsStream::setup(); // copy our support files $this->origin = SUPPORTPATH . 'Images/'; - vfsStream::copyFromFileSystem($this->origin, $this->root); + vfsStream::copyFromFileSystem($this->origin, $root); // make subfolders $structure = [ 'work' => [], @@ -58,10 +56,10 @@ protected function setUp(): void ]; vfsStream::create($structure); // with one of them read only - $this->root->getChild('wontwork')->chmod(0400); + $root->getChild('wontwork')->chmod(0400); // for VFS tests - $this->start = $this->root->url() . '/'; + $this->start = $root->url() . '/'; $this->path = $this->start . 'ci-logo.png'; } diff --git a/tests/system/Images/ImageTest.php b/tests/system/Images/ImageTest.php index c4411dd7dedb..622a34ad3cc2 100644 --- a/tests/system/Images/ImageTest.php +++ b/tests/system/Images/ImageTest.php @@ -26,7 +26,6 @@ final class ImageTest extends CIUnitTestCase { private vfsStreamDirectory $root; - private string $origin; private string $start; private Image $image; @@ -35,8 +34,8 @@ protected function setUp(): void // create virtual file system $this->root = vfsStream::setup(); // copy our support files - $this->origin = '_support/Images/'; - vfsStream::copyFromFileSystem(TESTPATH . $this->origin, $this->root); + $origin = '_support/Images/'; + vfsStream::copyFromFileSystem(TESTPATH . $origin, $this->root); // make subfolders $structure = [ 'work' => [], diff --git a/tests/system/Log/Handlers/FileHandlerTest.php b/tests/system/Log/Handlers/FileHandlerTest.php index 7cf11c1f3cf9..6647a42c8b43 100644 --- a/tests/system/Log/Handlers/FileHandlerTest.php +++ b/tests/system/Log/Handlers/FileHandlerTest.php @@ -17,7 +17,6 @@ use CodeIgniter\Test\Mock\MockFileLogger; use CodeIgniter\Test\Mock\MockLogger as LoggerConfig; use org\bovigo\vfs\vfsStream; -use org\bovigo\vfs\vfsStreamDirectory; use PHPUnit\Framework\Attributes\Group; use Tests\Support\Log\Handlers\TestHandler; @@ -27,14 +26,13 @@ #[Group('Others')] final class FileHandlerTest extends CIUnitTestCase { - private vfsStreamDirectory $root; private string $start; protected function setUp(): void { parent::setUp(); - $this->root = vfsStream::setup('root'); - $this->start = $this->root->url() . '/'; + $root = vfsStream::setup('root'); + $this->start = $root->url() . '/'; } public function testHandle(): void diff --git a/tests/system/Publisher/PublisherOutputTest.php b/tests/system/Publisher/PublisherOutputTest.php index e03335e86fe6..02f4f75876e8 100644 --- a/tests/system/Publisher/PublisherOutputTest.php +++ b/tests/system/Publisher/PublisherOutputTest.php @@ -24,11 +24,6 @@ #[Group('Others')] final class PublisherOutputTest extends CIUnitTestCase { - /** - * Files to seed to VFS - */ - private array $structure; - /** * Virtual destination */ @@ -60,7 +55,7 @@ protected function setUp(): void { parent::setUp(); - $this->structure = [ + $structure = [ 'able' => [ 'apple.php' => 'Once upon a midnight dreary', 'bazam' => 'While I pondered weak and weary', @@ -74,7 +69,7 @@ protected function setUp(): void '.hidden' => 'There is no spoon', ]; - $this->root = vfsStream::setup('root', null, $this->structure); + $this->root = vfsStream::setup('root', null, $structure); // Add root to the list of allowed destinations config('Publisher')->restrictions[$this->root->url()] = '*'; diff --git a/tests/system/View/CellTest.php b/tests/system/View/CellTest.php index 27dd6512d174..64796d119c50 100644 --- a/tests/system/View/CellTest.php +++ b/tests/system/View/CellTest.php @@ -25,15 +25,14 @@ #[Group('Others')] final class CellTest extends CIUnitTestCase { - private MockCache $cache; private Cell $cell; protected function setUp(): void { parent::setUp(); - $this->cache = new MockCache(); - $this->cell = new Cell($this->cache); + $cache = new MockCache(); + $this->cell = new Cell($cache); } public function testPrepareParamsReturnsEmptyArrayWithInvalidParam(): void From 3f5d516a985d557cf86a1e9d022a867ee9682624 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Wed, 6 Nov 2024 05:46:22 +0700 Subject: [PATCH 047/108] refactor: move comment from property to assign --- tests/system/Publisher/PublisherOutputTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/system/Publisher/PublisherOutputTest.php b/tests/system/Publisher/PublisherOutputTest.php index 02f4f75876e8..0b9b744e01fd 100644 --- a/tests/system/Publisher/PublisherOutputTest.php +++ b/tests/system/Publisher/PublisherOutputTest.php @@ -55,6 +55,9 @@ protected function setUp(): void { parent::setUp(); + /** + * Files to seed to VFS + */ $structure = [ 'able' => [ 'apple.php' => 'Once upon a midnight dreary', From 8628f120383a82a21cd0273230dab38bbe612446 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Wed, 6 Nov 2024 05:47:05 +0700 Subject: [PATCH 048/108] refactor: regenerate phpstan baseline --- phpstan-baseline.php | 6 ------ 1 file changed, 6 deletions(-) diff --git a/phpstan-baseline.php b/phpstan-baseline.php index 2e6e8b31ec37..7c0fb2d51540 100644 --- a/phpstan-baseline.php +++ b/phpstan-baseline.php @@ -16429,12 +16429,6 @@ 'count' => 5, 'path' => __DIR__ . '/tests/system/Pager/PagerTest.php', ]; -$ignoreErrors[] = [ - // identifier: missingType.iterableValue - 'message' => '#^Property CodeIgniter\\\\Publisher\\\\PublisherOutputTest\\:\\:\\$structure type has no value type specified in iterable type array\\.$#', - 'count' => 1, - 'path' => __DIR__ . '/tests/system/Publisher/PublisherOutputTest.php', -]; $ignoreErrors[] = [ // identifier: missingType.iterableValue 'message' => '#^Method CodeIgniter\\\\Publisher\\\\PublisherRestrictionsTest\\:\\:provideDefaultPublicRestrictions\\(\\) return type has no value type specified in iterable type iterable\\.$#', From 17d5669f4563b2acc0fbd8a64995c132c4b8899e Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 8 Nov 2024 07:37:49 +0700 Subject: [PATCH 049/108] refactor: flip assert and actuals value on tests --- tests/system/Database/Live/ForgeTest.php | 70 +++++++++---------- .../Live/OCI8/CallStoredProcedureTest.php | 4 +- .../Database/Live/OCI8/LastInsertIDTest.php | 8 +-- tests/system/Files/FileCollectionTest.php | 2 +- tests/system/HTTP/ResponseCookieTest.php | 6 +- tests/system/Helpers/DateHelperTest.php | 2 +- tests/system/Helpers/TextHelperTest.php | 10 +-- tests/system/Models/EventsModelTest.php | 2 +- .../Models/ValidationModelRuleGroupTest.php | 12 ++-- tests/system/Models/ValidationModelTest.php | 12 ++-- tests/system/Pager/PagerTest.php | 12 ++-- tests/system/Router/RouteCollectionTest.php | 4 +- tests/system/Router/RouterTest.php | 8 +-- 13 files changed, 76 insertions(+), 76 deletions(-) diff --git a/tests/system/Database/Live/ForgeTest.php b/tests/system/Database/Live/ForgeTest.php index 64d8dbd7e576..9aecdd969c78 100644 --- a/tests/system/Database/Live/ForgeTest.php +++ b/tests/system/Database/Live/ForgeTest.php @@ -278,15 +278,15 @@ public function testCreateTableApplyBigInt(): void $fieldsData = $this->db->getFieldData('forge_test_table'); if ($this->db->DBDriver === 'MySQLi') { - $this->assertSame(strtolower($fieldsData[0]->type), 'bigint'); + $this->assertSame('bigint', strtolower($fieldsData[0]->type)); } elseif ($this->db->DBDriver === 'Postgre') { - $this->assertSame(strtolower($fieldsData[0]->type), 'bigint'); + $this->assertSame('bigint', strtolower($fieldsData[0]->type)); } elseif ($this->db->DBDriver === 'SQLite3') { - $this->assertSame(strtolower($fieldsData[0]->type), 'integer'); + $this->assertSame('integer', strtolower($fieldsData[0]->type)); } elseif ($this->db->DBDriver === 'OCI8') { - $this->assertSame(strtolower($fieldsData[0]->type), 'number'); + $this->assertSame('number', strtolower($fieldsData[0]->type)); } elseif ($this->db->DBDriver === 'SQLSRV') { - $this->assertSame(strtolower($fieldsData[0]->type), 'bigint'); + $this->assertSame('bigint', strtolower($fieldsData[0]->type)); } $this->forge->dropTable('forge_test_table', true); @@ -1166,65 +1166,65 @@ public function testCompositeKey(): void $keys = $this->db->getIndexData('forge_test_1'); if ($this->db->DBDriver === 'MySQLi') { - $this->assertSame($keys['PRIMARY']->name, 'PRIMARY'); + $this->assertSame('PRIMARY', $keys['PRIMARY']->name); $this->assertSame($keys['PRIMARY']->fields, ['id']); - $this->assertSame($keys['PRIMARY']->type, 'PRIMARY'); + $this->assertSame('PRIMARY', $keys['PRIMARY']->type); - $this->assertSame($keys['code_company']->name, 'code_company'); + $this->assertSame('code_company', $keys['code_company']->name); $this->assertSame($keys['code_company']->fields, ['code', 'company']); - $this->assertSame($keys['code_company']->type, 'INDEX'); + $this->assertSame('INDEX', $keys['code_company']->type); - $this->assertSame($keys['code_active']->name, 'code_active'); + $this->assertSame('code_active', $keys['code_active']->name); $this->assertSame($keys['code_active']->fields, ['code', 'active']); - $this->assertSame($keys['code_active']->type, 'UNIQUE'); + $this->assertSame('UNIQUE', $keys['code_active']->type); } elseif ($this->db->DBDriver === 'Postgre') { - $this->assertSame($keys['pk_db_forge_test_1']->name, 'pk_db_forge_test_1'); + $this->assertSame('pk_db_forge_test_1', $keys['pk_db_forge_test_1']->name); $this->assertSame($keys['pk_db_forge_test_1']->fields, ['id']); - $this->assertSame($keys['pk_db_forge_test_1']->type, 'PRIMARY'); + $this->assertSame('PRIMARY', $keys['pk_db_forge_test_1']->type); - $this->assertSame($keys['db_forge_test_1_code_company']->name, 'db_forge_test_1_code_company'); + $this->assertSame('db_forge_test_1_code_company', $keys['db_forge_test_1_code_company']->name); $this->assertSame($keys['db_forge_test_1_code_company']->fields, ['code', 'company']); - $this->assertSame($keys['db_forge_test_1_code_company']->type, 'INDEX'); + $this->assertSame('INDEX', $keys['db_forge_test_1_code_company']->type); - $this->assertSame($keys['db_forge_test_1_code_active']->name, 'db_forge_test_1_code_active'); + $this->assertSame('db_forge_test_1_code_active', $keys['db_forge_test_1_code_active']->name); $this->assertSame($keys['db_forge_test_1_code_active']->fields, ['code', 'active']); - $this->assertSame($keys['db_forge_test_1_code_active']->type, 'UNIQUE'); + $this->assertSame('UNIQUE', $keys['db_forge_test_1_code_active']->type); } elseif ($this->db->DBDriver === 'SQLite3') { - $this->assertSame($keys['PRIMARY']->name, 'PRIMARY'); + $this->assertSame('PRIMARY', $keys['PRIMARY']->name); $this->assertSame($keys['PRIMARY']->fields, ['id']); - $this->assertSame($keys['PRIMARY']->type, 'PRIMARY'); + $this->assertSame('PRIMARY', $keys['PRIMARY']->type); - $this->assertSame($keys['db_forge_test_1_code_company']->name, 'db_forge_test_1_code_company'); + $this->assertSame('db_forge_test_1_code_company', $keys['db_forge_test_1_code_company']->name); $this->assertSame($keys['db_forge_test_1_code_company']->fields, ['code', 'company']); - $this->assertSame($keys['db_forge_test_1_code_company']->type, 'INDEX'); + $this->assertSame('INDEX', $keys['db_forge_test_1_code_company']->type); - $this->assertSame($keys['db_forge_test_1_code_active']->name, 'db_forge_test_1_code_active'); + $this->assertSame('db_forge_test_1_code_active', $keys['db_forge_test_1_code_active']->name); $this->assertSame($keys['db_forge_test_1_code_active']->fields, ['code', 'active']); - $this->assertSame($keys['db_forge_test_1_code_active']->type, 'UNIQUE'); + $this->assertSame('UNIQUE', $keys['db_forge_test_1_code_active']->type); } elseif ($this->db->DBDriver === 'SQLSRV') { - $this->assertSame($keys['pk_db_forge_test_1']->name, 'pk_db_forge_test_1'); + $this->assertSame('pk_db_forge_test_1', $keys['pk_db_forge_test_1']->name); $this->assertSame($keys['pk_db_forge_test_1']->fields, ['id']); - $this->assertSame($keys['pk_db_forge_test_1']->type, 'PRIMARY'); + $this->assertSame('PRIMARY', $keys['pk_db_forge_test_1']->type); - $this->assertSame($keys['db_forge_test_1_code_company']->name, 'db_forge_test_1_code_company'); + $this->assertSame('db_forge_test_1_code_company', $keys['db_forge_test_1_code_company']->name); $this->assertSame($keys['db_forge_test_1_code_company']->fields, ['code', 'company']); - $this->assertSame($keys['db_forge_test_1_code_company']->type, 'INDEX'); + $this->assertSame('INDEX', $keys['db_forge_test_1_code_company']->type); - $this->assertSame($keys['db_forge_test_1_code_active']->name, 'db_forge_test_1_code_active'); + $this->assertSame('db_forge_test_1_code_active', $keys['db_forge_test_1_code_active']->name); $this->assertSame($keys['db_forge_test_1_code_active']->fields, ['code', 'active']); - $this->assertSame($keys['db_forge_test_1_code_active']->type, 'UNIQUE'); + $this->assertSame('UNIQUE', $keys['db_forge_test_1_code_active']->type); } elseif ($this->db->DBDriver === 'OCI8') { - $this->assertSame($keys['pk_db_forge_test_1']->name, 'pk_db_forge_test_1'); + $this->assertSame('pk_db_forge_test_1', $keys['pk_db_forge_test_1']->name); $this->assertSame($keys['pk_db_forge_test_1']->fields, ['id']); - $this->assertSame($keys['pk_db_forge_test_1']->type, 'PRIMARY'); + $this->assertSame('PRIMARY', $keys['pk_db_forge_test_1']->type); - $this->assertSame($keys['db_forge_test_1_code_company']->name, 'db_forge_test_1_code_company'); + $this->assertSame('db_forge_test_1_code_company', $keys['db_forge_test_1_code_company']->name); $this->assertSame($keys['db_forge_test_1_code_company']->fields, ['code', 'company']); - $this->assertSame($keys['db_forge_test_1_code_company']->type, 'INDEX'); + $this->assertSame('INDEX', $keys['db_forge_test_1_code_company']->type); - $this->assertSame($keys['db_forge_test_1_code_active']->name, 'db_forge_test_1_code_active'); + $this->assertSame('db_forge_test_1_code_active', $keys['db_forge_test_1_code_active']->name); $this->assertSame($keys['db_forge_test_1_code_active']->fields, ['code', 'active']); - $this->assertSame($keys['db_forge_test_1_code_active']->type, 'UNIQUE'); + $this->assertSame('UNIQUE', $keys['db_forge_test_1_code_active']->type); } $this->forge->dropTable('forge_test_1', true); diff --git a/tests/system/Database/Live/OCI8/CallStoredProcedureTest.php b/tests/system/Database/Live/OCI8/CallStoredProcedureTest.php index 2baffb669957..43816b7301b3 100644 --- a/tests/system/Database/Live/OCI8/CallStoredProcedureTest.php +++ b/tests/system/Database/Live/OCI8/CallStoredProcedureTest.php @@ -55,7 +55,7 @@ public function testCallPackageProcedure(): void ], ]); - $this->assertSame($result, '7'); + $this->assertSame('7', $result); } public function testCallStoredProcedure(): void @@ -77,7 +77,7 @@ public function testCallStoredProcedure(): void ], ]); - $this->assertSame($result, '7'); + $this->assertSame('7', $result); } public function testCallStoredProcedureForCursor(): void diff --git a/tests/system/Database/Live/OCI8/LastInsertIDTest.php b/tests/system/Database/Live/OCI8/LastInsertIDTest.php index 5cc88e39510b..33945cf7d276 100644 --- a/tests/system/Database/Live/OCI8/LastInsertIDTest.php +++ b/tests/system/Database/Live/OCI8/LastInsertIDTest.php @@ -49,7 +49,7 @@ public function testGetInsertIDWithInsert(): void $this->db->table('job')->insert($jobData); $actual = $this->db->insertID(); - $this->assertSame($actual, 5); + $this->assertSame(5, $actual); } public function testGetInsertIDWithQuery(): void @@ -57,7 +57,7 @@ public function testGetInsertIDWithQuery(): void $this->db->query('INSERT INTO "db_job" ("name", "description") VALUES (?, ?)', ['Grocery Sales', 'Discount!']); $actual = $this->db->insertID(); - $this->assertSame($actual, 5); + $this->assertSame(5, $actual); } public function testGetInsertIDWithHasCommentQuery(): void @@ -73,7 +73,7 @@ public function testGetInsertIDWithHasCommentQuery(): void $this->db->query($sql, ['Discount!']); $actual = $this->db->insertID(); - $this->assertSame($actual, 5); + $this->assertSame(5, $actual); } public function testGetInsertIDWithPreparedQuery(): void @@ -87,6 +87,6 @@ public function testGetInsertIDWithPreparedQuery(): void $query->execute('foo', 'bar'); $actual = $this->db->insertID(); - $this->assertSame($actual, 5); + $this->assertSame(5, $actual); } } diff --git a/tests/system/Files/FileCollectionTest.php b/tests/system/Files/FileCollectionTest.php index 81005356fee3..f1431b36de8c 100644 --- a/tests/system/Files/FileCollectionTest.php +++ b/tests/system/Files/FileCollectionTest.php @@ -577,6 +577,6 @@ public function testIterable(): void $count++; } - $this->assertSame($count, 5); + $this->assertSame(5, $count); } } diff --git a/tests/system/HTTP/ResponseCookieTest.php b/tests/system/HTTP/ResponseCookieTest.php index 9782287fd70a..6fb03d516a9f 100644 --- a/tests/system/HTTP/ResponseCookieTest.php +++ b/tests/system/HTTP/ResponseCookieTest.php @@ -203,7 +203,7 @@ public function testCookieDelete(): void $response->setCookie(['name' => 'bee', 'value' => 'bop', 'expire' => 1000]); $response->deleteCookie('bee'); $cookie = $response->getCookie('bee'); - $this->assertSame($cookie->getExpiresTimestamp(), 0); + $this->assertSame(0, $cookie->getExpiresTimestamp()); // delete cookie with wrong prefix? $config->prefix = 'mine'; @@ -214,7 +214,7 @@ public function testCookieDelete(): void $this->assertFalse($cookie->isExpired(), $cookie->getExpiresTimestamp() . ' should be less than ' . time()); $response->deleteCookie('bee', '', '', 'mine'); $cookie = $response->getCookie('bee'); - $this->assertSame($cookie->getExpiresTimestamp(), 0); + $this->assertSame(0, $cookie->getExpiresTimestamp()); // delete cookie with wrong domain? $config->domain = '.mine.com'; @@ -225,7 +225,7 @@ public function testCookieDelete(): void $this->assertFalse($cookie->isExpired(), $cookie->getExpiresTimestamp() . ' should be less than ' . time()); $response->deleteCookie('bees', '.mine.com', '', ''); $cookie = $response->getCookie('bees'); - $this->assertSame($cookie->getExpiresTimestamp(), 0); + $this->assertSame(0, $cookie->getExpiresTimestamp()); } public function testCookieDefaultSetSameSite(): void diff --git a/tests/system/Helpers/DateHelperTest.php b/tests/system/Helpers/DateHelperTest.php index 173a979e29e3..4e7acf649ae7 100644 --- a/tests/system/Helpers/DateHelperTest.php +++ b/tests/system/Helpers/DateHelperTest.php @@ -34,7 +34,7 @@ public function testNowDefault(): void { Time::setTestNow('June 20, 2022', 'America/Chicago'); - $this->assertSame(now(), 1_655_701_200); + $this->assertSame(1_655_701_200, now()); Time::setTestNow(); } diff --git a/tests/system/Helpers/TextHelperTest.php b/tests/system/Helpers/TextHelperTest.php index 3ba265f3a1b5..dc5072a59217 100644 --- a/tests/system/Helpers/TextHelperTest.php +++ b/tests/system/Helpers/TextHelperTest.php @@ -345,17 +345,17 @@ public function testWordWrap(): void { $string = 'Here is a simple string of text that will help us demonstrate this function.'; $expected = "Here is a simple string\nof text that will help us\ndemonstrate this\nfunction."; - $this->assertSame(substr_count(word_wrap($string, 25), "\n"), 3); + $this->assertSame(3, substr_count(word_wrap($string, 25), "\n")); $this->assertSame($expected, word_wrap($string, 25)); $string2 = "Here is a\nbroken up sentence\rspanning lines\r\nwoohoo!"; $expected2 = "Here is a\nbroken up sentence\nspanning lines\nwoohoo!"; - $this->assertSame(substr_count(word_wrap($string2, 25), "\n"), 3); + $this->assertSame(3, substr_count(word_wrap($string2, 25), "\n")); $this->assertSame($expected2, word_wrap($string2, 25)); $string3 = "Here is another slightly longer\nbroken up sentence\rspanning lines\r\nwoohoo!"; $expected3 = "Here is another slightly\nlonger\nbroken up sentence\nspanning lines\nwoohoo!"; - $this->assertSame(substr_count(word_wrap($string3, 25), "\n"), 4); + $this->assertSame(4, substr_count(word_wrap($string3, 25), "\n")); $this->assertSame($expected3, word_wrap($string3, 25)); } @@ -363,7 +363,7 @@ public function testWordWrapUnwrap(): void { $string = 'Here is a {unwrap}simple string of text{/unwrap} that will help us demonstrate this function.'; $expected = "Here is a simple string of text\nthat will help us\ndemonstrate this\nfunction."; - $this->assertSame(substr_count(word_wrap($string, 25), "\n"), 3); + $this->assertSame(3, substr_count(word_wrap($string, 25), "\n")); $this->assertSame($expected, word_wrap($string, 25)); } @@ -386,7 +386,7 @@ public function testWordWrapURL(): void public function testDefaultWordWrapCharlim(): void { $string = 'Here is a longer string of text that will help us demonstrate the default charlim of this function.'; - $this->assertSame(strpos(word_wrap($string), "\n"), 73); + $this->assertSame(73, strpos(word_wrap($string), "\n")); } public function testExcerpt(): void diff --git a/tests/system/Models/EventsModelTest.php b/tests/system/Models/EventsModelTest.php index d697437d3534..4c6b2640723a 100644 --- a/tests/system/Models/EventsModelTest.php +++ b/tests/system/Models/EventsModelTest.php @@ -84,7 +84,7 @@ public function testBeforeFindReturnsData(): void $result = $this->model->find(1); $this->assertTrue($this->model->hasToken('beforeFind')); - $this->assertSame($result, 'foobar'); + $this->assertSame('foobar', $result); } public function testBeforeFindReturnDataPreventsAfterFind(): void diff --git a/tests/system/Models/ValidationModelRuleGroupTest.php b/tests/system/Models/ValidationModelRuleGroupTest.php index 4274d5d1578f..b08f73c9a04e 100644 --- a/tests/system/Models/ValidationModelRuleGroupTest.php +++ b/tests/system/Models/ValidationModelRuleGroupTest.php @@ -398,8 +398,8 @@ public function testUpdateEntityWithPropertyCleanValidationRulesTrueAndCallingCl $errors = $model->errors(); $this->assertCount(1, $errors); $this->assertSame( - $errors['field1'], - 'The field1 field is required when field2,field3,field4 is present.' + 'The field1 field is required when field2,field3,field4 is present.', + $errors['field1'] ); } @@ -438,8 +438,8 @@ public function testUpdateEntityWithPropertyCleanValidationRulesFalse(): void $errors = $model->errors(); $this->assertCount(1, $errors); $this->assertSame( - $errors['field1'], - 'The field1 field is required when field2,field3,field4 is present.' + 'The field1 field is required when field2,field3,field4 is present.', + $errors['field1'] ); } @@ -471,8 +471,8 @@ public function testInsertEntityValidateEntireRules(): void $errors = $model->errors(); $this->assertCount(1, $errors); $this->assertSame( - $errors['field2'], - 'The field2 field is required.' + 'The field2 field is required.', + $errors['field2'] ); } } diff --git a/tests/system/Models/ValidationModelTest.php b/tests/system/Models/ValidationModelTest.php index d2c9c7d0dab8..ca41e29e78ad 100644 --- a/tests/system/Models/ValidationModelTest.php +++ b/tests/system/Models/ValidationModelTest.php @@ -410,8 +410,8 @@ public function testUpdateEntityWithPropertyCleanValidationRulesTrueAndCallingCl $errors = $model->errors(); $this->assertCount(1, $errors); $this->assertSame( - $errors['field1'], - 'The field1 field is required when field2,field3,field4 is present.' + 'The field1 field is required when field2,field3,field4 is present.', + $errors['field1'] ); } @@ -450,8 +450,8 @@ public function testUpdateEntityWithPropertyCleanValidationRulesFalse(): void $errors = $model->errors(); $this->assertCount(1, $errors); $this->assertSame( - $errors['field1'], - 'The field1 field is required when field2,field3,field4 is present.' + 'The field1 field is required when field2,field3,field4 is present.', + $errors['field1'] ); } @@ -483,8 +483,8 @@ public function testInsertEntityValidateEntireRules(): void $errors = $model->errors(); $this->assertCount(1, $errors); $this->assertSame( - $errors['field2'], - 'The field2 field is required.' + 'The field2 field is required.', + $errors['field2'] ); } } diff --git a/tests/system/Pager/PagerTest.php b/tests/system/Pager/PagerTest.php index 047637a2025f..c652a3793738 100644 --- a/tests/system/Pager/PagerTest.php +++ b/tests/system/Pager/PagerTest.php @@ -123,9 +123,9 @@ public function testStoreDoesBasicCalcs(): void $details = $this->pager->getDetails('foo'); - $this->assertSame($details['total'], 100); - $this->assertSame($details['perPage'], 25); - $this->assertSame($details['currentPage'], 3); + $this->assertSame(100, $details['total']); + $this->assertSame(25, $details['perPage']); + $this->assertSame(3, $details['currentPage']); } public function testStoreDoesBasicCalcsOnPerPageReadFromPagerConfig(): void @@ -134,9 +134,9 @@ public function testStoreDoesBasicCalcsOnPerPageReadFromPagerConfig(): void $details = $this->pager->getDetails('foo'); - $this->assertSame($details['total'], 100); - $this->assertSame($details['perPage'], 20); - $this->assertSame($details['currentPage'], 3); + $this->assertSame(100, $details['total']); + $this->assertSame(20, $details['perPage']); + $this->assertSame(3, $details['currentPage']); } public function testStoreAndHasMore(): void diff --git a/tests/system/Router/RouteCollectionTest.php b/tests/system/Router/RouteCollectionTest.php index 5c06154a5d31..bfd53a3ebf7c 100644 --- a/tests/system/Router/RouteCollectionTest.php +++ b/tests/system/Router/RouteCollectionTest.php @@ -1296,7 +1296,7 @@ public function testWillDiscoverLocal(): void $match = $routes->getRoutes(); $this->assertArrayHasKey('testing', $match); - $this->assertSame($match['testing'], '\TestController::index'); + $this->assertSame('\TestController::index', $match['testing']); } public function testDiscoverLocalAllowsConfigToOverridePackages(): void @@ -1315,7 +1315,7 @@ public function testDiscoverLocalAllowsConfigToOverridePackages(): void $match = $routes->getRoutes(); $this->assertArrayHasKey('testing', $match); - $this->assertSame($match['testing'], '\MainRoutes::index'); + $this->assertSame('\MainRoutes::index', $match['testing']); } public function testRoutesOptions(): void diff --git a/tests/system/Router/RouterTest.php b/tests/system/Router/RouterTest.php index 5d51bf2fd38c..04e3d191bbf6 100644 --- a/tests/system/Router/RouterTest.php +++ b/tests/system/Router/RouterTest.php @@ -212,10 +212,10 @@ public function testClosures(): void $closure = $router->controllerName(); - $expects = $closure(...$router->params()); + $actual = $closure(...$router->params()); $this->assertIsCallable($router->controllerName()); - $this->assertSame($expects, '123-alpha'); + $this->assertSame('123-alpha', $actual); } public function testClosuresWithTranslateURIDashes(): void @@ -228,10 +228,10 @@ public function testClosuresWithTranslateURIDashes(): void $this->assertInstanceOf(Closure::class, $closure); - $expects = $closure(...$router->params()); + $actual = $closure(...$router->params()); $this->assertIsCallable($router->controllerName()); - $this->assertSame($expects, '123-alpha'); + $this->assertSame('123-alpha', $actual); } public function testAutoRouteFindsDefaultControllerAndMethod(): void From aad4820f9b2ad8bebb321d4e1ea76caf0dfacefe Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 8 Nov 2024 15:58:26 +0000 Subject: [PATCH 050/108] chore(deps-dev): update rector/rector requirement from 1.2.9 to 1.2.10 Updates the requirements on [rector/rector](https://github.com/rectorphp/rector) to permit the latest version. - [Release notes](https://github.com/rectorphp/rector/releases) - [Commits](https://github.com/rectorphp/rector/compare/1.2.9...1.2.10) --- updated-dependencies: - dependency-name: rector/rector dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 34178265c11c..af7aa5484c9a 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": "1.2.9" + "rector/rector": "1.2.10" }, "replace": { "codeigniter4/framework": "self.version" From 862cef65adcd6734e15564fedb1b38154668acb2 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sat, 9 Nov 2024 07:41:48 +0700 Subject: [PATCH 051/108] enable skipped NarrowUnusedSetUpDefinedPropertyRector --- rector.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/rector.php b/rector.php index 6a4a37835fc4..be9e45f1e169 100644 --- a/rector.php +++ b/rector.php @@ -43,7 +43,6 @@ use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector; use Rector\Php80\Rector\FunctionLike\MixedTypeRector; use Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector; -use Rector\PHPUnit\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector; use Rector\PHPUnit\CodeQuality\Rector\Class_\YieldDataProviderRector; use Rector\PHPUnit\Set\PHPUnitSetList; use Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector; @@ -177,9 +176,6 @@ // Unnecessary (string) is inserted NullToStrictStringFuncCallArgRector::class, - - // buggy with default value - NarrowUnusedSetUpDefinedPropertyRector::class, ]) // auto import fully qualified class names ->withImportNames(removeUnusedImports: true) From 583e7b61dad9392111864479752a4b8085e111a5 Mon Sep 17 00:00:00 2001 From: neznaika0 Date: Fri, 1 Nov 2024 17:00:17 +0300 Subject: [PATCH 052/108] refactor: up performance `service()` --- .../tests/session/ExampleSessionTest.php | 3 +- admin/starter/tests/unit/HealthTest.php | 3 +- app/Config/Events.php | 4 +- app/Config/Format.php | 2 +- app/Controllers/BaseController.php | 2 +- app/Views/errors/html/error_exception.php | 4 +- system/Autoloader/Autoloader.php | 3 +- system/BaseModel.php | 3 +- system/Boot.php | 8 +- system/CLI/CLI.php | 3 +- .../Utilities/Routes/FilterCollector.php | 5 +- system/Config/Services.php | 2 +- system/Database/MigrationRunner.php | 7 +- system/Debug/Exceptions.php | 5 +- system/Debug/Toolbar.php | 5 +- system/Debug/Toolbar/Collectors/Logs.php | 4 +- system/Debug/Toolbar/Collectors/Routes.php | 7 +- system/Debug/Toolbar/Collectors/Timers.php | 4 +- system/Exceptions/PageNotFoundException.php | 2 +- system/Filters/Honeypot.php | 3 +- system/HTTP/RedirectResponse.php | 5 +- system/HTTP/Response.php | 3 +- system/Log/Handlers/ChromeLoggerHandler.php | 5 +- system/Router/RouteCollection.php | 3 +- system/Test/ControllerTestTrait.php | 6 +- system/Test/FeatureTestTrait.php | 6 +- system/Test/bootstrap.php | 3 +- system/Validation/Validation.php | 3 +- system/View/Cell.php | 3 +- tests/system/Autoloader/AutoloaderTest.php | 5 +- tests/system/CodeIgniterTest.php | 132 +++++++++--------- tests/system/Commands/BaseCommandTest.php | 3 +- tests/system/Commands/CommandTest.php | 5 +- tests/system/Commands/RoutesTest.php | 4 +- .../system/Commands/ScaffoldGeneratorTest.php | 3 +- .../Translation/LocalizationFinderTest.php | 5 +- .../Commands/Utilities/ConfigCheckTest.php | 5 +- .../AutoRouteCollectorTest.php | 5 +- .../Utilities/Routes/FilterCollectorTest.php | 3 +- .../Utilities/Routes/FilterFinderTest.php | 7 +- .../Routes/SampleURIGeneratorTest.php | 3 +- tests/system/CommonFunctionsTest.php | 12 +- tests/system/CommonHelperTest.php | 6 +- tests/system/CommonSingleServiceTest.php | 2 +- tests/system/Config/ServicesTest.php | 4 +- tests/system/ControllerTest.php | 17 ++- .../DatabaseTestCaseMigrationOnce1Test.php | 3 +- .../DatabaseTestCaseMigrationOnce2Test.php | 3 +- .../system/Database/DatabaseTestCaseTest.php | 3 +- .../Migrations/MigrationRunnerTest.php | 3 +- tests/system/Debug/ExceptionHandlerTest.php | 10 +- tests/system/Filters/CSRFTest.php | 6 +- tests/system/Filters/CorsTest.php | 5 +- tests/system/Filters/DebugToolbarTest.php | 5 +- tests/system/Filters/FiltersTest.php | 7 +- tests/system/Filters/HoneypotTest.php | 17 ++- tests/system/Filters/SecureHeadersTest.php | 5 +- tests/system/Filters/fixtures/GoogleYou.php | 3 +- tests/system/HTTP/CorsTest.php | 31 ++-- tests/system/HTTP/RedirectExceptionTest.php | 10 +- tests/system/HTTP/RedirectResponseTest.php | 4 +- tests/system/HTTP/ResponseTest.php | 11 +- tests/system/HTTP/URITest.php | 6 +- tests/system/Helpers/CookieHelperTest.php | 2 +- tests/system/Helpers/FormHelperTest.php | 10 +- .../system/Helpers/URLHelper/MiscUrlTest.php | 4 +- tests/system/Honeypot/HoneypotTest.php | 11 +- tests/system/Language/LanguageTest.php | 9 +- .../Log/Handlers/ChromeLoggerHandlerTest.php | 2 +- .../Models/ValidationModelRuleGroupTest.php | 3 +- tests/system/Pager/PagerTest.php | 4 +- .../system/RESTful/ResourceControllerTest.php | 4 +- .../system/RESTful/ResourcePresenterTest.php | 2 +- .../system/Router/AutoRouterImprovedTest.php | 3 +- .../Router/DefinedRouteCollectorTest.php | 5 +- .../RouteCollectionReverseRouteTest.php | 5 +- tests/system/Router/RouteCollectionTest.php | 97 +++++++------ tests/system/Router/RouterTest.php | 5 +- .../SecurityCSRFSessionRandomizeTokenTest.php | 2 +- tests/system/Security/SecurityTest.php | 3 +- tests/system/Test/ControllerTestTraitTest.php | 5 +- .../FeatureTestAutoRoutingImprovedTest.php | 4 +- tests/system/Test/FeatureTestTraitTest.php | 17 ++- tests/system/Test/FilterTestTraitTest.php | 3 +- tests/system/Test/TestResponseTest.php | 7 +- .../system/Validation/CreditCardRulesTest.php | 3 +- tests/system/Validation/FileRulesTest.php | 3 +- tests/system/Validation/FormatRulesTest.php | 3 +- tests/system/Validation/RulesTest.php | 3 +- .../StrictRules/CreditCardRulesTest.php | 3 +- .../StrictRules/DatabaseRelatedRulesTest.php | 3 +- .../Validation/StrictRules/FileRulesTest.php | 3 +- tests/system/Validation/ValidationTest.php | 7 +- tests/system/View/DecoratorsTest.php | 3 +- tests/system/View/ParserFilterTest.php | 3 +- tests/system/View/ParserPluginTest.php | 4 +- tests/system/View/ParserTest.php | 3 +- tests/system/View/ViewTest.php | 3 +- 98 files changed, 325 insertions(+), 395 deletions(-) diff --git a/admin/starter/tests/session/ExampleSessionTest.php b/admin/starter/tests/session/ExampleSessionTest.php index 6ada0c56996d..33242a477112 100644 --- a/admin/starter/tests/session/ExampleSessionTest.php +++ b/admin/starter/tests/session/ExampleSessionTest.php @@ -1,7 +1,6 @@ set('logged_in', 123); $this->assertSame(123, $session->get('logged_in')); diff --git a/admin/starter/tests/unit/HealthTest.php b/admin/starter/tests/unit/HealthTest.php index 25f229b0cec5..f6a5a804802f 100644 --- a/admin/starter/tests/unit/HealthTest.php +++ b/admin/starter/tests/unit/HealthTest.php @@ -2,7 +2,6 @@ use CodeIgniter\Test\CIUnitTestCase; use Config\App; -use Config\Services; use Tests\Support\Libraries\ConfigReader; /** @@ -17,7 +16,7 @@ public function testIsDefinedAppPath(): void public function testBaseUrlHasBeenSet(): void { - $validation = Services::validation(); + $validation = service('validation'); $env = false; diff --git a/app/Config/Events.php b/app/Config/Events.php index 62a7b86d46c8..946285b89519 100644 --- a/app/Config/Events.php +++ b/app/Config/Events.php @@ -44,10 +44,10 @@ */ if (CI_DEBUG && ! is_cli()) { Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect'); - Services::toolbar()->respond(); + service('toolbar')->respond(); // Hot Reload route - for framework use on the hot reloader. if (ENVIRONMENT === 'development') { - Services::routes()->get('__hot-reload', static function (): void { + service('routes')->get('__hot-reload', static function (): void { (new HotReloader())->run(); }); } diff --git a/app/Config/Format.php b/app/Config/Format.php index 3de98d7a95d7..2838f55ef0d9 100644 --- a/app/Config/Format.php +++ b/app/Config/Format.php @@ -72,6 +72,6 @@ class Format extends BaseConfig */ public function getFormatter(string $mime) { - return Services::format()->getFormatter($mime); + return service('format')->getFormatter($mime); } } diff --git a/app/Controllers/BaseController.php b/app/Controllers/BaseController.php index 8b435dab7056..689405bdf314 100644 --- a/app/Controllers/BaseController.php +++ b/app/Controllers/BaseController.php @@ -53,6 +53,6 @@ public function initController(RequestInterface $request, ResponseInterface $res // Preload any models, libraries, etc, here. - // E.g.: $this->session = \Config\Services::session(); + // E.g.: $this->session = service('session'); } } diff --git a/app/Views/errors/html/error_exception.php b/app/Views/errors/html/error_exception.php index 44d749892473..38e73bb9b661 100644 --- a/app/Views/errors/html/error_exception.php +++ b/app/Views/errors/html/error_exception.php @@ -225,7 +225,7 @@
- + @@ -343,7 +343,7 @@ setStatusCode(http_response_code()); ?>
diff --git a/system/Autoloader/Autoloader.php b/system/Autoloader/Autoloader.php index 28c183f12552..bba6d3c5cebd 100644 --- a/system/Autoloader/Autoloader.php +++ b/system/Autoloader/Autoloader.php @@ -19,7 +19,6 @@ use Config\Autoload; use Config\Kint as KintConfig; use Config\Modules; -use Config\Services; use InvalidArgumentException; use Kint; use Kint\Renderer\CliRenderer; @@ -537,7 +536,7 @@ private function configureKint(): void Kint::$plugins = $config->plugins; } - $csp = Services::csp(); + $csp = service('csp'); if ($csp->enabled()) { RichRenderer::$js_nonce = $csp->getScriptNonce(); RichRenderer::$css_nonce = $csp->getStyleNonce(); diff --git a/system/BaseModel.php b/system/BaseModel.php index 2b364bdc1917..46bab107218f 100644 --- a/system/BaseModel.php +++ b/system/BaseModel.php @@ -26,7 +26,6 @@ use CodeIgniter\Pager\Pager; use CodeIgniter\Validation\ValidationInterface; use Config\Feature; -use Config\Services; use InvalidArgumentException; use ReflectionClass; use ReflectionException; @@ -1609,7 +1608,7 @@ public function getValidationRules(array $options = []): array protected function ensureValidation(): void { if ($this->validation === null) { - $this->validation = Services::validation(null, false); + $this->validation = service('validation', null, false); } } diff --git a/system/Boot.php b/system/Boot.php index 54468a5cc192..8b75908ded09 100644 --- a/system/Boot.php +++ b/system/Boot.php @@ -246,12 +246,12 @@ protected static function loadAutoloader(): void protected static function autoloadHelpers(): void { - Services::autoloader()->loadHelpers(); + service('autoloader')->loadHelpers(); } protected static function setExceptionHandler(): void { - Services::exceptions()->initialize(); + service('exceptions')->initialize(); } protected static function checkMissingExtensions(): void @@ -290,7 +290,7 @@ protected static function checkMissingExtensions(): void protected static function initializeKint(): void { - Services::autoloader()->initializeKint(CI_DEBUG); + service('autoloader')->initializeKint(CI_DEBUG); } protected static function loadConfigCache(): FactoriesCache @@ -308,7 +308,7 @@ protected static function loadConfigCache(): FactoriesCache */ protected static function initializeCodeIgniter(): CodeIgniter { - $app = Config\Services::codeigniter(); + $app = service('codeigniter'); $app->initialize(); $context = is_cli() ? 'php-cli' : 'web'; $app->setContext($context); diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index 54ca6a5ca97e..236e5b685fff 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -14,7 +14,6 @@ namespace CodeIgniter\CLI; use CodeIgniter\CLI\Exceptions\CLIException; -use Config\Services; use InvalidArgumentException; use Throwable; @@ -416,7 +415,7 @@ protected static function validate(string $field, string $value, $rules): bool { $label = $field; $field = 'temp'; - $validation = Services::validation(null, false); + $validation = service('validation', null, false); $validation->setRules([ $field => [ 'label' => $label, diff --git a/system/Commands/Utilities/Routes/FilterCollector.php b/system/Commands/Utilities/Routes/FilterCollector.php index 002a529b953e..b646dcb250a1 100644 --- a/system/Commands/Utilities/Routes/FilterCollector.php +++ b/system/Commands/Utilities/Routes/FilterCollector.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Commands\Utilities\Routes; -use CodeIgniter\Config\Services; use CodeIgniter\Filters\Filters; use CodeIgniter\HTTP\Method; use CodeIgniter\HTTP\Request; @@ -68,7 +67,7 @@ public function get(string $method, string $uri): array ]; } - $request = Services::incomingrequest(null, false); + $request = service('incomingrequest', null, false); $request->setMethod($method); $router = $this->createRouter($request); @@ -86,7 +85,7 @@ public function get(string $method, string $uri): array */ public function getRequiredFilters(): array { - $request = Services::incomingrequest(null, false); + $request = service('incomingrequest', null, false); $request->setMethod(Method::GET); $router = $this->createRouter($request); diff --git a/system/Config/Services.php b/system/Config/Services.php index 28e521df3f0e..c0d5fcc392d2 100644 --- a/system/Config/Services.php +++ b/system/Config/Services.php @@ -705,7 +705,7 @@ public static function session(?SessionConfig $config = null, bool $getShared = // See https://www.php.net/manual/en/function.session-cache-limiter.php. // The headers are not managed by CI's Response class. // So, we remove CI's default Cache-Control header. - AppServices::response()->removeHeader('Cache-Control'); + AppServices::get('response')->removeHeader('Cache-Control'); $session->start(); } diff --git a/system/Database/MigrationRunner.php b/system/Database/MigrationRunner.php index 055b8ba6eaf3..cf736171a7cf 100644 --- a/system/Database/MigrationRunner.php +++ b/system/Database/MigrationRunner.php @@ -19,7 +19,6 @@ use CodeIgniter\I18n\Time; use Config\Database; use Config\Migrations as MigrationsConfig; -use Config\Services; use RuntimeException; use stdClass; @@ -390,7 +389,7 @@ public function force(string $path, string $namespace, ?string $group = null) */ public function findMigrations(): array { - $namespaces = $this->namespace ? [$this->namespace] : array_keys(Services::autoloader()->getNamespace()); + $namespaces = $this->namespace ? [$this->namespace] : array_keys(service('autoloader')->getNamespace()); $migrations = []; foreach ($namespaces as $namespace) { @@ -415,7 +414,7 @@ public function findMigrations(): array public function findNamespaceMigrations(string $namespace): array { $migrations = []; - $locator = Services::locator(true); + $locator = service('locator', true); if (! empty($this->path)) { helper('filesystem'); @@ -455,7 +454,7 @@ protected function migrationFromFile(string $path, string $namespace) return false; } - $locator = Services::locator(true); + $locator = service('locator', true); $migration = new stdClass(); diff --git a/system/Debug/Exceptions.php b/system/Debug/Exceptions.php index e5f7ecb04881..aa353732c197 100644 --- a/system/Debug/Exceptions.php +++ b/system/Debug/Exceptions.php @@ -22,7 +22,6 @@ use CodeIgniter\HTTP\ResponseInterface; use Config\Exceptions as ExceptionsConfig; use Config\Paths; -use Config\Services; use ErrorException; use Psr\Log\LogLevel; use Throwable; @@ -126,7 +125,7 @@ public function exceptionHandler(Throwable $exception) [$statusCode, $exitCode] = $this->determineCodes($exception); - $this->request = Services::request(); + $this->request = service('request'); if ($this->config->log === true && ! in_array($statusCode, $this->config->ignoreCodes, true)) { $uri = $this->request->getPath() === '' ? '/' : $this->request->getPath(); @@ -155,7 +154,7 @@ public function exceptionHandler(Throwable $exception) } } - $this->response = Services::response(); + $this->response = service('response'); if (method_exists($this->config, 'handler')) { // Use new ExceptionHandler diff --git a/system/Debug/Toolbar.php b/system/Debug/Toolbar.php index 9f20f987f59c..b939e208fd21 100644 --- a/system/Debug/Toolbar.php +++ b/system/Debug/Toolbar.php @@ -25,7 +25,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\I18n\Time; -use Config\Services; use Config\Toolbar as ToolbarConfig; use Kint\Kint; @@ -386,7 +385,7 @@ public function prepare(?RequestInterface $request = null, ?ResponseInterface $r return; } - $toolbar = Services::toolbar(config(ToolbarConfig::class)); + $toolbar = service('toolbar', config(ToolbarConfig::class)); $stats = $app->getPerformanceStats(); $data = $toolbar->run( $stats['startTime'], @@ -529,7 +528,7 @@ protected function format(string $data, string $format = 'html'): string case 'html': $data['styles'] = []; extract($data); - $parser = Services::parser($this->config->viewsPath, null, false); + $parser = service('parser', $this->config->viewsPath, null, false); ob_start(); include $this->config->viewsPath . 'toolbar.tpl.php'; $output = ob_get_clean(); diff --git a/system/Debug/Toolbar/Collectors/Logs.php b/system/Debug/Toolbar/Collectors/Logs.php index 2194526c733e..f36dfb1d12b5 100644 --- a/system/Debug/Toolbar/Collectors/Logs.php +++ b/system/Debug/Toolbar/Collectors/Logs.php @@ -13,8 +13,6 @@ namespace CodeIgniter\Debug\Toolbar\Collectors; -use Config\Services; - /** * Loags collector */ @@ -92,6 +90,6 @@ protected function collectLogs() return $this->data; } - return $this->data = Services::logger(true)->logCache ?? []; + return $this->data = service('logger', true)->logCache ?? []; } } diff --git a/system/Debug/Toolbar/Collectors/Routes.php b/system/Debug/Toolbar/Collectors/Routes.php index b6862dcee73c..561399fbf37f 100644 --- a/system/Debug/Toolbar/Collectors/Routes.php +++ b/system/Debug/Toolbar/Collectors/Routes.php @@ -14,7 +14,6 @@ namespace CodeIgniter\Debug\Toolbar\Collectors; use CodeIgniter\Router\DefinedRouteCollector; -use Config\Services; use ReflectionException; use ReflectionFunction; use ReflectionMethod; @@ -74,8 +73,8 @@ class Routes extends BaseCollector */ public function display(): array { - $rawRoutes = Services::routes(true); - $router = Services::router(null, null, true); + $rawRoutes = service('routes', true); + $router = service('router', null, null, true); // Get our parameters // Closure routes @@ -153,7 +152,7 @@ public function display(): array */ public function getBadgeValue(): int { - $rawRoutes = Services::routes(true); + $rawRoutes = service('routes', true); return count($rawRoutes->getRoutes()); } diff --git a/system/Debug/Toolbar/Collectors/Timers.php b/system/Debug/Toolbar/Collectors/Timers.php index 163c9f5743f0..d450cc5c306a 100644 --- a/system/Debug/Toolbar/Collectors/Timers.php +++ b/system/Debug/Toolbar/Collectors/Timers.php @@ -13,8 +13,6 @@ namespace CodeIgniter\Debug\Toolbar\Collectors; -use Config\Services; - /** * Timers collector */ @@ -52,7 +50,7 @@ protected function formatTimelineData(): array { $data = []; - $benchmark = Services::timer(true); + $benchmark = service('timer', true); $rows = $benchmark->getTimers(6); foreach ($rows as $name => $info) { diff --git a/system/Exceptions/PageNotFoundException.php b/system/Exceptions/PageNotFoundException.php index b1af079e3a54..552c8fd1c924 100644 --- a/system/Exceptions/PageNotFoundException.php +++ b/system/Exceptions/PageNotFoundException.php @@ -78,7 +78,7 @@ public static function forLocaleNotSupported(string $locale) */ private static function lang(string $line, array $args = []): string { - $lang = Services::language(null, false); + $lang = service('language', null, false); return $lang->getLine($line, $args); } diff --git a/system/Filters/Honeypot.php b/system/Filters/Honeypot.php index c2fb98c62d60..cdff293aacb4 100644 --- a/system/Filters/Honeypot.php +++ b/system/Filters/Honeypot.php @@ -17,7 +17,6 @@ use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; -use Config\Services; /** * Honeypot filter @@ -40,7 +39,7 @@ public function before(RequestInterface $request, $arguments = null) return; } - if (Services::honeypot()->hasContent($request)) { + if (service('honeypot')->hasContent($request)) { throw HoneypotException::isBot(); } } diff --git a/system/HTTP/RedirectResponse.php b/system/HTTP/RedirectResponse.php index 95bfadcd4299..c8c76607b651 100644 --- a/system/HTTP/RedirectResponse.php +++ b/system/HTTP/RedirectResponse.php @@ -15,7 +15,6 @@ use CodeIgniter\Cookie\CookieStore; use CodeIgniter\HTTP\Exceptions\HTTPException; -use Config\Services; /** * Handle a redirect response @@ -148,7 +147,7 @@ public function with(string $key, $message) */ public function withCookies() { - $this->cookieStore = new CookieStore(Services::response()->getCookies()); + $this->cookieStore = new CookieStore(service('response')->getCookies()); return $this; } @@ -163,7 +162,7 @@ public function withCookies() */ public function withHeaders() { - foreach (Services::response()->headers() as $name => $value) { + foreach (service('response')->headers() as $name => $value) { if ($value instanceof Header) { $this->setHeader($name, $value->getValue()); } else { diff --git a/system/HTTP/Response.php b/system/HTTP/Response.php index a19fbb5fee14..ac853c3de93b 100644 --- a/system/HTTP/Response.php +++ b/system/HTTP/Response.php @@ -18,7 +18,6 @@ use CodeIgniter\HTTP\Exceptions\HTTPException; use Config\App; use Config\Cookie as CookieConfig; -use Config\Services; /** * Representation of an outgoing, server-side response. @@ -158,7 +157,7 @@ public function __construct($config) // @phpstan-ignore-line $this->noCache(); // We need CSP object even if not enabled to avoid calls to non existing methods - $this->CSP = Services::csp(); + $this->CSP = service('csp'); $this->cookieStore = new CookieStore([]); diff --git a/system/Log/Handlers/ChromeLoggerHandler.php b/system/Log/Handlers/ChromeLoggerHandler.php index 192f7f2951b8..26fe0b6f9525 100644 --- a/system/Log/Handlers/ChromeLoggerHandler.php +++ b/system/Log/Handlers/ChromeLoggerHandler.php @@ -14,7 +14,6 @@ namespace CodeIgniter\Log\Handlers; use CodeIgniter\HTTP\ResponseInterface; -use Config\Services; /** * Class ChromeLoggerHandler @@ -156,8 +155,8 @@ protected function format($object) */ public function sendLogs(?ResponseInterface &$response = null) { - if (! $response instanceof ResponseInterface) { - $response = Services::response(null, true); + if ($response instanceof ResponseInterface) { + $response = service('response', null, true); } $data = base64_encode( diff --git a/system/Router/RouteCollection.php b/system/Router/RouteCollection.php index 231711c48aac..74c34d6ad518 100644 --- a/system/Router/RouteCollection.php +++ b/system/Router/RouteCollection.php @@ -21,7 +21,6 @@ use Config\App; use Config\Modules; use Config\Routing; -use Config\Services; use InvalidArgumentException; /** @@ -283,7 +282,7 @@ public function __construct(FileLocatorInterface $locator, Modules $moduleConfig $this->fileLocator = $locator; $this->moduleConfig = $moduleConfig; - $this->httpHost = Services::request()->getServer('HTTP_HOST'); + $this->httpHost = service('request')->getServer('HTTP_HOST'); // Setup based on config file. Let routes file override. $this->defaultNamespace = rtrim($routing->defaultNamespace, '\\') . '\\'; diff --git a/system/Test/ControllerTestTrait.php b/system/Test/ControllerTestTrait.php index ab1a1aef3907..99e9cf330274 100644 --- a/system/Test/ControllerTestTrait.php +++ b/system/Test/ControllerTestTrait.php @@ -109,14 +109,14 @@ protected function setUpControllerTestTrait(): void $tempUri = service('uri'); Services::injectMock('uri', $this->uri); - $this->withRequest(Services::incomingrequest($this->appConfig, false)); + $this->withRequest(service('incomingrequest', $this->appConfig, false)); // Restore the URI service Services::injectMock('uri', $tempUri); } if (empty($this->response)) { - $this->response = Services::response($this->appConfig, false); + $this->response = service('response', $this->appConfig, false); } if (empty($this->logger)) { @@ -285,7 +285,7 @@ public function withUri(string $uri) Services::injectMock('uri', $this->uri); // Update the Request instance, because Request has the SiteURI instance. - $this->request = Services::incomingrequest(null, false); + $this->request = service('incomingrequest', null, false); Services::injectMock('request', $this->request); return $this; diff --git a/system/Test/FeatureTestTrait.php b/system/Test/FeatureTestTrait.php index 0f2467ffd897..a1d492f85fdd 100644 --- a/system/Test/FeatureTestTrait.php +++ b/system/Test/FeatureTestTrait.php @@ -200,10 +200,10 @@ public function call(string $method, string $path, ?array $params = null) Services::injectMock('request', $request); // Make sure filters are reset between tests - Services::injectMock('filters', Services::filters(null, false)); + Services::injectMock('filters', service('filters', null, false)); // Make sure validation is reset between tests - Services::injectMock('validation', Services::validation(null, false)); + Services::injectMock('validation', service('validation', null, false)); $response = $this->app ->setContext('web') @@ -321,7 +321,7 @@ protected function setupRequest(string $method, ?string $path = null): IncomingR Services::injectMock('uri', $uri); - $request = Services::incomingrequest($config, false); + $request = service('incomingrequest', $config, false); $request->setMethod($method); $request->setProtocolVersion('1.1'); diff --git a/system/Test/bootstrap.php b/system/Test/bootstrap.php index 4a068a4c97b1..d2b47aaf21fb 100644 --- a/system/Test/bootstrap.php +++ b/system/Test/bootstrap.php @@ -13,7 +13,6 @@ use CodeIgniter\Boot; use Config\Paths; -use Config\Services; error_reporting(E_ALL); ini_set('display_errors', '1'); @@ -88,4 +87,4 @@ * --------------------------------------------------------------- */ -Services::routes()->loadRoutes(); +service('routes')->loadRoutes(); diff --git a/system/Validation/Validation.php b/system/Validation/Validation.php index 66ed1f8e48a3..5eae6b52c9a5 100644 --- a/system/Validation/Validation.php +++ b/system/Validation/Validation.php @@ -21,7 +21,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\Validation\Exceptions\ValidationException; use CodeIgniter\View\RendererInterface; -use Config\Services; use Config\Validation as ValidationConfig; use InvalidArgumentException; use LogicException; @@ -796,7 +795,7 @@ protected function fillPlaceholders(array $rules, array $data): array $placeholderFields = $this->retrievePlaceholders($row, $data); foreach ($placeholderFields as $field) { - $validator ??= Services::validation(null, false); + $validator ??= service('validation', null, false); assert($validator instanceof Validation); $placeholderRules = $rules[$field]['rules'] ?? null; diff --git a/system/View/Cell.php b/system/View/Cell.php index 28b249a60e1c..f2801e4194ec 100644 --- a/system/View/Cell.php +++ b/system/View/Cell.php @@ -17,7 +17,6 @@ use CodeIgniter\Config\Factories; use CodeIgniter\View\Cells\Cell as BaseCell; use CodeIgniter\View\Exceptions\ViewException; -use Config\Services; use ReflectionException; use ReflectionMethod; @@ -93,7 +92,7 @@ public function render(string $library, $params = null, int $ttl = 0, ?string $c } if (method_exists($instance, 'initController')) { - $instance->initController(Services::request(), service('response'), service('logger')); + $instance->initController(service('request'), service('response'), service('logger')); } if (! method_exists($instance, $method)) { diff --git a/tests/system/Autoloader/AutoloaderTest.php b/tests/system/Autoloader/AutoloaderTest.php index 8529d79dc118..d56afbafaf84 100644 --- a/tests/system/Autoloader/AutoloaderTest.php +++ b/tests/system/Autoloader/AutoloaderTest.php @@ -20,7 +20,6 @@ use CodeIgniter\Test\ReflectionHelper; use Config\Autoload; use Config\Modules; -use Config\Services; use InvalidArgumentException; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\PreserveGlobalState; @@ -112,7 +111,7 @@ public function testInitializeTwice(): void public function testServiceAutoLoaderFromShareInstances(): void { - $classLoader = $this->getPrivateMethodInvoker(Services::autoloader(), 'loadInNamespace'); + $classLoader = $this->getPrivateMethodInvoker(service('autoloader'), 'loadInNamespace'); // look for Home controller, as that should be in base repo $actual = $classLoader(Home::class); @@ -122,7 +121,7 @@ public function testServiceAutoLoaderFromShareInstances(): void public function testServiceAutoLoader(): void { - $autoloader = Services::autoloader(false); + $autoloader = service('autoloader', false); $autoloader->initialize(new Autoload(), new Modules()); $autoloader->register(); diff --git a/tests/system/CodeIgniterTest.php b/tests/system/CodeIgniterTest.php index 2928777271fd..735aed389552 100644 --- a/tests/system/CodeIgniterTest.php +++ b/tests/system/CodeIgniterTest.php @@ -58,7 +58,7 @@ protected function setUp(): void $this->codeigniter = new MockCodeIgniter(new App()); - $response = Services::response(); + $response = service('response'); $response->pretend(); } @@ -110,11 +110,11 @@ public function testRunClosureRoute(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add('pages/(:segment)', static function ($segment): void { echo 'You want to see "' . esc($segment) . '" page.'; }); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -131,10 +131,10 @@ public function testRun404Override(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->setAutoRoute(false); $routes->set404Override('Tests\Support\Errors::show404'); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -151,10 +151,10 @@ public function testRun404OverrideControllerReturnsResponse(): void $_SERVER['argc'] = 2; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->setAutoRoute(false); $routes->set404Override('Tests\Support\Controllers\Popcorn::pop'); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); $response = $this->codeigniter->run($routes, true); @@ -169,10 +169,10 @@ public function testRun404OverrideReturnResponse(): void $_SERVER['argc'] = 2; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->setAutoRoute(false); $routes->set404Override('Tests\Support\Controllers\Popcorn::pop'); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); $response = $this->codeigniter->run($routes, true); @@ -186,12 +186,12 @@ public function testRun404OverrideByClosure(): void $_SERVER['argc'] = 2; // Inject mock router. - $routes = new RouteCollection(Services::locator(), new Modules(), new Routing()); + $routes = new RouteCollection(service('locator'), new Modules(), new Routing()); $routes->setAutoRoute(false); $routes->set404Override(static function (): void { echo '404 Override by Closure.'; }); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -211,12 +211,12 @@ public function testControllersCanReturnString(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add( 'pages/(:segment)', static fn ($segment) => 'You want to see "' . esc($segment) . '" page.' ); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -235,14 +235,14 @@ public function testControllersCanReturnResponseObject(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add('pages/(:segment)', static function ($segment) { - $response = Services::response(); + $response = service('response'); $string = "You want to see 'about' page."; return $response->setBody($string); }); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -264,13 +264,13 @@ public function testControllersCanReturnDownloadResponseObject(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add('pages/(:segment)', static function ($segment) { - $response = Services::response(); + $response = service('response'); return $response->download('some.txt', 'some text', true); }); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -289,14 +289,14 @@ public function testRunExecuteFilterByClassName(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add( 'pages/about', - static fn () => Services::incomingrequest()->getBody(), + static fn () => service('incomingrequest')->getBody(), ['filter' => Customfilter::class] ); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -319,15 +319,15 @@ public function testRegisterSameFilterTwiceWithDifferentArgument(): void $_SERVER['REQUEST_URI'] = '/pages/about'; $_SERVER['SCRIPT_NAME'] = '/index.php'; - $routes = Services::routes(); + $routes = service('routes'); $routes->add( 'pages/about', - static fn () => Services::incomingrequest()->getBody(), + static fn () => service('incomingrequest')->getBody(), // Set filter with no argument. ['filter' => 'test-customfilter'] ); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); /** @var FiltersConfig $filterConfig */ @@ -338,7 +338,7 @@ public function testRegisterSameFilterTwiceWithDifferentArgument(): void 'before' => ['pages/*'], ], ]; - Services::filters($filterConfig); + service('filters', $filterConfig); $this->codeigniter->run(); @@ -354,13 +354,13 @@ public function testDisableControllerFilters(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add( 'pages/about', - static fn () => Services::incomingrequest()->getBody(), + static fn () => service('incomingrequest')->getBody(), ['filter' => Customfilter::class] ); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -378,7 +378,7 @@ public function testResponseConfigEmpty(): void $_SERVER['argv'] = ['index.php', '/']; $_SERVER['argc'] = 2; - $response = Services::response(null, false); + $response = service('response', null, false); $this->assertInstanceOf(Response::class, $response); } @@ -389,7 +389,7 @@ public function testRoutesIsEmpty(): void $_SERVER['argc'] = 2; // Inject mock router. - $router = Services::router(null, Services::incomingrequest(), false); + $router = service('router', null, service('incomingrequest'), false); Services::injectMock('router', $router); ob_start(); @@ -478,12 +478,12 @@ public function testRunRedirectionWithNamed(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add('pages/named', static function (): void { }, ['as' => 'name']); $routes->addRedirect('example', 'name'); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -502,12 +502,12 @@ public function testRunRedirectionWithURI(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add('pages/uri', static function (): void { }); $routes->addRedirect('example', 'pages/uri'); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -531,11 +531,11 @@ public function testRunRedirectionWithGET(): void $_SERVER['REQUEST_METHOD'] = 'GET'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); // addRedirect() sets status code 302 by default. $routes->addRedirect('example', 'pages/notset'); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -558,10 +558,10 @@ public function testRunRedirectionWithGETAndHTTPCode301(): void $_SERVER['REQUEST_METHOD'] = 'GET'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->addRedirect('example', 'pages/notset', 301); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -583,10 +583,10 @@ public function testRunRedirectionWithPOSTAndHTTPCode301(): void $_SERVER['REQUEST_METHOD'] = 'POST'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->addRedirect('example', 'pages/notset', 301); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -606,12 +606,12 @@ public function testRedirectExceptionDeprecated(): void $_SERVER['argc'] = 2; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->get('/', static function (): never { throw new RedirectException('redirect-exception', 503); }); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); $response = $this->codeigniter->run($routes, true); @@ -626,7 +626,7 @@ public function testStoresPreviousURL(): void $_SERVER['argc'] = 2; // Inject mock router. - $router = Services::router(null, Services::incomingrequest(), false); + $router = service('router', null, service('incomingrequest'), false); Services::injectMock('router', $router); ob_start(); @@ -648,10 +648,10 @@ public function testNotStoresPreviousURL(): void $_SERVER['REQUEST_METHOD'] = 'GET'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->addRedirect('example', 'pages/notset', 301); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -670,13 +670,13 @@ public function testNotStoresPreviousURLByCheckingContentType(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->add('image', static function () { - $response = Services::response(); + $response = service('response'); return $response->setContentType('image/jpeg', ''); }); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); ob_start(); @@ -713,7 +713,7 @@ public function testRunCLIRoute(): void $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1'; $_SERVER['REQUEST_METHOD'] = 'CLI'; - $routes = Services::routes(); + $routes = service('routes'); $routes->cli('cli', '\Tests\Support\Controllers\Popcorn::index'); ob_start(); @@ -735,7 +735,7 @@ public function testSpoofRequestMethodCanUsePUT(): void $_POST['_method'] = Method::PUT; - $routes = \Config\Services::routes(); + $routes = service('routes'); $routes->setDefaultNamespace('App\Controllers'); $routes->resetRoutes(); $routes->post('/', 'Home::index'); @@ -745,7 +745,7 @@ public function testSpoofRequestMethodCanUsePUT(): void $this->codeigniter->run(); ob_get_clean(); - $this->assertSame(Method::PUT, Services::incomingrequest()->getMethod()); + $this->assertSame(Method::PUT, service('incomingrequest')->getMethod()); } public function testSpoofRequestMethodCannotUseGET(): void @@ -760,7 +760,7 @@ public function testSpoofRequestMethodCannotUseGET(): void $_POST['_method'] = 'GET'; - $routes = \Config\Services::routes(); + $routes = service('routes'); $routes->setDefaultNamespace('App\Controllers'); $routes->resetRoutes(); $routes->post('/', 'Home::index'); @@ -770,7 +770,7 @@ public function testSpoofRequestMethodCannotUseGET(): void $this->codeigniter->run(); ob_get_clean(); - $this->assertSame('POST', Services::incomingrequest()->getMethod()); + $this->assertSame('POST', service('incomingrequest')->getMethod()); } /** @@ -789,22 +789,22 @@ public function testPageCacheSendSecureHeaders(): void $_SERVER['REQUEST_URI'] = '/test'; $_SERVER['SCRIPT_NAME'] = '/index.php'; - $routes = Services::routes(); + $routes = service('routes'); $routes->add('test', static function () { CodeIgniter::cache(3600); - $response = Services::response(); + $response = service('response'); $string = 'This is a test page. Elapsed time: {elapsed_time}'; return $response->setBody($string); }); - $router = Services::router($routes, Services::incomingrequest()); + $router = service('router', $routes, service('incomingrequest')); Services::injectMock('router', $router); /** @var FiltersConfig $filterConfig */ $filterConfig = config('Filters'); $filterConfig->globals['after'] = ['secureheaders']; - Services::filters($filterConfig); + service('filters', $filterConfig); // The first response to be cached. ob_start(); @@ -812,7 +812,7 @@ public function testPageCacheSendSecureHeaders(): void $output = ob_get_clean(); $this->assertStringContainsString('This is a test page', $output); - $response = Services::response(); + $response = service('response'); $headers = $response->headers(); $this->assertArrayHasKey('X-Frame-Options', $headers); @@ -822,7 +822,7 @@ public function testPageCacheSendSecureHeaders(): void $output = ob_get_clean(); $this->assertStringContainsString('This is a test page', $output); - $response = Services::response(); + $response = service('response'); $headers = $response->headers(); $this->assertArrayHasKey('X-Frame-Options', $headers); @@ -868,18 +868,18 @@ public function testPageCacheWithCacheQueryString( $_SERVER['SCRIPT_NAME'] = '/index.php'; $this->codeigniter = new MockCodeIgniter(new App()); - $routes = Services::routes(true); + $routes = service('routes', true); $routePath = explode('?', $testingUrl)[0]; $string = 'This is a test page, to check cache configuration'; $routes->add($routePath, static function () use ($string) { - Services::responsecache()->setTtl(60); - $response = Services::response(); + service('responsecache')->setTtl(60); + $response = service('response'); return $response->setBody($string); }); // Inject router - $router = Services::router($routes, Services::incomingrequest(null, false)); + $router = service('router', $routes, service('incomingrequest', null, false)); Services::injectMock('router', $router); // Cache the page output using default caching function and $cacheConfig @@ -952,14 +952,14 @@ public function testRunControllerNotFoundBeforeFilter(): void $_SERVER['SCRIPT_NAME'] = '/index.php'; // Inject mock router. - $routes = Services::routes(); + $routes = service('routes'); $routes->setAutoRoute(true); // Inject the before filter. $filterConfig = config('Filters'); $filterConfig->aliases['redirectFilter'] = RedirectFilter::class; $filterConfig->globals['before'] = ['redirectFilter']; - Services::filters($filterConfig); + service('filters', $filterConfig); $this->expectException(PageNotFoundException::class); diff --git a/tests/system/Commands/BaseCommandTest.php b/tests/system/Commands/BaseCommandTest.php index 9e9a2d3408a0..cffb7963af44 100644 --- a/tests/system/Commands/BaseCommandTest.php +++ b/tests/system/Commands/BaseCommandTest.php @@ -15,7 +15,6 @@ use CodeIgniter\Log\Logger; use CodeIgniter\Test\CIUnitTestCase; -use Config\Services; use PHPUnit\Framework\Attributes\Group; use Tests\Support\Commands\AppInfo; @@ -30,7 +29,7 @@ final class BaseCommandTest extends CIUnitTestCase protected function setUp(): void { parent::setUp(); - $this->logger = Services::logger(); + $this->logger = service('logger'); } public function testMagicIssetTrue(): void diff --git a/tests/system/Commands/CommandTest.php b/tests/system/Commands/CommandTest.php index d783d25ddab0..84fa6ecac993 100644 --- a/tests/system/Commands/CommandTest.php +++ b/tests/system/Commands/CommandTest.php @@ -17,7 +17,6 @@ use CodeIgniter\Log\Logger; use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\StreamFilterTrait; -use Config\Services; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use Tests\Support\Commands\ParamsReveal; @@ -39,8 +38,8 @@ protected function setUp(): void parent::setUp(); - $this->logger = Services::logger(); - $this->commands = Services::commands(); + $this->logger = service('logger'); + $this->commands = service('commands'); } protected function getBuffer(): string diff --git a/tests/system/Commands/RoutesTest.php b/tests/system/Commands/RoutesTest.php index 2ee9f44f1bac..7859156ccf93 100644 --- a/tests/system/Commands/RoutesTest.php +++ b/tests/system/Commands/RoutesTest.php @@ -46,7 +46,7 @@ protected function getBuffer() private function getCleanRoutes(): RouteCollection { - $routes = Services::routes(); + $routes = service('routes'); $routes->resetRoutes(); $routes->loadRoutes(); @@ -243,7 +243,7 @@ public function testRoutesCommandRouteLegacy(): void public function testRoutesCommandRouteWithRegexp(): void { - $routes = Services::routes(); + $routes = service('routes'); $routes->resetRoutes(); $routes->options('picker/(.+)', 'Options::index'); diff --git a/tests/system/Commands/ScaffoldGeneratorTest.php b/tests/system/Commands/ScaffoldGeneratorTest.php index aca2bf2a2469..fe99f2c38ccd 100644 --- a/tests/system/Commands/ScaffoldGeneratorTest.php +++ b/tests/system/Commands/ScaffoldGeneratorTest.php @@ -17,7 +17,6 @@ use CodeIgniter\Test\StreamFilterTrait; use Config\Autoload; use Config\Modules; -use Config\Services; use PHPUnit\Framework\Attributes\Group; /** @@ -31,7 +30,7 @@ final class ScaffoldGeneratorTest extends CIUnitTestCase protected function setUp(): void { $this->resetServices(); - Services::autoloader()->initialize(new Autoload(), new Modules()); + service('autoloader')->initialize(new Autoload(), new Modules()); parent::setUp(); } diff --git a/tests/system/Commands/Translation/LocalizationFinderTest.php b/tests/system/Commands/Translation/LocalizationFinderTest.php index 85bb59c7c09b..f40ae88098f5 100644 --- a/tests/system/Commands/Translation/LocalizationFinderTest.php +++ b/tests/system/Commands/Translation/LocalizationFinderTest.php @@ -16,7 +16,6 @@ use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\StreamFilterTrait; use Config\App; -use Config\Services; use Locale; use PHPUnit\Framework\Attributes\Group; @@ -68,7 +67,7 @@ public function testUpdateWithIncorrectLocaleOption(): void self::$locale = 'test_locale_incorrect'; $this->makeLocaleDirectory(); - $status = Services::commands()->run('lang:find', [ + $status = service('commands')->run('lang:find', [ 'dir' => 'Translation', 'locale' => self::$locale, ]); @@ -89,7 +88,7 @@ public function testUpdateWithIncorrectDirOption(): void { $this->makeLocaleDirectory(); - $status = Services::commands()->run('lang:find', [ + $status = service('commands')->run('lang:find', [ 'dir' => 'Translation/NotExistFolder', ]); diff --git a/tests/system/Commands/Utilities/ConfigCheckTest.php b/tests/system/Commands/Utilities/ConfigCheckTest.php index 535cb0dd0489..c075ac3df422 100644 --- a/tests/system/Commands/Utilities/ConfigCheckTest.php +++ b/tests/system/Commands/Utilities/ConfigCheckTest.php @@ -16,7 +16,6 @@ use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\StreamFilterTrait; use Config\App; -use Config\Services; use PHPUnit\Framework\Attributes\Group; /** @@ -74,7 +73,7 @@ public function testCommandConfigCheckNonexistentClass(): void public function testGetKintD(): void { - $command = new ConfigCheck(Services::logger(), Services::commands()); + $command = new ConfigCheck(service('logger'), service('commands')); $getKintD = $this->getPrivateMethodInvoker($command, 'getKintD'); $output = $getKintD(new App()); @@ -114,7 +113,7 @@ public function testGetKintD(): void public function testGetVarDump(): void { - $command = new ConfigCheck(Services::logger(), Services::commands()); + $command = new ConfigCheck(service('logger'), service('commands')); $getVarDump = $this->getPrivateMethodInvoker($command, 'getVarDump'); $output = $getVarDump(new App()); diff --git a/tests/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollectorTest.php b/tests/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollectorTest.php index a669385568dd..3413d1a83b86 100644 --- a/tests/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollectorTest.php +++ b/tests/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollectorTest.php @@ -16,7 +16,6 @@ use CodeIgniter\HTTP\Method; use CodeIgniter\Test\CIUnitTestCase; use Config\Filters; -use Config\Services; use PHPUnit\Framework\Attributes\Group; /** @@ -34,7 +33,7 @@ protected function setUp(): void private function createAutoRouteCollector(array $filterConfigFilters): AutoRouteCollector { - $routes = Services::routes(); + $routes = service('routes'); $routes->resetRoutes(); $routes->setAutoRoute(true); config('Feature')->autoRoutesImproved = true; @@ -44,7 +43,7 @@ private function createAutoRouteCollector(array $filterConfigFilters): AutoRoute /** @var Filters $filterConfig */ $filterConfig = config('Filters'); $filterConfig->filters = $filterConfigFilters; - Services::filters($filterConfig); + service('filters', $filterConfig); return new AutoRouteCollector( $namespace, diff --git a/tests/system/Commands/Utilities/Routes/FilterCollectorTest.php b/tests/system/Commands/Utilities/Routes/FilterCollectorTest.php index e3b86fcf9a56..fb6c0e5e8ebd 100644 --- a/tests/system/Commands/Utilities/Routes/FilterCollectorTest.php +++ b/tests/system/Commands/Utilities/Routes/FilterCollectorTest.php @@ -15,7 +15,6 @@ use CodeIgniter\HTTP\Method; use CodeIgniter\Test\CIUnitTestCase; -use Config\Services; use PHPUnit\Framework\Attributes\Group; /** @@ -26,7 +25,7 @@ final class FilterCollectorTest extends CIUnitTestCase { public function testGet(): void { - $routes = Services::routes(); + $routes = service('routes'); $routes->resetRoutes(); $routes->setDefaultNamespace('App\Controllers'); $routes->get('/', 'Home::index'); diff --git a/tests/system/Commands/Utilities/Routes/FilterFinderTest.php b/tests/system/Commands/Utilities/Routes/FilterFinderTest.php index d96571c6b2f2..7bba11d9c968 100644 --- a/tests/system/Commands/Utilities/Routes/FilterFinderTest.php +++ b/tests/system/Commands/Utilities/Routes/FilterFinderTest.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Commands\Utilities\Routes; -use CodeIgniter\Config\Services; use CodeIgniter\Filters\CSRF; use CodeIgniter\Filters\DebugToolbar; use CodeIgniter\Filters\Filters; @@ -47,8 +46,8 @@ protected function setUp(): void { parent::setUp(); - $this->request = Services::request(); - $this->response = Services::response(); + $this->request = service('request'); + $this->response = service('response'); $this->moduleConfig = new Modules(); $this->moduleConfig->enabled = false; @@ -56,7 +55,7 @@ protected function setUp(): void private function createRouteCollection(array $routes = []): RouteCollection { - $collection = new RouteCollection(Services::locator(), $this->moduleConfig, new Routing()); + $collection = new RouteCollection(service('locator'), $this->moduleConfig, new Routing()); $routes = ($routes !== []) ? $routes : [ 'users' => 'Users::index', diff --git a/tests/system/Commands/Utilities/Routes/SampleURIGeneratorTest.php b/tests/system/Commands/Utilities/Routes/SampleURIGeneratorTest.php index d5f3d4a542c8..6b5c10e45ea0 100644 --- a/tests/system/Commands/Utilities/Routes/SampleURIGeneratorTest.php +++ b/tests/system/Commands/Utilities/Routes/SampleURIGeneratorTest.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Commands\Utilities\Routes; -use CodeIgniter\Config\Services; use CodeIgniter\Test\CIUnitTestCase; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; @@ -49,7 +48,7 @@ public static function provideGet(): iterable public function testGetFromPlaceholderCustomPlaceholder(): void { - $routes = Services::routes(); + $routes = service('routes'); $routes->addPlaceholder( 'uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' diff --git a/tests/system/CommonFunctionsTest.php b/tests/system/CommonFunctionsTest.php index faa96e1fea4e..d708b193f56b 100644 --- a/tests/system/CommonFunctionsTest.php +++ b/tests/system/CommonFunctionsTest.php @@ -630,11 +630,11 @@ public function testViewNotSaveData(): void #[WithoutErrorHandler] public function testForceHttpsNullRequestAndResponse(): void { - $this->assertNull(Services::response()->header('Location')); + $this->assertNull(service('response')->header('Location')); - Services::response()->setCookie('force', 'cookie'); - Services::response()->setHeader('Force', 'header'); - Services::response()->setBody('default body'); + service('response')->setCookie('force', 'cookie'); + service('response')->setHeader('Force', 'header'); + service('response')->setBody('default body'); try { force_https(); @@ -726,7 +726,7 @@ public function testDWithCSP(): void $config->CSPEnabled = true; // Initialize Kint - Services::autoloader()->initializeKint(CI_DEBUG); + service('autoloader')->initializeKint(CI_DEBUG); $cliDetection = Kint::$cli_detection; Kint::$cli_detection = false; @@ -750,7 +750,7 @@ public function testTraceWithCSP(): void $config->CSPEnabled = true; // Initialize Kint - Services::autoloader()->initializeKint(CI_DEBUG); + service('autoloader')->initializeKint(CI_DEBUG); Kint::$cli_detection = false; diff --git a/tests/system/CommonHelperTest.php b/tests/system/CommonHelperTest.php index 90b417d41639..db304ecfdb70 100644 --- a/tests/system/CommonHelperTest.php +++ b/tests/system/CommonHelperTest.php @@ -82,7 +82,7 @@ private function cleanUpDummyHelpers(): void private function getMockLocator() { return $this->getMockBuilder(FileLocator::class) - ->setConstructorArgs([Services::autoloader()]) + ->setConstructorArgs([service('autoloader')]) ->onlyMethods(['search']) ->getMock(); } @@ -90,7 +90,7 @@ private function getMockLocator() public function testHelperWithFatalLocatorThrowsException(): void { // Replace the locator with one that will fail if it is called - $locator = new FatalLocator(Services::autoloader()); + $locator = new FatalLocator(service('autoloader')); Services::injectMock('locator', $locator); try { @@ -109,7 +109,7 @@ public function testHelperLoadsOnce(): void helper('baguette'); // Replace the locator with one that will fail if it is called - $locator = new FatalLocator(Services::autoloader()); + $locator = new FatalLocator(service('autoloader')); Services::injectMock('locator', $locator); try { diff --git a/tests/system/CommonSingleServiceTest.php b/tests/system/CommonSingleServiceTest.php index a8b4c6dabc32..6a07695dfbe1 100644 --- a/tests/system/CommonSingleServiceTest.php +++ b/tests/system/CommonSingleServiceTest.php @@ -48,7 +48,7 @@ public function testSingleServiceWithAtLeastOneParamSupplied(string $service): v { if ($service === 'commands') { $locator = $this->getMockBuilder(FileLocator::class) - ->setConstructorArgs([Services::autoloader()]) + ->setConstructorArgs([service('autoloader')]) ->onlyMethods(['listFiles']) ->getMock(); diff --git a/tests/system/Config/ServicesTest.php b/tests/system/Config/ServicesTest.php index 2c093724ac71..e2679757f9a9 100644 --- a/tests/system/Config/ServicesTest.php +++ b/tests/system/Config/ServicesTest.php @@ -216,7 +216,7 @@ public function testNewThrottler(): void public function testNewToolbar(): void { - $actual = Services::toolbar(null); + $actual = service('toolbar', null); $this->assertInstanceOf(Toolbar::class, $actual); } @@ -385,7 +385,7 @@ public function testFilters(): void public function testFormat(): void { - $this->assertInstanceOf(Format::class, Services::format()); + $this->assertInstanceOf(Format::class, service('format')); } public function testUnsharedFormat(): void diff --git a/tests/system/ControllerTest.php b/tests/system/ControllerTest.php index ffdcd9589f8a..55664c42c779 100644 --- a/tests/system/ControllerTest.php +++ b/tests/system/ControllerTest.php @@ -23,7 +23,6 @@ use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Validation\Exceptions\ValidationException; use Config\App; -use Config\Services; use Config\Validation as ValidationConfig; use PHPUnit\Framework\Attributes\BackupGlobals; use PHPUnit\Framework\Attributes\Group; @@ -61,7 +60,7 @@ protected function setUp(): void $config = new App(); $this->request = new IncomingRequest($config, new SiteURI($config), null, new UserAgent()); $this->response = new Response($config); - $this->logger = Services::logger(); + $this->logger = service('logger'); } public function testConstructor(): void @@ -149,7 +148,7 @@ public function testValidateWithStringRulesFoundReadMessagesFromValidationConfig $method = $this->getPrivateMethodInvoker($this->controller, 'validate'); $this->assertFalse($method('signup')); - $this->assertSame('You must choose a username.', Services::validation()->getError('username')); + $this->assertSame('You must choose a username.', service('validation')->getError('username')); } public function testValidateWithStringRulesFoundUseMessagesParameter(): void @@ -174,7 +173,7 @@ public function testValidateWithStringRulesFoundUseMessagesParameter(): void 'required' => 'You must choose a username.', ], ])); - $this->assertSame('You must choose a username.', Services::validation()->getError('username')); + $this->assertSame('You must choose a username.', service('validation')->getError('username')); } public function testValidateData(): void @@ -196,7 +195,7 @@ public function testValidateData(): void $this->assertFalse($method($data, $rule)); $this->assertSame( 'The password field must be at least 10 characters in length.', - Services::validation()->getError('password') + service('validation')->getError('password') ); } @@ -225,11 +224,11 @@ public function testValidateDataWithCustomErrorMessage(): void $this->assertFalse($method($data, $rules, $errors)); $this->assertSame( '"username" must be 3 letters or longer.', - Services::validation()->getError('username') + service('validation')->getError('username') ); $this->assertSame( 'The password field must be at least 10 characters in length.', - Services::validation()->getError('password') + service('validation')->getError('password') ); } @@ -263,11 +262,11 @@ public function testValidateDataWithCustomErrorMessageLabeledStyle(): void $this->assertFalse($method($data, $rules)); $this->assertSame( '"Username" must be 3 letters or longer.', - Services::validation()->getError('username') + service('validation')->getError('username') ); $this->assertSame( 'The Password field must be at least 10 characters in length.', - Services::validation()->getError('password') + service('validation')->getError('password') ); } diff --git a/tests/system/Database/DatabaseTestCase/DatabaseTestCaseMigrationOnce1Test.php b/tests/system/Database/DatabaseTestCase/DatabaseTestCaseMigrationOnce1Test.php index 8a0980f853a9..c3e744749909 100644 --- a/tests/system/Database/DatabaseTestCase/DatabaseTestCaseMigrationOnce1Test.php +++ b/tests/system/Database/DatabaseTestCase/DatabaseTestCaseMigrationOnce1Test.php @@ -16,7 +16,6 @@ use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\DatabaseTestTrait; use Config\Database; -use Config\Services; use PHPUnit\Framework\Attributes\Group; /** @@ -68,7 +67,7 @@ protected function setUp(): void protected function setUpAddNamespace(): void { - Services::autoloader()->addNamespace( + service('autoloader')->addNamespace( 'Tests\Support\MigrationTestMigrations', SUPPORTPATH . 'MigrationTestMigrations' ); diff --git a/tests/system/Database/DatabaseTestCase/DatabaseTestCaseMigrationOnce2Test.php b/tests/system/Database/DatabaseTestCase/DatabaseTestCaseMigrationOnce2Test.php index 5c4013e055e1..7820b83c06c7 100644 --- a/tests/system/Database/DatabaseTestCase/DatabaseTestCaseMigrationOnce2Test.php +++ b/tests/system/Database/DatabaseTestCase/DatabaseTestCaseMigrationOnce2Test.php @@ -16,7 +16,6 @@ use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\DatabaseTestTrait; use Config\Database; -use Config\Services; use PHPUnit\Framework\Attributes\Group; /** @@ -68,7 +67,7 @@ protected function setUp(): void protected function setUpAddNamespace(): void { - Services::autoloader()->addNamespace( + service('autoloader')->addNamespace( 'Tests\Support\MigrationTestMigrations', SUPPORTPATH . 'MigrationTestMigrations' ); diff --git a/tests/system/Database/DatabaseTestCaseTest.php b/tests/system/Database/DatabaseTestCaseTest.php index c6a03022df72..76867e852e23 100644 --- a/tests/system/Database/DatabaseTestCaseTest.php +++ b/tests/system/Database/DatabaseTestCaseTest.php @@ -16,7 +16,6 @@ use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\DatabaseTestTrait; use Config\Database; -use Config\Services; use PHPUnit\Framework\Attributes\Group; use Tests\Support\Database\Seeds\AnotherSeeder; use Tests\Support\Database\Seeds\CITestSeeder; @@ -73,7 +72,7 @@ protected function setUp(): void protected function setUpAddNamespace(): void { - Services::autoloader()->addNamespace( + service('autoloader')->addNamespace( 'Tests\Support\MigrationTestMigrations', SUPPORTPATH . 'MigrationTestMigrations' ); diff --git a/tests/system/Database/Migrations/MigrationRunnerTest.php b/tests/system/Database/Migrations/MigrationRunnerTest.php index 547eec670ce4..0ecd2ca0b051 100644 --- a/tests/system/Database/Migrations/MigrationRunnerTest.php +++ b/tests/system/Database/Migrations/MigrationRunnerTest.php @@ -21,7 +21,6 @@ use CodeIgniter\Test\DatabaseTestTrait; use Config\Database; use Config\Migrations; -use Config\Services; use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStreamDirectory; use PHPUnit\Framework\Attributes\Group; @@ -60,7 +59,7 @@ protected function setUp(): void protected function setUpAddNamespace(): void { - Services::autoloader()->addNamespace( + service('autoloader')->addNamespace( 'Tests\Support\MigrationTestMigrations', SUPPORTPATH . 'MigrationTestMigrations' ); diff --git a/tests/system/Debug/ExceptionHandlerTest.php b/tests/system/Debug/ExceptionHandlerTest.php index 85eaed74621b..ddb1304c3d7e 100644 --- a/tests/system/Debug/ExceptionHandlerTest.php +++ b/tests/system/Debug/ExceptionHandlerTest.php @@ -107,8 +107,8 @@ public function testHandleWebPageNotFoundExceptionDoNotAcceptHTML(): void { $exception = PageNotFoundException::forControllerNotFound('Foo', 'bar'); - $request = Services::incomingrequest(null, false); - $response = Services::response(null, false); + $request = service('incomingrequest', null, false); + $response = service('response', null, false); $response->pretend(); ob_start(); @@ -126,9 +126,9 @@ public function testHandleWebPageNotFoundExceptionAcceptHTML(): void { $exception = PageNotFoundException::forControllerNotFound('Foo', 'bar'); - $request = Services::incomingrequest(null, false); + $request = service('incomingrequest', null, false); $request->setHeader('accept', 'text/html'); - $response = Services::response(null, false); + $response = service('response', null, false); $response->pretend(); ob_start(); @@ -144,7 +144,7 @@ public function testHandleCLIPageNotFoundException(): void $request = Services::clirequest(null, false); $request->setHeader('accept', 'text/html'); - $response = Services::response(null, false); + $response = service('response', null, false); $response->pretend(); $this->handler->handle($exception, $request, $response, 404, EXIT_ERROR); diff --git a/tests/system/Filters/CSRFTest.php b/tests/system/Filters/CSRFTest.php index c0d85b02150d..d1977e4f5cea 100644 --- a/tests/system/Filters/CSRFTest.php +++ b/tests/system/Filters/CSRFTest.php @@ -51,7 +51,7 @@ public function testDoNotCheckCliRequest(): void ]; $this->request = Services::clirequest(null, false); - $this->response = Services::response(); + $this->response = service('response'); $filters = new Filters($this->config, $this->request, $this->response); $uri = 'admin/foo/bar'; @@ -68,8 +68,8 @@ public function testPassGetRequest(): void 'after' => [], ]; - $this->request = Services::incomingrequest(null, false); - $this->response = Services::response(); + $this->request = service('incomingrequest', null, false); + $this->response = service('response'); $filters = new Filters($this->config, $this->request, $this->response); $uri = 'admin/foo/bar'; diff --git a/tests/system/Filters/CorsTest.php b/tests/system/Filters/CorsTest.php index 78023ddfdadc..bbbbefc0b413 100644 --- a/tests/system/Filters/CorsTest.php +++ b/tests/system/Filters/CorsTest.php @@ -22,7 +22,6 @@ use CodeIgniter\HTTP\UserAgent; use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\Mock\MockAppConfig; -use Config\Services; use PHPUnit\Framework\Attributes\Group; /** @@ -145,10 +144,10 @@ private function handle(RequestInterface $request): ResponseInterface return $response; } - $response ??= Services::response(); + $response ??= service('response'); $response = $this->cors->after($request, $response); - $response ??= Services::response(); + $response ??= service('response'); $this->response = $response; diff --git a/tests/system/Filters/DebugToolbarTest.php b/tests/system/Filters/DebugToolbarTest.php index 6cb716ee9556..e395f5ba200c 100644 --- a/tests/system/Filters/DebugToolbarTest.php +++ b/tests/system/Filters/DebugToolbarTest.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Filters; -use CodeIgniter\Config\Services; use CodeIgniter\HTTP\CLIRequest; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\Response; @@ -40,8 +39,8 @@ protected function setUp(): void { parent::setUp(); - $this->request = Services::request(); - $this->response = Services::response(); + $this->request = service('request'); + $this->response = service('response'); } public function testDebugToolbarFilter(): void diff --git a/tests/system/Filters/FiltersTest.php b/tests/system/Filters/FiltersTest.php index 3a35920989e5..d4a390c113e0 100644 --- a/tests/system/Filters/FiltersTest.php +++ b/tests/system/Filters/FiltersTest.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Filters; -use CodeIgniter\Config\Services; use CodeIgniter\Exceptions\ConfigException; use CodeIgniter\Filters\Exceptions\FilterException; use CodeIgniter\Filters\fixtures\GoogleCurious; @@ -66,16 +65,16 @@ protected function setUp(): void 'App' => APPPATH, 'Tests\Support' => TESTPATH . '_support', ]; - Services::autoloader()->addNamespace($defaults); + service('autoloader')->addNamespace($defaults); $_SERVER = []; - $this->response = Services::response(); + $this->response = service('response'); } private function createFilters(FiltersConfig $config, $request = null): Filters { - $request ??= Services::request(); + $request ??= service('request'); return new Filters($config, $request, $this->response); } diff --git a/tests/system/Filters/HoneypotTest.php b/tests/system/Filters/HoneypotTest.php index 79519709d72c..43d85094dd04 100644 --- a/tests/system/Filters/HoneypotTest.php +++ b/tests/system/Filters/HoneypotTest.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Filters; -use CodeIgniter\Config\Services; use CodeIgniter\Honeypot\Exceptions\HoneypotException; use CodeIgniter\HTTP\CLIRequest; use CodeIgniter\HTTP\IncomingRequest; @@ -62,8 +61,8 @@ public function testBeforeTriggered(): void 'after' => [], ]; - $this->request = Services::request(null, false); - $this->response = Services::response(); + $this->request = service('request', null, false); + $this->response = service('response'); $filters = new Filters($this->config, $this->request, $this->response); $uri = 'admin/foo/bar'; @@ -80,8 +79,8 @@ public function testBeforeClean(): void ]; unset($_POST[$this->honey->name]); - $this->request = Services::request(null, false); - $this->response = Services::response(); + $this->request = service('request', null, false); + $this->response = service('response'); $expected = $this->request; @@ -101,8 +100,8 @@ public function testAfter(): void 'after' => ['honeypot'], ]; - $this->request = Services::request(null, false); - $this->response = Services::response(); + $this->request = service('request', null, false); + $this->response = service('response'); $filters = new Filters($this->config, $this->request, $this->response); $uri = 'admin/foo/bar'; @@ -121,8 +120,8 @@ public function testAfterNotApplicable(): void 'after' => ['honeypot'], ]; - $this->request = Services::request(null, false); - $this->response = Services::response(); + $this->request = service('request', null, false); + $this->response = service('response'); $filters = new Filters($this->config, $this->request, $this->response); $uri = 'admin/foo/bar'; diff --git a/tests/system/Filters/SecureHeadersTest.php b/tests/system/Filters/SecureHeadersTest.php index 48ff8bb7d04f..5b446d523647 100644 --- a/tests/system/Filters/SecureHeadersTest.php +++ b/tests/system/Filters/SecureHeadersTest.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Filters; -use CodeIgniter\Config\Services; use CodeIgniter\Test\CIUnitTestCase; use PHPUnit\Framework\Attributes\Group; @@ -26,8 +25,8 @@ final class SecureHeadersTest extends CIUnitTestCase public function testAfter(): void { $filter = new SecureHeaders(); - $request = Services::request(null, false); - $response = Services::response(null, false); + $request = service('request', null, false); + $response = service('response', null, false); $filter->after($request, $response); diff --git a/tests/system/Filters/fixtures/GoogleYou.php b/tests/system/Filters/fixtures/GoogleYou.php index c01c5d534435..7d2913866b30 100644 --- a/tests/system/Filters/fixtures/GoogleYou.php +++ b/tests/system/Filters/fixtures/GoogleYou.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Filters\fixtures; -use CodeIgniter\Config\Services; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; @@ -22,7 +21,7 @@ class GoogleYou implements FilterInterface { public function before(RequestInterface $request, $arguments = null) { - $response = Services::response(); + $response = service('response'); $response->setBody('http://google.com'); return $response; diff --git a/tests/system/HTTP/CorsTest.php b/tests/system/HTTP/CorsTest.php index 9f2a7280bee4..bdb29567df59 100644 --- a/tests/system/HTTP/CorsTest.php +++ b/tests/system/HTTP/CorsTest.php @@ -14,7 +14,6 @@ namespace CodeIgniter\HTTP; use CodeIgniter\Test\CIUnitTestCase; -use Config\Services; use PHPUnit\Framework\Attributes\Group; /** @@ -41,7 +40,7 @@ private function createCors(array $config = []): Cors private function createRequest(): IncomingRequest { - return Services::incomingrequest(null, false); + return service('incomingrequest', null, false); } /** @@ -103,7 +102,7 @@ public function testHandlePreflightRequestSingleAllowedOrigin(): void ->setHeader('Access-Control-Request-Method', 'PUT') ->setHeader('Origin', 'http://localhost:8080'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->handlePreflightRequest($request, $response); @@ -138,7 +137,7 @@ public function testHandlePreflightRequestMultipleAllowedOriginsAllowed(): void ->setHeader('Access-Control-Request-Method', 'PUT') ->setHeader('Origin', 'https://api.example.com'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->handlePreflightRequest($request, $response); @@ -175,7 +174,7 @@ public function testHandlePreflightRequestMultipleAllowedOriginsAllowedAlreadyVa ->setHeader('Access-Control-Request-Method', 'PUT') ->setHeader('Origin', 'https://api.example.com'); - $response = Services::response(null, false) + $response = service('response', null, false) ->setHeader('Vary', 'Accept-Language'); $response = $cors->handlePreflightRequest($request, $response); @@ -213,7 +212,7 @@ public function testHandlePreflightRequestMultipleAllowedOriginsNotAllowed(): vo ->setHeader('Access-Control-Request-Method', 'PUT') ->setHeader('Origin', 'https://bad.site.com'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->handlePreflightRequest($request, $response); @@ -239,7 +238,7 @@ public function testHandlePreflightRequestAllowedOriginsPatternsAllowed(): void ->setHeader('Access-Control-Request-Method', 'PUT') ->setHeader('Origin', 'https://api.example.com'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->handlePreflightRequest($request, $response); @@ -276,7 +275,7 @@ public function testHandlePreflightRequestAllowedOriginsPatternsNotAllowed(): vo ->setHeader('Access-Control-Request-Method', 'PUT') ->setHeader('Origin', 'https://bad.site.com'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->handlePreflightRequest($request, $response); @@ -303,7 +302,7 @@ public function testHandlePreflightRequestSingleAllowedOriginWithCredentials(): ->setHeader('Access-Control-Request-Method', 'PUT') ->setHeader('Origin', 'http://localhost:8080'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->handlePreflightRequest($request, $response); @@ -340,7 +339,7 @@ public function testAddResponseHeadersSingleAllowedOriginSimpleRequest(): void ->withMethod('GET') ->setHeader('Origin', 'http://localhost:8080'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->addResponseHeaders($request, $response); @@ -371,7 +370,7 @@ public function testAddResponseHeadersSingleAllowedOriginRealRequest(): void ->withMethod('POST') ->setHeader('Origin', 'http://localhost:8080'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->addResponseHeaders($request, $response); @@ -395,7 +394,7 @@ public function testAddResponseHeadersSingleAllowedOriginWithCredentials(): void ->setHeader('Cookie', 'pageAccess=2') ->setHeader('Origin', 'http://localhost:8080'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->addResponseHeaders($request, $response); @@ -423,7 +422,7 @@ public function testAddResponseHeadersSingleAllowedOriginWithExposeHeaders(): vo ->withMethod('GET') ->setHeader('Origin', 'http://localhost:8080'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->addResponseHeaders($request, $response); @@ -449,7 +448,7 @@ public function testAddResponseHeadersMultipleAllowedOriginsAllowed(): void ->withMethod('PUT') ->setHeader('Origin', 'https://api.example.com'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->addResponseHeaders($request, $response); @@ -481,7 +480,7 @@ public function testAddResponseHeadersMultipleAllowedOriginsAllowedAlreadyVary() ->withMethod('PUT') ->setHeader('Origin', 'https://api.example.com'); - $response = Services::response(null, false) + $response = service('response', null, false) ->setHeader('Vary', 'Accept-Language'); $response = $cors->addResponseHeaders($request, $response); @@ -508,7 +507,7 @@ public function testAddResponseHeadersMultipleAllowedOriginsNotAllowed(): void ->withMethod('PUT') ->setHeader('Origin', 'https://bad.site.com'); - $response = Services::response(null, false); + $response = service('response', null, false); $response = $cors->addResponseHeaders($request, $response); diff --git a/tests/system/HTTP/RedirectExceptionTest.php b/tests/system/HTTP/RedirectExceptionTest.php index e77c0ea060d3..cd90a9aa148c 100644 --- a/tests/system/HTTP/RedirectExceptionTest.php +++ b/tests/system/HTTP/RedirectExceptionTest.php @@ -46,7 +46,7 @@ protected function tearDown(): void public function testResponse(): void { $response = (new RedirectException( - Services::response() + service('response') ->redirect('redirect') ->setCookie('cookie', 'value') ->setHeader('Redirect-Header', 'value') @@ -65,12 +65,12 @@ public function testResponseWithoutLocation(): void 'The Response object passed to RedirectException does not contain a redirect address.' ); - new RedirectException(Services::response()); + new RedirectException(service('response')); } public function testResponseWithoutStatusCode(): void { - $response = (new RedirectException(Services::response()->setHeader('Location', 'location')))->getResponse(); + $response = (new RedirectException(service('response')->setHeader('Location', 'location')))->getResponse(); $this->assertSame('location', $response->getHeaderLine('location')); $this->assertSame(302, $response->getStatusCode()); @@ -82,7 +82,7 @@ public function testLoggingLocationHeader(): void $uri = 'http://location'; $expected = 'INFO - ' . Time::now()->format('Y-m-d') . ' --> REDIRECTED ROUTE at ' . $uri; - $response = (new RedirectException(Services::response()->redirect($uri)))->getResponse(); + $response = (new RedirectException(service('response')->redirect($uri)))->getResponse(); $logs = TestHandler::getLogs(); @@ -97,7 +97,7 @@ public function testLoggingRefreshHeader(): void $uri = 'http://location'; $expected = 'INFO - ' . Time::now()->format('Y-m-d') . ' --> REDIRECTED ROUTE at ' . $uri; - $response = (new RedirectException(Services::response()->redirect($uri, 'refresh')))->getResponse(); + $response = (new RedirectException(service('response')->redirect($uri, 'refresh')))->getResponse(); $logs = TestHandler::getLogs(); diff --git a/tests/system/HTTP/RedirectResponseTest.php b/tests/system/HTTP/RedirectResponseTest.php index 41ac8139bdc4..1614244d762b 100644 --- a/tests/system/HTTP/RedirectResponseTest.php +++ b/tests/system/HTTP/RedirectResponseTest.php @@ -54,7 +54,7 @@ protected function setUp(): void $this->config = new App(); $this->config->baseURL = 'http://example.com/'; - $this->routes = new RouteCollection(Services::locator(), new Modules(), new Routing()); + $this->routes = new RouteCollection(service('locator'), new Modules(), new Routing()); Services::injectMock('routes', $this->routes); $this->request = new MockIncomingRequest( @@ -237,7 +237,7 @@ public function testWithCookies(): void { $_SESSION = []; - $baseResponse = Services::response(); + $baseResponse = service('response'); $baseResponse->setCookie('foo', 'bar'); $response = new RedirectResponse(new App()); diff --git a/tests/system/HTTP/ResponseTest.php b/tests/system/HTTP/ResponseTest.php index bb939741dda1..3137620029bc 100644 --- a/tests/system/HTTP/ResponseTest.php +++ b/tests/system/HTTP/ResponseTest.php @@ -18,7 +18,6 @@ use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\Mock\MockResponse; use Config\App; -use Config\Services; use DateTime; use DateTimeZone; use PHPUnit\Framework\Attributes\DataProvider; @@ -169,7 +168,7 @@ public function testSetLink(): void $this->resetServices(); $response = new Response($config); - $pager = Services::pager(); + $pager = service('pager'); $pager->store('default', 3, 10, 200); $response->setLink($pager); @@ -390,7 +389,7 @@ public function testJSONWithArray(): void 3, ], ]; - $expected = Services::format()->getFormatter('application/json')->format($body); + $expected = service('format')->getFormatter('application/json')->format($body); $response = new Response(new App()); $response->setJSON($body); @@ -409,7 +408,7 @@ public function testJSONGetFromNormalBody(): void 3, ], ]; - $expected = Services::format()->getFormatter('application/json')->format($body); + $expected = service('format')->getFormatter('application/json')->format($body); $response = new Response(new App()); $response->setBody($body); @@ -427,7 +426,7 @@ public function testXMLWithArray(): void 3, ], ]; - $expected = Services::format()->getFormatter('application/xml')->format($body); + $expected = service('format')->getFormatter('application/xml')->format($body); $response = new Response(new App()); $response->setXML($body); @@ -446,7 +445,7 @@ public function testXMLGetFromNormalBody(): void 3, ], ]; - $expected = Services::format()->getFormatter('application/xml')->format($body); + $expected = service('format')->getFormatter('application/xml')->format($body); $response = new Response(new App()); $response->setBody($body); diff --git a/tests/system/HTTP/URITest.php b/tests/system/HTTP/URITest.php index 8a953ee3cab1..517e2d888973 100644 --- a/tests/system/HTTP/URITest.php +++ b/tests/system/HTTP/URITest.php @@ -1046,7 +1046,7 @@ public function testBasedNoIndex(): void $config->indexPage = ''; Factories::injectMock('config', 'App', $config); - $request = Services::request($config); + $request = service('request', $config); Services::injectMock('request', $request); // going through request @@ -1080,7 +1080,7 @@ public function testBasedWithIndex(): void $config->indexPage = 'index.php'; Factories::injectMock('config', 'App', $config); - $request = Services::request($config); + $request = service('request', $config); Services::injectMock('request', $request); // going through request @@ -1120,7 +1120,7 @@ public function testForceGlobalSecureRequests(): void $config->forceGlobalSecureRequests = true; Factories::injectMock('config', 'App', $config); - $request = Services::request($config); + $request = service('request', $config); Services::injectMock('request', $request); // Detected by request diff --git a/tests/system/Helpers/CookieHelperTest.php b/tests/system/Helpers/CookieHelperTest.php index b672e4da9104..c6bfba193054 100644 --- a/tests/system/Helpers/CookieHelperTest.php +++ b/tests/system/Helpers/CookieHelperTest.php @@ -49,7 +49,7 @@ protected function setUp(): void $this->expire = 9999; Services::injectMock('response', new MockResponse(new App())); - $this->response = Services::response(); + $this->response = service('response'); $request = new IncomingRequest(new App(), new SiteURI(new App()), null, new UserAgent()); Services::injectMock('request', $request); diff --git a/tests/system/Helpers/FormHelperTest.php b/tests/system/Helpers/FormHelperTest.php index fc9eb0ab021a..9023fd73ac6f 100644 --- a/tests/system/Helpers/FormHelperTest.php +++ b/tests/system/Helpers/FormHelperTest.php @@ -48,7 +48,7 @@ private function setRequest(): void $uri = new SiteURI($config); Services::injectMock('uri', $uri); - $request = Services::request($config); + $request = service('request', $config); Services::injectMock('request', $request); } @@ -1050,7 +1050,7 @@ public function testValidationErrorsFromSession(): void public function testValidationErrorsFromValidation(): void { - $validation = Services::validation(); + $validation = service('validation'); $validation->setRule('id', 'ID', 'required')->run([]); $this->assertSame(['id' => 'The ID field is required.'], validation_errors()); @@ -1058,7 +1058,7 @@ public function testValidationErrorsFromValidation(): void public function testValidationListErrors(): void { - $validation = Services::validation(); + $validation = service('validation'); $validation->setRule('id', 'ID', 'required')->run([]); $html = validation_list_errors(); @@ -1068,7 +1068,7 @@ public function testValidationListErrors(): void public function testValidationShowError(): void { - $validation = Services::validation(); + $validation = service('validation'); $validation->setRule('id', 'ID', 'required')->run([]); $html = validation_show_error('id'); @@ -1081,7 +1081,7 @@ public function testValidationShowError(): void public function testValidationShowErrorForWildcards(): void { - $validation = Services::validation(); + $validation = service('validation'); $validation->setRule('user.*.name', 'Name', 'required') ->run([ 'user' => [ diff --git a/tests/system/Helpers/URLHelper/MiscUrlTest.php b/tests/system/Helpers/URLHelper/MiscUrlTest.php index a006ec80c6ae..e12b7873f9e2 100644 --- a/tests/system/Helpers/URLHelper/MiscUrlTest.php +++ b/tests/system/Helpers/URLHelper/MiscUrlTest.php @@ -44,7 +44,7 @@ protected function setUp(): void parent::setUp(); Services::reset(true); - Services::routes()->loadRoutes(); + service('routes')->loadRoutes(); // Set a common base configuration (overriden by individual tests) $this->config = new App(); @@ -956,7 +956,7 @@ public function testUrlToMissingArgument(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Missing argument for "(:alpha)" in route "(:alpha)/login".'); - $routes = Services::routes(); + $routes = service('routes'); $routes->group('(:alpha)', static function ($routes): void { $routes->match(['GET'], 'login', 'Common\LoginController::loginView', ['as' => 'loginURL']); }); diff --git a/tests/system/Honeypot/HoneypotTest.php b/tests/system/Honeypot/HoneypotTest.php index ee048a1a785c..fdcf198d7608 100644 --- a/tests/system/Honeypot/HoneypotTest.php +++ b/tests/system/Honeypot/HoneypotTest.php @@ -14,7 +14,6 @@ namespace CodeIgniter\Honeypot; use CodeIgniter\Config\Factories; -use CodeIgniter\Config\Services; use CodeIgniter\Filters\Filters; use CodeIgniter\Honeypot\Exceptions\HoneypotException; use CodeIgniter\HTTP\CLIRequest; @@ -54,8 +53,8 @@ protected function setUp(): void $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST[$this->config->name] = 'hey'; - $this->request = Services::request(null, false); - $this->response = Services::response(); + $this->request = service('request', null, false); + $this->response = service('response'); } public function testAttachHoneypot(): void @@ -99,7 +98,7 @@ public function testAttachHoneypotAndContainerWithCSP(): void $config = new App(); $config->CSPEnabled = true; Factories::injectMock('config', 'App', $config); - $this->response = Services::response($config, false); + $this->response = service('response', $config, false); $this->config = new HoneypotConfig(); $this->honeypot = new Honeypot($this->config); @@ -118,7 +117,7 @@ public function testNotAttachHoneypotWithCSP(): void $config = new App(); $config->CSPEnabled = true; Factories::injectMock('config', 'App', $config); - $this->response = Services::response($config, false); + $this->response = service('response', $config, false); $this->config = new HoneypotConfig(); $this->honeypot = new Honeypot($this->config); @@ -132,7 +131,7 @@ public function testNotAttachHoneypotWithCSP(): void public function testHasntContent(): void { unset($_POST[$this->config->name]); - $this->request = Services::request(); + $this->request = service('request'); $this->assertFalse($this->honeypot->hasContent($this->request)); } diff --git a/tests/system/Language/LanguageTest.php b/tests/system/Language/LanguageTest.php index 8dd3a290b286..cb1cfff267aa 100644 --- a/tests/system/Language/LanguageTest.php +++ b/tests/system/Language/LanguageTest.php @@ -15,7 +15,6 @@ use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\Mock\MockLanguage; -use Config\Services; use MessageFormatter; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; @@ -296,7 +295,7 @@ public function testLanguageSameKeyAndFileName(): void public function testGetLocale(): void { - $this->lang = Services::language('en', false); + $this->lang = service('language', 'en', false); $this->assertSame('en', $this->lang->getLocale()); } @@ -353,7 +352,7 @@ public function testBundleUniqueKeys($bundle): void public function testBaseFallbacks(): void { - $this->lang = Services::language('en-ZZ', false); + $this->lang = service('language', 'en-ZZ', false); // key is in both base and variant; should pick variant $this->assertSame("It's made of cheese", $this->lang->getLine('More.notaMoon')); @@ -372,7 +371,7 @@ public function testBaseFallbacks(): void */ public function testLangKeepLocale(): void { - $this->lang = Services::language('en', true); + $this->lang = service('language', 'en', true); lang('Language.languageGetLineInvalidArgumentException'); $this->assertSame('en', $this->lang->getLocale()); @@ -399,7 +398,7 @@ public function testLangKeepLocale(): void */ public function testAllTheWayFallbacks(): void { - $this->lang = Services::language('ab-CD', false); + $this->lang = service('language', 'ab-CD', false); $this->assertSame('Allin.none', $this->lang->getLine('Allin.none')); $this->assertSame('Pyramid of Giza', $this->lang->getLine('Allin.one')); $this->assertSame('gluttony', $this->lang->getLine('Allin.two')); diff --git a/tests/system/Log/Handlers/ChromeLoggerHandlerTest.php b/tests/system/Log/Handlers/ChromeLoggerHandlerTest.php index 3dc0b1ccee80..73461c3c96ed 100644 --- a/tests/system/Log/Handlers/ChromeLoggerHandlerTest.php +++ b/tests/system/Log/Handlers/ChromeLoggerHandlerTest.php @@ -56,7 +56,7 @@ public function testSendLogs(): void $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); $logger->sendLogs(); - $response = Services::response(null, true); + $response = service('response', null, true); $this->assertTrue($response->hasHeader('X-ChromeLogger-Data')); } diff --git a/tests/system/Models/ValidationModelRuleGroupTest.php b/tests/system/Models/ValidationModelRuleGroupTest.php index b08f73c9a04e..34e51bcf07bc 100644 --- a/tests/system/Models/ValidationModelRuleGroupTest.php +++ b/tests/system/Models/ValidationModelRuleGroupTest.php @@ -15,7 +15,6 @@ use CodeIgniter\Database\BaseConnection; use CodeIgniter\Model; -use Config\Services; use PHPUnit\Framework\Attributes\Group; use stdClass; use Tests\Support\Config\Validation; @@ -40,7 +39,7 @@ protected function setUp(): void protected function createModel(string $modelName, ?BaseConnection $db = null): Model { $config = new Validation(); - $validation = new \CodeIgniter\Validation\Validation($config, Services::renderer()); + $validation = new \CodeIgniter\Validation\Validation($config, service('renderer')); $this->db = $db ?? $this->db; $this->model = new $modelName($this->db, $validation); diff --git a/tests/system/Pager/PagerTest.php b/tests/system/Pager/PagerTest.php index c652a3793738..13d0d846f07c 100644 --- a/tests/system/Pager/PagerTest.php +++ b/tests/system/Pager/PagerTest.php @@ -64,7 +64,7 @@ private function createPager(string $requestUri): void Services::injectMock('request', $request); $this->config = new PagerConfig(); - $this->pager = new Pager($this->config, Services::renderer()); + $this->pager = new Pager($this->config, service('renderer')); } public function testSetPathRemembersPath(): void @@ -493,7 +493,7 @@ public function testBasedURI(): void Services::injectMock('request', $request); $this->config = new PagerConfig(); - $this->pager = new Pager($this->config, Services::renderer()); + $this->pager = new Pager($this->config, service('renderer')); $_GET['page_foo'] = 2; diff --git a/tests/system/RESTful/ResourceControllerTest.php b/tests/system/RESTful/ResourceControllerTest.php index 77ca329248dc..580909cdff76 100644 --- a/tests/system/RESTful/ResourceControllerTest.php +++ b/tests/system/RESTful/ResourceControllerTest.php @@ -69,14 +69,14 @@ private function createCodeigniter(): void $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1'; // Inject mock router. - $this->routes = Services::routes(); + $this->routes = service('routes'); $this->routes->resource('work', ['controller' => '\\' . Worker::class]); Services::injectMock('routes', $this->routes); $config = new App(); $this->codeigniter = new MockCodeIgniter($config); - $response = Services::response(); + $response = service('response'); $response->pretend(); } diff --git a/tests/system/RESTful/ResourcePresenterTest.php b/tests/system/RESTful/ResourcePresenterTest.php index e5614adfd1c0..3617e7a18e67 100644 --- a/tests/system/RESTful/ResourcePresenterTest.php +++ b/tests/system/RESTful/ResourcePresenterTest.php @@ -63,7 +63,7 @@ private function createCodeigniter(): void $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1'; // Inject mock router. - $this->routes = Services::routes(); + $this->routes = service('routes'); $this->routes->presenter('work', ['controller' => '\\' . Worker2::class]); Services::injectMock('routes', $this->routes); diff --git a/tests/system/Router/AutoRouterImprovedTest.php b/tests/system/Router/AutoRouterImprovedTest.php index 0f4c75162a2f..56e334dc96d9 100644 --- a/tests/system/Router/AutoRouterImprovedTest.php +++ b/tests/system/Router/AutoRouterImprovedTest.php @@ -14,7 +14,6 @@ namespace CodeIgniter\Router; use CodeIgniter\Config\Factories; -use CodeIgniter\Config\Services; use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\HTTP\Method; use CodeIgniter\Router\Controllers\BlogController; @@ -42,7 +41,7 @@ protected function setUp(): void $moduleConfig = new Modules(); $moduleConfig->enabled = false; - $this->collection = new RouteCollection(Services::locator(), $moduleConfig, new Routing()); + $this->collection = new RouteCollection(service('locator'), $moduleConfig, new Routing()); } private function createNewAutoRouter(string $namespace = 'CodeIgniter\Router\Controllers'): AutoRouterImproved diff --git a/tests/system/Router/DefinedRouteCollectorTest.php b/tests/system/Router/DefinedRouteCollectorTest.php index 7c493c028512..3c1d29abc023 100644 --- a/tests/system/Router/DefinedRouteCollectorTest.php +++ b/tests/system/Router/DefinedRouteCollectorTest.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Router; -use CodeIgniter\Config\Services; use CodeIgniter\HTTP\Method; use CodeIgniter\Test\CIUnitTestCase; use Config\Modules; @@ -34,9 +33,9 @@ private function createRouteCollection(array $config = [], $moduleConfig = null) ]; $config = array_merge($config, $defaults); - Services::autoloader()->addNamespace($config); + service('autoloader')->addNamespace($config); - $loader = Services::locator(); + $loader = service('locator'); if ($moduleConfig === null) { $moduleConfig = new Modules(); diff --git a/tests/system/Router/RouteCollectionReverseRouteTest.php b/tests/system/Router/RouteCollectionReverseRouteTest.php index ebe344293f46..ca70b315f5b6 100644 --- a/tests/system/Router/RouteCollectionReverseRouteTest.php +++ b/tests/system/Router/RouteCollectionReverseRouteTest.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Router; -use CodeIgniter\Config\Services; use CodeIgniter\HTTP\Method; use CodeIgniter\Router\Exceptions\RouterException; use CodeIgniter\Test\CIUnitTestCase; @@ -44,9 +43,9 @@ protected function getCollector(array $config = [], array $files = [], $moduleCo ]; $config = array_merge($config, $defaults); - Services::autoloader()->addNamespace($config); + service('autoloader')->addNamespace($config); - $loader = Services::locator(); + $loader = service('locator'); if ($moduleConfig === null) { $moduleConfig = new Modules(); diff --git a/tests/system/Router/RouteCollectionTest.php b/tests/system/Router/RouteCollectionTest.php index bfd53a3ebf7c..5e398cfdf2a3 100644 --- a/tests/system/Router/RouteCollectionTest.php +++ b/tests/system/Router/RouteCollectionTest.php @@ -14,7 +14,6 @@ namespace CodeIgniter\Router; use App\Controllers\Product; -use CodeIgniter\Config\Services; use CodeIgniter\controller; use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\HTTP\Method; @@ -47,9 +46,9 @@ protected function getCollector(array $config = [], array $files = [], $moduleCo ]; $config = array_merge($config, $defaults); - Services::autoloader()->addNamespace($config); + service('autoloader')->addNamespace($config); - $loader = Services::locator(); + $loader = service('locator'); if ($moduleConfig === null) { $moduleConfig = new Modules(); @@ -148,7 +147,7 @@ public function testAddIgnoresDefaultNamespaceWhenExists(): void public function testAddWorksWithCurrentHTTPMethods(): void { - Services::request()->setMethod(Method::GET); + service('request')->setMethod(Method::GET); $routes = $this->getCollector(); @@ -180,7 +179,7 @@ public function testAddWithLeadingSlash(): void public function testMatchIgnoresInvalidHTTPMethods(): void { - Services::request()->setMethod(Method::GET); + service('request')->setMethod(Method::GET); $routes = $this->getCollector(); @@ -193,7 +192,7 @@ public function testMatchIgnoresInvalidHTTPMethods(): void public function testAddWorksWithArrayOFHTTPMethods(): void { - Services::request()->setMethod(Method::POST); + service('request')->setMethod(Method::POST); $routes = $this->getCollector(); @@ -714,7 +713,7 @@ public function testPresenterScaffoldsCorrectly(): void public function testResourcesWithCustomController(): void { - Services::request()->setMethod(Method::GET); + service('request')->setMethod(Method::GET); $routes = $this->getCollector(); $routes->resource('photos', ['controller' => '