@@ -343,7 +342,7 @@
setStatusCode(http_response_code());
?>
diff --git a/composer.json b/composer.json
index 2410b37e84e2..1704c70baa06 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.10"
},
"replace": {
"codeigniter4/framework": "self.version"
diff --git a/phpstan-baseline.php b/phpstan-baseline.php
index 0573b578a2bd..46bd91c2586d 100644
--- a/phpstan-baseline.php
+++ b/phpstan-baseline.php
@@ -7,54 +7,12 @@
'count' => 1,
'path' => __DIR__ . '/app/Config/Filters.php',
];
-$ignoreErrors[] = [
- // identifier: function.alreadyNarrowedType
- 'message' => '#^Call to function method_exists\\(\\) with \'Composer\\\\\\\\InstalledVersions\' and \'getAllRawData\' will always evaluate to true\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Autoloader/Autoloader.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.iterableValue
- 'message' => '#^Method CodeIgniter\\\\Autoloader\\\\Autoloader\\:\\:loadComposerNamespaces\\(\\) has parameter \\$composerPackages with no value type specified in iterable type array\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Autoloader/Autoloader.php',
-];
$ignoreErrors[] = [
// identifier: isset.property
'message' => '#^Property Config\\\\Autoload\\:\\:\\$helpers \\(array\\\\) in isset\\(\\) is not nullable\\.$#',
'count' => 1,
'path' => __DIR__ . '/system/Autoloader/Autoloader.php',
];
-$ignoreErrors[] = [
- // identifier: ternary.condNotBoolean
- 'message' => '#^Only booleans are allowed in a ternary operator condition, int\\|string given\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Autoloader/FileLocator.php',
-];
-$ignoreErrors[] = [
- // identifier: ternary.shortNotAllowed
- 'message' => '#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#',
- 'count' => 6,
- 'path' => __DIR__ . '/system/Autoloader/FileLocator.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.iterableValue
- 'message' => '#^Method CodeIgniter\\\\Autoloader\\\\FileLocatorCached\\:\\:search\\(\\) return type has no value type specified in iterable type array\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Autoloader/FileLocatorCached.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.iterableValue
- 'message' => '#^Property CodeIgniter\\\\Autoloader\\\\FileLocatorCached\\:\\:\\$cache type has no value type specified in iterable type array\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Autoloader/FileLocatorCached.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.iterableValue
- 'message' => '#^Method CodeIgniter\\\\Autoloader\\\\FileLocatorInterface\\:\\:search\\(\\) return type has no value type specified in iterable type array\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Autoloader/FileLocatorInterface.php',
-];
$ignoreErrors[] = [
// identifier: missingType.iterableValue
'message' => '#^Method CodeIgniter\\\\BaseModel\\:\\:__call\\(\\) has parameter \\$params with no value type specified in iterable type array\\.$#',
@@ -1009,12 +967,6 @@
'count' => 1,
'path' => __DIR__ . '/system/Common.php',
];
-$ignoreErrors[] = [
- // identifier: empty.notAllowed
- 'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
- 'count' => 4,
- 'path' => __DIR__ . '/system/Common.php',
-];
$ignoreErrors[] = [
// identifier: missingType.iterableValue
'message' => '#^Function cache\\(\\) return type has no value type specified in iterable type array\\.$#',
@@ -1285,18 +1237,6 @@
'count' => 1,
'path' => __DIR__ . '/system/Config/Factories.php',
];
-$ignoreErrors[] = [
- // identifier: booleanNot.exprNotBoolean
- 'message' => '#^Only booleans are allowed in a negated boolean, array given\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Config/Factories.php',
-];
-$ignoreErrors[] = [
- // identifier: booleanNot.exprNotBoolean
- 'message' => '#^Only booleans are allowed in a negated boolean, string\\|null given\\.$#',
- 'count' => 2,
- 'path' => __DIR__ . '/system/Config/Factories.php',
-];
$ignoreErrors[] = [
// identifier: missingType.iterableValue
'message' => '#^Property CodeIgniter\\\\Config\\\\Factory\\:\\:\\$default type has no value type specified in iterable type array\\.$#',
@@ -2500,7 +2440,7 @@
$ignoreErrors[] = [
// identifier: empty.notAllowed
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
- 'count' => 13,
+ 'count' => 12,
'path' => __DIR__ . '/system/Database/Forge.php',
];
$ignoreErrors[] = [
@@ -5863,12 +5803,6 @@
'count' => 2,
'path' => __DIR__ . '/system/HTTP/DownloadResponse.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.iterableValue
- 'message' => '#^Method CodeIgniter\\\\HTTP\\\\DownloadResponse\\:\\:setCache\\(\\) has parameter \\$options with no value type specified in iterable type array\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/HTTP/DownloadResponse.php',
-];
$ignoreErrors[] = [
// identifier: method.childReturnType
'message' => '#^Return type \\(CodeIgniter\\\\HTTP\\\\DownloadResponse\\) of method CodeIgniter\\\\HTTP\\\\DownloadResponse\\:\\:sendBody\\(\\) should be covariant with return type \\(\\$this\\(CodeIgniter\\\\HTTP\\\\Response\\)\\) of method CodeIgniter\\\\HTTP\\\\Response\\:\\:sendBody\\(\\)$#',
@@ -9115,12 +9049,6 @@
'count' => 1,
'path' => __DIR__ . '/system/Test/CIUnitTestCase.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.callable
- 'message' => '#^Method CodeIgniter\\\\Test\\\\CIUnitTestCase\\:\\:getPrivateMethodInvoker\\(\\) return type has no signature specified for Closure\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Test/CIUnitTestCase.php',
-];
$ignoreErrors[] = [
// identifier: missingType.return
'message' => '#^Method CodeIgniter\\\\Test\\\\CIUnitTestCase\\:\\:mockCache\\(\\) has no return type specified\\.$#',
@@ -9151,12 +9079,6 @@
'count' => 1,
'path' => __DIR__ . '/system/Test/CIUnitTestCase.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.return
- 'message' => '#^Method CodeIgniter\\\\Test\\\\CIUnitTestCase\\:\\:setPrivateProperty\\(\\) has no return type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/system/Test/CIUnitTestCase.php',
-];
$ignoreErrors[] = [
// identifier: booleanNot.exprNotBoolean
'message' => '#^Only booleans are allowed in a negated boolean, CodeIgniter\\\\CodeIgniter given\\.$#',
@@ -11689,36 +11611,6 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/AutoReview/FrameworkCodeTest.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.callable
- 'message' => '#^Method CodeIgniter\\\\Autoloader\\\\AutoloaderTest\\:\\:getPrivateMethodInvoker\\(\\) return type has no signature specified for Closure\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Autoloader/AutoloaderTest.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.return
- 'message' => '#^Method CodeIgniter\\\\Autoloader\\\\AutoloaderTest\\:\\:setPrivateProperty\\(\\) has no return type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Autoloader/AutoloaderTest.php',
-];
-$ignoreErrors[] = [
- // identifier: ternary.shortNotAllowed
- 'message' => '#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#',
- 'count' => 2,
- 'path' => __DIR__ . '/tests/system/Autoloader/AutoloaderTest.php',
-];
-$ignoreErrors[] = [
- // identifier: method.notFound
- 'message' => '#^Call to an undefined method CodeIgniter\\\\Autoloader\\\\FileLocatorInterface\\:\\:__destruct\\(\\)\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Autoloader/FileLocatorCachedTest.php',
-];
-$ignoreErrors[] = [
- // identifier: method.notFound
- 'message' => '#^Call to an undefined method CodeIgniter\\\\Autoloader\\\\FileLocatorInterface\\:\\:deleteCache\\(\\)\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Autoloader/FileLocatorCachedTest.php',
-];
$ignoreErrors[] = [
// identifier: codeigniter.superglobalAccessAssign
'message' => '#^Assigning 3 directly on offset \'argc\' of \\$_SERVER is discouraged\\.$#',
@@ -13009,24 +12901,12 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/Database/Builder/WhereTest.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.callable
- 'message' => '#^Method CodeIgniter\\\\Database\\\\ConfigTest\\:\\:getPrivateMethodInvoker\\(\\) return type has no signature specified for Closure\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Database/ConfigTest.php',
-];
$ignoreErrors[] = [
// identifier: missingType.iterableValue
'message' => '#^Method CodeIgniter\\\\Database\\\\ConfigTest\\:\\:provideConvertDSN\\(\\) return type has no value type specified in iterable type iterable\\.$#',
'count' => 1,
'path' => __DIR__ . '/tests/system/Database/ConfigTest.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.return
- 'message' => '#^Method CodeIgniter\\\\Database\\\\ConfigTest\\:\\:setPrivateProperty\\(\\) has no return type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Database/ConfigTest.php',
-];
$ignoreErrors[] = [
// identifier: missingType.iterableValue
'message' => '#^Property CodeIgniter\\\\Database\\\\ConfigTest\\:\\:\\$dsnGroup type has no value type specified in iterable type array\\.$#',
@@ -13375,18 +13255,6 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/Debug/ExceptionsTest.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.callable
- 'message' => '#^Method CodeIgniter\\\\Debug\\\\ExceptionsTest\\:\\:getPrivateMethodInvoker\\(\\) return type has no signature specified for Closure\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Debug/ExceptionsTest.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.return
- 'message' => '#^Method CodeIgniter\\\\Debug\\\\ExceptionsTest\\:\\:setPrivateProperty\\(\\) has no return type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Debug/ExceptionsTest.php',
-];
$ignoreErrors[] = [
// identifier: argument.type
'message' => '#^Parameter \\#2 \\$callable of method CodeIgniter\\\\Debug\\\\Timer\\:\\:record\\(\\) expects callable\\(\\)\\: mixed, \'strlen\' given\\.$#',
@@ -13525,12 +13393,6 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/Entity/EntityTest.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.callable
- 'message' => '#^Method CodeIgniter\\\\Entity\\\\EntityTest\\:\\:getPrivateMethodInvoker\\(\\) return type has no signature specified for Closure\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Entity/EntityTest.php',
-];
$ignoreErrors[] = [
// identifier: missingType.return
'message' => '#^Method CodeIgniter\\\\Entity\\\\EntityTest\\:\\:getSimpleSwappedEntity\\(\\) has no return type specified\\.$#',
@@ -13543,12 +13405,6 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/Entity/EntityTest.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.return
- 'message' => '#^Method CodeIgniter\\\\Entity\\\\EntityTest\\:\\:setPrivateProperty\\(\\) has no return type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Entity/EntityTest.php',
-];
$ignoreErrors[] = [
// identifier: codeigniter.configArgumentInstanceof
'message' => '#^Argument \\#1 \\$name \\(\'Modules\'\\) passed to function config does not extend CodeIgniter\\\\\\\\Config\\\\\\\\BaseConfig\\.$#',
@@ -15651,13 +15507,13 @@
];
$ignoreErrors[] = [
// identifier: argument.type
- 'message' => '#^Parameter \\#1 \\$row of method CodeIgniter\\\\BaseModel\\:\\:save\\(\\) expects array\\\\|object, array\\\\> given\\.$#',
+ 'message' => '#^Parameter \\#1 \\$row of method CodeIgniter\\\\BaseModel\\:\\:save\\(\\) expects array\\|object, array> given\\.$#',
'count' => 1,
'path' => __DIR__ . '/tests/system/Models/DataConverterModelTest.php',
];
$ignoreErrors[] = [
// identifier: argument.type
- 'message' => '#^Parameter \\#2 \\$row of method CodeIgniter\\\\Model\\:\\:update\\(\\) expects array\\\\|object\\|null, array\\\\> given\\.$#',
+ 'message' => '#^Parameter \\#2 \\$row of method CodeIgniter\\\\Model\\:\\:update\\(\\) expects array\\|object\\|null, array> given\\.$#',
'count' => 1,
'path' => __DIR__ . '/tests/system/Models/DataConverterModelTest.php',
];
@@ -15853,18 +15709,6 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/Models/InsertModelTest.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.callable
- 'message' => '#^Method CodeIgniter\\\\Models\\\\LiveModelTestCase\\:\\:getPrivateMethodInvoker\\(\\) return type has no signature specified for Closure\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Models/LiveModelTestCase.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.return
- 'message' => '#^Method CodeIgniter\\\\Models\\\\LiveModelTestCase\\:\\:setPrivateProperty\\(\\) has no return type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Models/LiveModelTestCase.php',
-];
$ignoreErrors[] = [
// identifier: property.nonObject
'message' => '#^Cannot access property \\$created_at on array\\.$#',
@@ -16059,7 +15903,7 @@
];
$ignoreErrors[] = [
// identifier: argument.type
- 'message' => '#^Parameter \\#1 \\$row of method CodeIgniter\\\\BaseModel\\:\\:save\\(\\) expects array\\\\|object, array\\\\|null given\\.$#',
+ 'message' => '#^Parameter \\#1 \\$row of method CodeIgniter\\\\BaseModel\\:\\:save\\(\\) expects array\\|object, array\\|null given\\.$#',
'count' => 1,
'path' => __DIR__ . '/tests/system/Models/UpdateModelTest.php',
];
@@ -16303,12 +16147,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\\.$#',
@@ -16921,18 +16759,6 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/Session/Handlers/Database/AbstractHandlerTestCase.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.callable
- 'message' => '#^Method CodeIgniter\\\\Session\\\\Handlers\\\\Database\\\\AbstractHandlerTestCase\\:\\:getPrivateMethodInvoker\\(\\) return type has no signature specified for Closure\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Session/Handlers/Database/AbstractHandlerTestCase.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.return
- 'message' => '#^Method CodeIgniter\\\\Session\\\\Handlers\\\\Database\\\\AbstractHandlerTestCase\\:\\:setPrivateProperty\\(\\) has no return type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/Session/Handlers/Database/AbstractHandlerTestCase.php',
-];
$ignoreErrors[] = [
// identifier: missingType.return
'message' => '#^Method CodeIgniter\\\\Session\\\\Handlers\\\\Database\\\\MySQLiHandlerTest\\:\\:getInstance\\(\\) has no return type specified\\.$#',
@@ -18181,18 +18007,6 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/Validation/ValidationTest.php',
];
-$ignoreErrors[] = [
- // identifier: assign.propertyType
- 'message' => '#^Property CodeIgniter\\\\View\\\\DecoratorsTest\\:\\:\\$loader \\(CodeIgniter\\\\Autoloader\\\\FileLocator\\) does not accept CodeIgniter\\\\Autoloader\\\\FileLocatorInterface\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/View/DecoratorsTest.php',
-];
-$ignoreErrors[] = [
- // identifier: assign.propertyType
- 'message' => '#^Property CodeIgniter\\\\View\\\\ParserFilterTest\\:\\:\\$loader \\(CodeIgniter\\\\Autoloader\\\\FileLocator\\) does not accept CodeIgniter\\\\Autoloader\\\\FileLocatorInterface\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/View/ParserFilterTest.php',
-];
$ignoreErrors[] = [
// identifier: missingType.return
'message' => '#^Method CodeIgniter\\\\View\\\\ParserPluginTest\\:\\:setHints\\(\\) has no return type specified\\.$#',
@@ -18217,36 +18031,12 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/View/ParserTest.php',
];
-$ignoreErrors[] = [
- // identifier: missingType.iterableValue
- 'message' => '#^Method class@anonymous/tests/system/View/ParserTest\\.php\\:340\\:\\:toArray\\(\\) return type has no value type specified in iterable type array\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/View/ParserTest.php',
-];
$ignoreErrors[] = [
// identifier: argument.type
'message' => '#^Parameter \\#2 \\$context of method CodeIgniter\\\\View\\\\Parser\\:\\:setData\\(\\) expects \'attr\'\\|\'css\'\\|\'html\'\\|\'js\'\\|\'raw\'\\|\'url\'\\|null, \'unknown\' given\\.$#',
'count' => 3,
'path' => __DIR__ . '/tests/system/View/ParserTest.php',
];
-$ignoreErrors[] = [
- // identifier: assign.propertyType
- 'message' => '#^Property CodeIgniter\\\\View\\\\ParserTest\\:\\:\\$loader \\(CodeIgniter\\\\Autoloader\\\\FileLocator\\) does not accept CodeIgniter\\\\Autoloader\\\\FileLocatorInterface\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/View/ParserTest.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.property
- 'message' => '#^Property class@anonymous/tests/system/View/ParserTest\\.php\\:340\\:\\:\\$bar has no type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/View/ParserTest.php',
-];
-$ignoreErrors[] = [
- // identifier: missingType.property
- 'message' => '#^Property class@anonymous/tests/system/View/ParserTest\\.php\\:340\\:\\:\\$foo has no type specified\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/View/ParserTest.php',
-];
$ignoreErrors[] = [
// identifier: method.notFound
'message' => '#^Call to an undefined method CodeIgniter\\\\View\\\\Table\\:\\:compileTemplate\\(\\)\\.$#',
@@ -18337,11 +18127,5 @@
'count' => 1,
'path' => __DIR__ . '/tests/system/View/TableTest.php',
];
-$ignoreErrors[] = [
- // identifier: assign.propertyType
- 'message' => '#^Property CodeIgniter\\\\View\\\\ViewTest\\:\\:\\$loader \\(CodeIgniter\\\\Autoloader\\\\FileLocator\\) does not accept CodeIgniter\\\\Autoloader\\\\FileLocatorInterface\\.$#',
- 'count' => 1,
- 'path' => __DIR__ . '/tests/system/View/ViewTest.php',
-];
return ['parameters' => ['ignoreErrors' => $ignoreErrors]];
diff --git a/rector.php b/rector.php
index 89647759b914..64abc9a73541 100644
--- a/rector.php
+++ b/rector.php
@@ -17,13 +17,9 @@
use Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector;
use Rector\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeysRector;
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\Identical\FlipTypeControlToUseExclusiveTypeRector;
use Rector\CodeQuality\Rector\If_\ShortenElseIfRector;
-use Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector;
use Rector\CodeQuality\Rector\Ternary\TernaryEmptyArrayArrayDimFetchToCoalesceRector;
use Rector\CodingStyle\Rector\ClassMethod\FuncGetArgsToVariadicParamRector;
use Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsParentRector;
@@ -187,11 +183,9 @@
CountArrayToEmptyArrayComparisonRector::class,
ChangeNestedForeachIfsToEarlyContinueRector::class,
ChangeIfElseValueAssignToEarlyReturnRector::class,
- CombineIfRector::class,
InlineIfToExplicitIfRector::class,
PreparedValueToEarlyReturnRector::class,
ShortenElseIfRector::class,
- SimplifyIfElseToTernaryRector::class,
UnusedForeachValueToArrayKeysRector::class,
ChangeArrayPushToArrayAssignRector::class,
RemoveErrorSuppressInTryCatchStmtsRector::class,
@@ -204,18 +198,16 @@
PrivatizeFinalClassPropertyRector::class,
CompleteDynamicPropertiesRector::class,
BooleanInIfConditionRuleFixerRector::class,
- SingleInArrayToCompareRector::class,
VersionCompareFuncCallToConstantRector::class,
- ExplicitBoolCompareRector::class,
AddClosureVoidReturnTypeWhereNoReturnRector::class,
AddFunctionVoidReturnTypeWhereNoReturnRector::class,
AddMethodCallBasedStrictParamTypeRector::class,
TypedPropertyFromAssignsRector::class,
ClosureReturnTypeRector::class,
- SimplifyBoolIdenticalTrueRector::class,
+ FlipTypeControlToUseExclusiveTypeRector::class,
])
->withConfiguredRule(StringClassNameToClassConstantRector::class, [
// keep '\\' prefix string on string '\Foo\Bar'
StringClassNameToClassConstantRector::SHOULD_KEEP_PRE_SLASH => true,
])
- ->withCodeQualityLevel(15);
+ ->withCodeQualityLevel(24);
diff --git a/system/Autoloader/Autoloader.php b/system/Autoloader/Autoloader.php
index d61818e20cdf..3c2a250f6600 100644
--- a/system/Autoloader/Autoloader.php
+++ b/system/Autoloader/Autoloader.php
@@ -21,7 +21,6 @@
use Config\Autoload;
use Config\Kint as KintConfig;
use Config\Modules;
-use Config\Services;
use Kint;
use Kint\Renderer\CliRenderer;
use Kint\Renderer\RichRenderer;
@@ -367,6 +366,9 @@ public function sanitizeFilename(string $filename): string
return $cleanFilename;
}
+ /**
+ * @param array{only?: list, exclude?: list} $composerPackages
+ */
private function loadComposerNamespaces(ClassLoader $composer, array $composerPackages): void
{
$namespacePaths = $composer->getPrefixesPsr4();
@@ -380,7 +382,7 @@ private function loadComposerNamespaces(ClassLoader $composer, array $composerPa
}
}
- if (! method_exists(InstalledVersions::class, 'getAllRawData')) {
+ if (! method_exists(InstalledVersions::class, 'getAllRawData')) { // @phpstan-ignore function.alreadyNarrowedType
throw new RuntimeException(
'Your Composer version is too old.'
. ' Please update Composer (run `composer self-update`) to v2.0.14 or later'
@@ -537,7 +539,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/Autoloader/FileLocator.php b/system/Autoloader/FileLocator.php
index 14b9a1366ab4..8e2564e00941 100644
--- a/system/Autoloader/FileLocator.php
+++ b/system/Autoloader/FileLocator.php
@@ -145,10 +145,11 @@ public function getClassname(string $file): string
if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $token[0] === T_STRING)) {
if (! $dlm) {
- $namespace = 0;
+ $namespace = '';
}
+
if (isset($token[1])) {
- $namespace = $namespace ? $namespace . '\\' . $token[1] : $token[1];
+ $namespace = $namespace !== '' ? $namespace . '\\' . $token[1] : $token[1];
$dlm = true;
}
} elseif ($dlm && ($token[0] !== T_NS_SEPARATOR) && ($token[0] !== T_STRING)) {
@@ -194,8 +195,9 @@ public function search(string $path, string $ext = 'php', bool $prioritizeApp =
foreach ($this->getNamespaces() as $namespace) {
if (isset($namespace['path']) && is_file($namespace['path'] . $path)) {
- $fullPath = $namespace['path'] . $path;
- $fullPath = realpath($fullPath) ?: $fullPath;
+ $fullPath = $namespace['path'] . $path;
+ $resolvedPath = realpath($fullPath);
+ $fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if ($prioritizeApp) {
$foundPaths[] = $fullPath;
@@ -272,14 +274,16 @@ protected function getNamespaces()
*/
public function findQualifiedNameFromPath(string $path)
{
- $path = realpath($path) ?: $path;
+ $resolvedPath = realpath($path);
+ $path = $resolvedPath !== false ? $resolvedPath : $path;
if (! is_file($path)) {
return false;
}
foreach ($this->getNamespaces() as $namespace) {
- $namespace['path'] = realpath($namespace['path']) ?: $namespace['path'];
+ $resolvedNamespacePath = realpath($namespace['path']);
+ $namespace['path'] = $resolvedNamespacePath !== false ? $resolvedNamespacePath : $namespace['path'];
if ($namespace['path'] === '') {
continue;
@@ -331,8 +335,9 @@ public function listFiles(string $path): array
helper('filesystem');
foreach ($this->getNamespaces() as $namespace) {
- $fullPath = $namespace['path'] . $path;
- $fullPath = realpath($fullPath) ?: $fullPath;
+ $fullPath = $namespace['path'] . $path;
+ $resolvedPath = realpath($fullPath);
+ $fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if (! is_dir($fullPath)) {
continue;
@@ -365,8 +370,9 @@ public function listNamespaceFiles(string $prefix, string $path): array
// autoloader->getNamespace($prefix) returns an array of paths for that namespace
foreach ($this->autoloader->getNamespace($prefix) as $namespacePath) {
- $fullPath = rtrim($namespacePath, '/') . '/' . $path;
- $fullPath = realpath($fullPath) ?: $fullPath;
+ $fullPath = rtrim($namespacePath, '/') . '/' . $path;
+ $resolvedPath = realpath($fullPath);
+ $fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if (! is_dir($fullPath)) {
continue;
@@ -392,8 +398,9 @@ public function listNamespaceFiles(string $prefix, string $path): array
*/
protected function legacyLocate(string $file, ?string $folder = null)
{
- $path = APPPATH . ($folder === null ? $file : $folder . '/' . $file);
- $path = realpath($path) ?: $path;
+ $path = APPPATH . ($folder === null ? $file : $folder . '/' . $file);
+ $resolvedPath = realpath($path);
+ $path = $resolvedPath !== false ? $resolvedPath : $path;
if (is_file($path)) {
return $path;
diff --git a/system/Autoloader/FileLocatorCached.php b/system/Autoloader/FileLocatorCached.php
index adf453308de3..8b17399444c6 100644
--- a/system/Autoloader/FileLocatorCached.php
+++ b/system/Autoloader/FileLocatorCached.php
@@ -36,6 +36,8 @@ final class FileLocatorCached implements FileLocatorInterface
* [
* 'search' => [$path => $foundPaths],
* ]
+ *
+ * @var array>
*/
private array $cache = [];
@@ -114,6 +116,9 @@ public function getClassname(string $file): string
return $classname;
}
+ /**
+ * @return list
+ */
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array
{
if (isset($this->cache['search'][$path][$ext][$prioritizeApp])) {
diff --git a/system/Autoloader/FileLocatorInterface.php b/system/Autoloader/FileLocatorInterface.php
index 3f7355a8f09d..3a1112dd480e 100644
--- a/system/Autoloader/FileLocatorInterface.php
+++ b/system/Autoloader/FileLocatorInterface.php
@@ -53,6 +53,8 @@ public function getClassname(string $file): string;
* 'app/Modules/foo/Config/Routes.php',
* 'app/Modules/bar/Config/Routes.php',
* ]
+ *
+ * @return list
*/
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array;
diff --git a/system/BaseModel.php b/system/BaseModel.php
index 5f4569962dd3..a00dec86f3d1 100644
--- a/system/BaseModel.php
+++ b/system/BaseModel.php
@@ -27,7 +27,6 @@
use CodeIgniter\Pager\Pager;
use CodeIgniter\Validation\ValidationInterface;
use Config\Feature;
-use Config\Services;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;
@@ -47,7 +46,7 @@
* - process various callbacks
* - allow intermingling calls to the db connection
*
- * @phpstan-type row_array array
+ * @phpstan-type row_array array
* @phpstan-type event_data_beforeinsert array{data: row_array}
* @phpstan-type event_data_afterinsert array{id: int|string, data: row_array, result: bool}
* @phpstan-type event_data_beforefind array{id?: int|string, method: string, singleton: bool, limit?: int, offset?: int}
@@ -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 dc3dc7f0b899..2b468e622816 100644
--- a/system/CLI/CLI.php
+++ b/system/CLI/CLI.php
@@ -15,7 +15,6 @@
use CodeIgniter\CLI\Exceptions\CLIException;
use CodeIgniter\Exceptions\InvalidArgumentException;
-use Config\Services;
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/CodeIgniter.php b/system/CodeIgniter.php
index d8406bc2b329..bb68c33f0760 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/Commands/Utilities/Routes/FilterCollector.php b/system/Commands/Utilities/Routes/FilterCollector.php
index dd1015838851..5a4e3d186940 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);
@@ -128,7 +127,7 @@ public function getClasses(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/Common.php b/system/Common.php
index c660a94c9c8a..20afcd3cfbf4 100644
--- a/system/Common.php
+++ b/system/Common.php
@@ -582,8 +582,8 @@ function helper($filenames): void
foreach ($filenames as $filename) {
// Store our system and application helper
// versions so that we can control the load ordering.
- $systemHelper = null;
- $appHelper = null;
+ $systemHelper = '';
+ $appHelper = '';
$localIncludes = [];
if (! str_contains($filename, '_helper')) {
@@ -600,7 +600,7 @@ function helper($filenames): void
if (str_contains($filename, '\\')) {
$path = $loader->locateFile($filename, 'Helpers');
- if (empty($path)) {
+ if ($path !== '') {
throw FileNotFoundException::forFileNotFound($filename);
}
@@ -622,7 +622,7 @@ function helper($filenames): void
}
// App-level helpers should override all others
- if (! empty($appHelper)) {
+ if ($appHelper !== '') {
$includes[] = $appHelper;
$loaded[] = $filename;
}
@@ -631,7 +631,7 @@ function helper($filenames): void
$includes = [...$includes, ...$localIncludes];
// And the system default one should be added in last.
- if (! empty($systemHelper)) {
+ if ($systemHelper !== '') {
$includes[] = $systemHelper;
$loaded[] = $filename;
}
@@ -871,7 +871,7 @@ function _solidus(?DocTypes $docTypesConfig = null): string
{
static $docTypes = null;
- if ($docTypesConfig !== null) {
+ if ($docTypesConfig instanceof DocTypes) {
$docTypes = $docTypesConfig;
}
@@ -1094,7 +1094,7 @@ function stringify_attributes($attributes, bool $js = false): string
{
$atts = '';
- if (empty($attributes)) {
+ if ($attributes === '' || $attributes === [] || $attributes === null) {
return $atts;
}
diff --git a/system/Config/Factories.php b/system/Config/Factories.php
index 2d93011a7455..6091ab42c5eb 100644
--- a/system/Config/Factories.php
+++ b/system/Config/Factories.php
@@ -162,7 +162,7 @@ public static function __callStatic(string $component, array $arguments)
}
// Try to locate the class
- if (! $class = self::locateClass($options, $alias)) {
+ if (($class = self::locateClass($options, $alias)) === null) {
return null;
}
@@ -213,7 +213,7 @@ private static function getDefinedInstance(array $options, string $alias, array
}
// Try to locate the class
- if (! $class = self::locateClass($options, $alias)) {
+ if (($class = self::locateClass($options, $alias)) === null) {
return null;
}
@@ -310,7 +310,7 @@ class_exists($alias, false)
}
// No namespace? Search for it
// Check all namespaces, prioritizing App and modules
- elseif (! $files = $locator->search($options['path'] . DIRECTORY_SEPARATOR . $alias)) {
+ elseif (($files = $locator->search($options['path'] . DIRECTORY_SEPARATOR . $alias)) === []) {
return null;
}
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/BaseConnection.php b/system/Database/BaseConnection.php
index 93b1f16e9e2f..5cac985631f1 100644
--- a/system/Database/BaseConnection.php
+++ b/system/Database/BaseConnection.php
@@ -688,7 +688,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/Forge.php b/system/Database/Forge.php
index c4fc224eb58a..dbb0491dc612 100644
--- a/system/Database/Forge.php
+++ b/system/Database/Forge.php
@@ -573,7 +573,7 @@ public function createTable(string $table, bool $ifNotExists = false, array $att
}
// Most databases don't support creating indexes from within the CREATE TABLE statement
- if (! empty($this->keys)) {
+ if ($this->keys !== []) {
for ($i = 0, $sqls = $this->_processIndexes($table), $c = count($sqls); $i < $c; $i++) {
$this->db->query($sqls[$i]);
}
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/MigrationRunner.php b/system/Database/MigrationRunner.php
index 58d94a7f8a08..46d8be709d3e 100644
--- a/system/Database/MigrationRunner.php
+++ b/system/Database/MigrationRunner.php
@@ -20,7 +20,6 @@
use CodeIgniter\I18n\Time;
use Config\Database;
use Config\Migrations as MigrationsConfig;
-use Config\Services;
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/Database/Seeder.php b/system/Database/Seeder.php
index ee6f6d1081b1..3530592fe671 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/Debug/Exceptions.php b/system/Debug/Exceptions.php
index 2c88bf695985..7688d29f01e3 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/DownloadException.php b/system/Exceptions/DownloadException.php
index d4b224fdee4d..c3bde8ed2556 100644
--- a/system/Exceptions/DownloadException.php
+++ b/system/Exceptions/DownloadException.php
@@ -45,6 +45,8 @@ public static function forNotFoundDownloadSource()
}
/**
+ * @deprecated Since v4.5.6
+ *
* @return static
*/
public static function forCannotSetCache()
diff --git a/system/Exceptions/PageNotFoundException.php b/system/Exceptions/PageNotFoundException.php
index ba9b98c49350..f84763ec25ff 100644
--- a/system/Exceptions/PageNotFoundException.php
+++ b/system/Exceptions/PageNotFoundException.php
@@ -13,8 +13,6 @@
namespace CodeIgniter\Exceptions;
-use Config\Services;
-
class PageNotFoundException extends RuntimeException implements HTTPExceptionInterface
{
use DebugTraceableTrait;
@@ -77,7 +75,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/DownloadResponse.php b/system/HTTP/DownloadResponse.php
index 56953823693d..a0da2e8ce4b9 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();
}
@@ -242,16 +242,6 @@ public function noCache(): self
return $this;
}
- /**
- * Disables cache configuration.
- *
- * @throws DownloadException
- */
- public function setCache(array $options = [])
- {
- throw DownloadException::forCannotSetCache();
- }
-
/**
* {@inheritDoc}
*
@@ -290,10 +280,8 @@ public function buildHeaders()
$this->setHeader('Content-Disposition', $this->getContentDisposition());
}
- $this->setHeader('Expires-Disposition', '0');
$this->setHeader('Content-Transfer-Encoding', 'binary');
$this->setHeader('Content-Length', (string) $this->getContentLength());
- $this->noCache();
}
/**
@@ -309,7 +297,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 0ee895fbb688..b9a4b4e125b0 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/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/RequestTrait.php b/system/HTTP/RequestTrait.php
index 43a4f23a0e87..51de3ea5c0fc 100644
--- a/system/HTTP/RequestTrait.php
+++ b/system/HTTP/RequestTrait.php
@@ -249,7 +249,7 @@ public function setGlobal(string $name, $value)
*
* @param string $name Supergrlobal name (lowercase)
* @phpstan-param 'get'|'post'|'request'|'cookie'|'server' $name
- * @param array|string|null $index
+ * @param array|int|string|null $index
* @param int|null $filter Filter constant
* @param array|int|null $flags Options
*
@@ -290,7 +290,7 @@ public function fetchGlobal(string $name, $index = null, ?int $filter = null, $f
}
// Does the index contain array notation?
- if (($count = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches)) > 1) {
+ if (is_string($index) && ($count = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches)) > 1) {
$value = $this->globals[$name];
for ($i = 0; $i < $count; $i++) {
diff --git a/system/HTTP/Response.php b/system/HTTP/Response.php
index 89ba119b11af..9de285b85d08 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/HTTP/SiteURI.php b/system/HTTP/SiteURI.php
index 9931b1cc10c4..55b2a97574af 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/HTTP/URI.php b/system/HTTP/URI.php
index e3062d30dd7c..03d4c2170504 100644
--- a/system/HTTP/URI.php
+++ b/system/HTTP/URI.php
@@ -1177,7 +1177,8 @@ protected function parseStr(string $query): array
parse_str($params, $result);
foreach ($result as $key => $value) {
- $return[hex2bin($key)] = $value;
+ // Array key might be int
+ $return[hex2bin((string) $key)] = $value;
}
return $return;
diff --git a/system/Log/Handlers/ChromeLoggerHandler.php b/system/Log/Handlers/ChromeLoggerHandler.php
index 8d39d4c06705..37c7c0ffeddf 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 === null) {
- $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 ece81113742e..eeffc8814bd0 100644
--- a/system/Router/RouteCollection.php
+++ b/system/Router/RouteCollection.php
@@ -22,7 +22,6 @@
use Config\App;
use Config\Modules;
use Config\Routing;
-use Config\Services;
/**
* @todo Implement nested resource routing (See CakePHP)
@@ -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 7417e7307a08..7abab0521fd7 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/ReflectionHelper.php b/system/Test/ReflectionHelper.php
index c72276d1a01a..adf22ac5a9ac 100644
--- a/system/Test/ReflectionHelper.php
+++ b/system/Test/ReflectionHelper.php
@@ -31,7 +31,8 @@ trait ReflectionHelper
* @param object|string $obj object or class name
* @param string $method method name
*
- * @return Closure
+ * @return Closure
+ * @phpstan-return Closure(mixed ...$args): mixed
*
* @throws ReflectionException
*/
@@ -73,7 +74,7 @@ private static function getAccessibleRefProperty($obj, $property)
*
* @throws ReflectionException
*/
- public static function setPrivateProperty($obj, $property, $value)
+ public static function setPrivateProperty($obj, $property, $value): void
{
$refProperty = self::getAccessibleRefProperty($obj, $property);
@@ -90,7 +91,7 @@ public static function setPrivateProperty($obj, $property, $value)
* @param object|string $obj object or class name
* @param string $property property name
*
- * @return mixed value
+ * @return mixed
*
* @throws ReflectionException
*/
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 71d96786c419..881052a21f3a 100644
--- a/system/Validation/Validation.php
+++ b/system/Validation/Validation.php
@@ -23,7 +23,6 @@
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\Validation\Exceptions\ValidationException;
use CodeIgniter\View\RendererInterface;
-use Config\Services;
use Config\Validation as ValidationConfig;
/**
@@ -795,7 +794,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;
@@ -918,26 +917,24 @@ protected function getErrorMessage(
): string {
$param ??= '';
+ $args = [
+ 'field' => ($label === null || $label === '') ? $field : lang($label),
+ 'param' => (! isset($this->rules[$param]['label'])) ? $param : lang($this->rules[$param]['label']),
+ 'value' => $value ?? '',
+ ];
+
// Check if custom message has been defined by user
if (isset($this->customErrors[$field][$rule])) {
- $message = lang($this->customErrors[$field][$rule]);
- } elseif (null !== $originalField && isset($this->customErrors[$originalField][$rule])) {
- $message = lang($this->customErrors[$originalField][$rule]);
- } else {
- // Try to grab a localized version of the message...
- // lang() will return the rule name back if not found,
- // so there will always be a string being returned.
- $message = lang('Validation.' . $rule);
+ return lang($this->customErrors[$field][$rule], $args);
+ }
+ if (null !== $originalField && isset($this->customErrors[$originalField][$rule])) {
+ return lang($this->customErrors[$originalField][$rule], $args);
}
- $message = str_replace('{field}', ($label === null || $label === '') ? $field : lang($label), $message);
- $message = str_replace(
- '{param}',
- (! isset($this->rules[$param]['label'])) ? $param : lang($this->rules[$param]['label']),
- $message
- );
-
- return str_replace('{value}', $value ?? '', $message);
+ // Try to grab a localized version of the message...
+ // lang() will return the rule name back if not found,
+ // so there will always be a string being returned.
+ return lang('Validation.' . $rule, $args);
}
/**
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/API/ResponseTraitTest.php b/tests/system/API/ResponseTraitTest.php
index 229475c7fae8..543677d1edd6 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/tests/system/Autoloader/AutoloaderTest.php b/tests/system/Autoloader/AutoloaderTest.php
index 1793a0cd20cb..328a7834e4fc 100644
--- a/tests/system/Autoloader/AutoloaderTest.php
+++ b/tests/system/Autoloader/AutoloaderTest.php
@@ -22,7 +22,6 @@
use CodeIgniter\Test\ReflectionHelper;
use Config\Autoload;
use Config\Modules;
-use Config\Services;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
@@ -112,17 +111,21 @@ 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);
$expected = APPPATH . 'Controllers' . DIRECTORY_SEPARATOR . 'Home.php';
- $this->assertSame($expected, realpath($actual) ?: $actual);
+
+ $resolvedPath = realpath($actual);
+ $actual = $resolvedPath !== false ? $resolvedPath : $actual;
+
+ $this->assertSame($expected, $actual);
}
public function testServiceAutoLoader(): void
{
- $autoloader = Services::autoloader(false);
+ $autoloader = service('autoloader', false);
$autoloader->initialize(new Autoload(), new Modules());
$autoloader->register();
@@ -131,7 +134,11 @@ public function testServiceAutoLoader(): void
// look for Home controller, as that should be in base repo
$actual = $classLoader(Home::class);
$expected = APPPATH . 'Controllers' . DIRECTORY_SEPARATOR . 'Home.php';
- $this->assertSame($expected, realpath($actual) ?: $actual);
+
+ $resolvedPath = realpath($actual);
+ $actual = $resolvedPath !== false ? $resolvedPath : $actual;
+
+ $this->assertSame($expected, $actual);
$autoloader->unregister();
}
diff --git a/tests/system/Autoloader/FileLocatorCachedTest.php b/tests/system/Autoloader/FileLocatorCachedTest.php
index 0aac85a8c59c..f8b5b386818c 100644
--- a/tests/system/Autoloader/FileLocatorCachedTest.php
+++ b/tests/system/Autoloader/FileLocatorCachedTest.php
@@ -25,7 +25,6 @@
final class FileLocatorCachedTest extends FileLocatorTest
{
private FileVarExportHandler $handler;
- protected FileLocatorInterface $locator;
public static function tearDownAfterClass(): void
{
diff --git a/tests/system/Autoloader/FileLocatorTest.php b/tests/system/Autoloader/FileLocatorTest.php
index e3a20286acc6..90580864fc47 100644
--- a/tests/system/Autoloader/FileLocatorTest.php
+++ b/tests/system/Autoloader/FileLocatorTest.php
@@ -27,6 +27,9 @@
#[Group('Others')]
class FileLocatorTest extends CIUnitTestCase
{
+ /**
+ * @var FileLocator|FileLocatorCached
+ */
protected FileLocatorInterface $locator;
protected function setUp(): void
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 991e31d1b75c..f9ac0f3e4bf4 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 5ae964fd8999..6c9eab7bbec9 100644
--- a/tests/system/CodeIgniterTest.php
+++ b/tests/system/CodeIgniterTest.php
@@ -46,7 +46,6 @@
final class CodeIgniterTest extends CIUnitTestCase
{
private CodeIgniter $codeigniter;
- protected $routes;
#[WithoutErrorHandler]
protected function setUp(): void
@@ -58,7 +57,7 @@ protected function setUp(): void
$this->codeigniter = new MockCodeIgniter(new App());
- $response = Services::response();
+ $response = service('response');
$response->pretend();
}
@@ -110,11 +109,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();
@@ -134,10 +133,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();
@@ -154,10 +153,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);
@@ -172,10 +171,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);
@@ -189,12 +188,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();
@@ -214,12 +213,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();
@@ -238,14 +237,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();
@@ -267,13 +266,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();
@@ -292,14 +291,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 +318,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 +337,7 @@ public function testRegisterSameFilterTwiceWithDifferentArgument(): void
'before' => ['pages/*'],
],
];
- Services::filters($filterConfig);
+ service('filters', $filterConfig);
ob_start();
$this->codeigniter->run();
@@ -358,13 +357,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();
@@ -382,7 +381,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);
}
@@ -393,7 +392,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();
@@ -482,12 +481,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();
@@ -506,12 +505,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();
@@ -535,11 +534,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();
@@ -562,10 +561,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();
@@ -587,10 +586,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();
@@ -610,12 +609,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);
@@ -630,7 +629,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();
@@ -652,10 +651,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();
@@ -674,13 +673,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();
@@ -717,7 +716,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();
@@ -739,7 +738,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');
@@ -749,7 +748,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
@@ -764,7 +763,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');
@@ -774,7 +773,7 @@ public function testSpoofRequestMethodCannotUseGET(): void
$this->codeigniter->run();
ob_get_clean();
- $this->assertSame('POST', Services::incomingrequest()->getMethod());
+ $this->assertSame('POST', service('incomingrequest')->getMethod());
}
/**
@@ -793,22 +792,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();
@@ -816,7 +815,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);
@@ -826,7 +825,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);
@@ -872,18 +871,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
@@ -956,14 +955,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 60b326dee35e..b7c6aaa6382f 100644
--- a/tests/system/Commands/RoutesTest.php
+++ b/tests/system/Commands/RoutesTest.php
@@ -47,7 +47,7 @@ protected function getBuffer()
private function getCleanRoutes(): RouteCollection
{
- $routes = Services::routes();
+ $routes = service('routes');
$routes->resetRoutes();
$routes->loadRoutes();
@@ -246,7 +246,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 a51c3db08634..dd402be42ab1 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 2c655169fead..f2c81684b623 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 8df7f3238fec..86ba03a8b25e 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 343f17e22f5a..a977eac7c88a 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/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/Config/ServicesTest.php b/tests/system/Config/ServicesTest.php
index 0f6e802c48af..b9ec264682f9 100644
--- a/tests/system/Config/ServicesTest.php
+++ b/tests/system/Config/ServicesTest.php
@@ -217,7 +217,7 @@ public function testNewThrottler(): void
public function testNewToolbar(): void
{
- $actual = Services::toolbar(null);
+ $actual = service('toolbar', null);
$this->assertInstanceOf(Toolbar::class, $actual);
}
@@ -409,7 +409,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 add07fc20dd4..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;
@@ -40,7 +39,6 @@
#[Group('Others')]
final class ControllerTest extends CIUnitTestCase
{
- private App $config;
private ?Controller $controller = null;
/**
@@ -59,10 +57,10 @@ 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);
- $this->logger = Services::logger();
+ $config = new App();
+ $this->request = new IncomingRequest($config, new SiteURI($config), null, new UserAgent());
+ $this->response = new Response($config);
+ $this->logger = service('logger');
}
public function testConstructor(): void
@@ -150,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
@@ -175,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
@@ -197,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')
);
}
@@ -226,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')
);
}
@@ -264,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/Live/ForgeTest.php b/tests/system/Database/Live/ForgeTest.php
index ef3a1f3726da..ddfa226276ee 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/GetFieldDataTestCase.php b/tests/system/Database/Live/OCI8/GetFieldDataTestCase.php
index a45c893dc3f9..2ff1f103fb33 100644
--- a/tests/system/Database/Live/OCI8/GetFieldDataTestCase.php
+++ b/tests/system/Database/Live/OCI8/GetFieldDataTestCase.php
@@ -58,7 +58,7 @@ public function testGetFieldDataDefault(): void
$fields = $this->db->getFieldData($this->table);
$idDefault = $this->getFieldMetaData('id', $this->table)->default;
- $this->assertMatchesRegularExpression('/"ORACLE"."ISEQ\$\$_[0-9]+".nextval/', $idDefault);
+ $this->assertMatchesRegularExpression('/"ORACLE"."ISEQ\$\$_\d+".nextval/', $idDefault);
$expected = [
(object) [
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/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/Database/RawSqlTest.php b/tests/system/Database/RawSqlTest.php
index 340e85c0ffba..fe26130cd0ee 100644
--- a/tests/system/Database/RawSqlTest.php
+++ b/tests/system/Database/RawSqlTest.php
@@ -49,6 +49,6 @@ public function testGetBindingKey(): void
$key = $rawSql->getBindingKey();
- $this->assertMatchesRegularExpression('/\ARawSql[0-9]+\z/', $key);
+ $this->assertMatchesRegularExpression('/\ARawSql\d+\z/', $key);
}
}
diff --git a/tests/system/Debug/ExceptionHandlerTest.php b/tests/system/Debug/ExceptionHandlerTest.php
index 0d6ba9499ec3..b75fe29a9d5c 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/Files/FileCollectionTest.php b/tests/system/Files/FileCollectionTest.php
index ddde8667eb3f..44a1acf54dab 100644
--- a/tests/system/Files/FileCollectionTest.php
+++ b/tests/system/Files/FileCollectionTest.php
@@ -647,6 +647,6 @@ public function testIterable(): void
$count++;
}
- $this->assertSame($count, 5);
+ $this->assertSame(5, $count);
}
}
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/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..0826a04afca8 100644
--- a/tests/system/Filters/DebugToolbarTest.php
+++ b/tests/system/Filters/DebugToolbarTest.php
@@ -13,9 +13,9 @@
namespace CodeIgniter\Filters;
-use CodeIgniter\Config\Services;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
+use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\Test\CIUnitTestCase;
use Config\Filters as FilterConfig;
@@ -32,7 +32,7 @@ final class DebugToolbarTest extends CIUnitTestCase
/**
* @var CLIRequest|IncomingRequest
*/
- private $request;
+ private RequestInterface $request;
private Response $response;
@@ -40,8 +40,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 f64f4b458c6e..14e045cd8cdc 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\Filters\Exceptions\FilterException;
use CodeIgniter\Filters\fixtures\GoogleCurious;
use CodeIgniter\Filters\fixtures\GoogleEmpty;
@@ -65,16 +64,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::incomingrequest();
+ $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..2d45b35a20b0 100644
--- a/tests/system/Filters/HoneypotTest.php
+++ b/tests/system/Filters/HoneypotTest.php
@@ -13,10 +13,10 @@
namespace CodeIgniter\Filters;
-use CodeIgniter\Config\Services;
use CodeIgniter\Honeypot\Exceptions\HoneypotException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
+use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\Test\CIUnitTestCase;
use Config\Honeypot;
@@ -37,9 +37,9 @@ final class HoneypotTest extends CIUnitTestCase
private Honeypot $honey;
/**
- * @var CLIRequest|IncomingRequest|null
+ * @var CLIRequest|IncomingRequest
*/
- private $request;
+ private RequestInterface $request;
private ?Response $response = null;
@@ -62,8 +62,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 +80,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 +101,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 +121,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/DownloadResponseTest.php b/tests/system/HTTP/DownloadResponseTest.php
index b62996f3d825..5897a1f58750 100644
--- a/tests/system/HTTP/DownloadResponseTest.php
+++ b/tests/system/HTTP/DownloadResponseTest.php
@@ -148,12 +148,25 @@ public function testNoCache(): void
$this->assertSame('private, no-transform, no-store, must-revalidate', $response->getHeaderLine('Cache-control'));
}
- public function testCantSetCache(): void
+ public function testSetCache(): void
{
$response = new DownloadResponse('unit-test.txt', true);
- $this->expectException(DownloadException::class);
- $response->setCache();
+ $date = date('r');
+
+ $options = [
+ 'etag' => '12345678',
+ 'last-modified' => $date,
+ 'max-age' => 300,
+ 'must-revalidate',
+ ];
+
+ $response->setCache($options);
+ $response->buildHeaders();
+
+ $this->assertSame('12345678', $response->getHeaderLine('ETag'));
+ $this->assertSame($date, $response->getHeaderLine('Last-Modified'));
+ $this->assertSame('max-age=300, must-revalidate', $response->getHeaderLine('Cache-Control'));
}
public function testWhenFilepathIsSetBinaryCanNotBeSet(): void
@@ -200,30 +213,53 @@ public function testCanGetContentLength(): void
$this->assertSame($size, $response->getContentLength());
}
- public function testIsSetDownloadableHeadlersFromBinary(): void
+ public function testIsSetDownloadableHeadersFromBinary(): void
{
$response = new DownloadResponse('unit test.txt', false);
$response->setBinary('test');
$response->buildHeaders();
+ $this->assertSame('private, no-transform, no-store, must-revalidate', $response->getHeaderLine('Cache-Control'));
$this->assertSame('application/octet-stream', $response->getHeaderLine('Content-Type'));
$this->assertSame('attachment; filename="unit test.txt"; filename*=UTF-8\'\'unit%20test.txt', $response->getHeaderLine('Content-Disposition'));
- $this->assertSame('0', $response->getHeaderLine('Expires-Disposition'));
$this->assertSame('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
$this->assertSame('4', $response->getHeaderLine('Content-Length'));
}
- public function testIsSetDownloadableHeadlersFromFile(): void
+ public function testIsSetDownloadableHeadersFromFile(): void
+ {
+ $response = new DownloadResponse('unit-test.php', false);
+
+ $response->setFilePath(__FILE__);
+ $response->buildHeaders();
+
+ $this->assertSame('private, no-transform, no-store, must-revalidate', $response->getHeaderLine('Cache-Control'));
+ $this->assertSame('application/octet-stream', $response->getHeaderLine('Content-Type'));
+ $this->assertSame('attachment; filename="unit-test.php"; filename*=UTF-8\'\'unit-test.php', $response->getHeaderLine('Content-Disposition'));
+ $this->assertSame('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
+ $this->assertSame(filesize(__FILE__), (int) $response->getHeaderLine('Content-Length'));
+ }
+
+ public function testCustomHeaders(): void
{
$response = new DownloadResponse('unit-test.php', false);
$response->setFilePath(__FILE__);
+
+ $response->setHeader('Last-Modified', 'Fri, 18 Oct 2024 13:17:37 GMT');
+ $response->setHeader('Expires', 'Sun, 17 Nov 2024 14:17:37 GMT');
+ $response->setHeader('Pragma', 'public');
+ $response->removeHeader('Cache-Control');
+ $response->setHeader('Cache-Control', 'public');
$response->buildHeaders();
+ $this->assertSame('Fri, 18 Oct 2024 13:17:37 GMT', $response->getHeaderLine('Last-Modified'));
+ $this->assertSame('Sun, 17 Nov 2024 14:17:37 GMT', $response->getHeaderLine('Expires'));
+ $this->assertSame('public', $response->getHeaderLine('Pragma'));
+ $this->assertSame('public', $response->getHeaderLine('Cache-Control'));
$this->assertSame('application/octet-stream', $response->getHeaderLine('Content-Type'));
$this->assertSame('attachment; filename="unit-test.php"; filename*=UTF-8\'\'unit-test.php', $response->getHeaderLine('Content-Disposition'));
- $this->assertSame('0', $response->getHeaderLine('Expires-Disposition'));
$this->assertSame('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
$this->assertSame(filesize(__FILE__), (int) $response->getHeaderLine('Content-Length'));
}
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/HTTP/RedirectExceptionTest.php b/tests/system/HTTP/RedirectExceptionTest.php
index b1f325199cc6..847ad2173563 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/RequestTest.php b/tests/system/HTTP/RequestTest.php
index e2073268d794..6659c6966861 100644
--- a/tests/system/HTTP/RequestTest.php
+++ b/tests/system/HTTP/RequestTest.php
@@ -196,6 +196,21 @@ public function testFetchGlobalReturnsArrayValues(): void
$this->assertCount(2, $result['ANNOUNCEMENTS']);
}
+ public function testFetchGlobalReturnsWithListValues(): void
+ {
+ $post = [
+ 0 => ['foo' => 0],
+ 1 => ['bar' => 1],
+ 2 => ['baz' => 2],
+ ];
+
+ $this->request->setGlobal('post', $post);
+ $result = $this->request->fetchGlobal('post');
+
+ $this->assertIsList($result);
+ $this->assertSame($post, $result);
+ }
+
public function testFetchGlobalWithArrayTop(): void
{
$post = [
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/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 619a21717f86..c6bfba193054 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;
@@ -50,9 +49,9 @@ protected function setUp(): void
$this->expire = 9999;
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);
+ $this->response = service('response');
+ $request = new IncomingRequest(new App(), new SiteURI(new App()), null, new UserAgent());
+ Services::injectMock('request', $request);
helper('cookie');
}
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/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/TextHelperTest.php b/tests/system/Helpers/TextHelperTest.php
index e2b0d60ca5ff..ff0ecacf8746 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/Helpers/URLHelper/MiscUrlTest.php b/tests/system/Helpers/URLHelper/MiscUrlTest.php
index 560729f55c95..1efe206dbc79 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..3878a5d957ff 100644
--- a/tests/system/Honeypot/HoneypotTest.php
+++ b/tests/system/Honeypot/HoneypotTest.php
@@ -14,11 +14,11 @@
namespace CodeIgniter\Honeypot;
use CodeIgniter\Config\Factories;
-use CodeIgniter\Config\Services;
use CodeIgniter\Filters\Filters;
use CodeIgniter\Honeypot\Exceptions\HoneypotException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
+use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\Test\CIUnitTestCase;
use Config\App;
@@ -39,7 +39,7 @@ final class HoneypotTest extends CIUnitTestCase
/**
* @var CLIRequest|IncomingRequest
*/
- private $request;
+ private RequestInterface $request;
private Response $response;
@@ -54,8 +54,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 +99,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 +118,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 +132,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/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/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/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/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..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);
@@ -398,8 +397,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 +437,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 +470,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..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
@@ -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
@@ -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/Publisher/PublisherOutputTest.php b/tests/system/Publisher/PublisherOutputTest.php
index e03335e86fe6..0b9b744e01fd 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,10 @@ protected function setUp(): void
{
parent::setUp();
- $this->structure = [
+ /**
+ * Files to seed to VFS
+ */
+ $structure = [
'able' => [
'apple.php' => 'Once upon a midnight dreary',
'bazam' => 'While I pondered weak and weary',
@@ -74,7 +72,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/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 7996e3300dc7..e60a563c4134 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 1a5c72a0b68e..cde22e98b3b0 100644
--- a/tests/system/Router/RouteCollectionTest.php
+++ b/tests/system/Router/RouteCollectionTest.php
@@ -15,7 +15,6 @@
use App\Controllers\Home;
use App\Controllers\Product;
-use CodeIgniter\Config\Services;
use CodeIgniter\controller;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\Method;
@@ -49,9 +48,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();
@@ -150,7 +149,7 @@ public function testAddIgnoresDefaultNamespaceWhenExists(): void
public function testAddWorksWithCurrentHTTPMethods(): void
{
- Services::request()->setMethod(Method::GET);
+ service('request')->setMethod(Method::GET);
$routes = $this->getCollector();
@@ -182,7 +181,7 @@ public function testAddWithLeadingSlash(): void
public function testMatchIgnoresInvalidHTTPMethods(): void
{
- Services::request()->setMethod(Method::GET);
+ service('request')->setMethod(Method::GET);
$routes = $this->getCollector();
@@ -195,7 +194,7 @@ public function testMatchIgnoresInvalidHTTPMethods(): void
public function testAddWorksWithArrayOFHTTPMethods(): void
{
- Services::request()->setMethod(Method::POST);
+ service('request')->setMethod(Method::POST);
$routes = $this->getCollector();
@@ -716,7 +715,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' => '