diff --git a/system/API/ResponseTrait.php b/system/API/ResponseTrait.php index 57a9077f7f40..01ce42860b32 100644 --- a/system/API/ResponseTrait.php +++ b/system/API/ResponseTrait.php @@ -16,7 +16,6 @@ use CodeIgniter\Format\FormatterInterface; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\ResponseInterface; -use Config\Services; /** * Provides common, more readable, methods to provide @@ -307,7 +306,7 @@ protected function failServerError(string $description = 'Internal Server Error' */ protected function format($data = null) { - $format = Services::format(); + $format = service('format'); $mime = ($this->format === null) ? $format->getConfig()->supportedResponseFormats[0] : "application/{$this->format}"; diff --git a/system/BaseModel.php b/system/BaseModel.php index d5c125524744..cfe6dad9aac5 100644 --- a/system/BaseModel.php +++ b/system/BaseModel.php @@ -1266,7 +1266,7 @@ public function errors(bool $forceDB = false) public function paginate(?int $perPage = null, string $group = 'default', ?int $page = null, int $segment = 0) { // Since multiple models may use the Pager, the Pager must be shared. - $pager = Services::pager(); + $pager = service('pager'); if ($segment !== 0) { $pager->setSegment($segment, $group); diff --git a/system/CLI/GeneratorTrait.php b/system/CLI/GeneratorTrait.php index 3a5347df868c..47701e0f7b28 100644 --- a/system/CLI/GeneratorTrait.php +++ b/system/CLI/GeneratorTrait.php @@ -14,7 +14,6 @@ namespace CodeIgniter\CLI; use Config\Generators; -use Config\Services; use Throwable; /** @@ -417,7 +416,7 @@ protected function buildPath(string $class): string $namespace = $this->getNamespace(); // Check if the namespace is actually defined and we are not just typing gibberish. - $base = Services::autoloader()->getNamespace($namespace); + $base = service('autoloader')->getNamespace($namespace); if (! $base = reset($base)) { CLI::error( diff --git a/system/CodeIgniter.php b/system/CodeIgniter.php index 8322d4ee34eb..f126878689b9 100644 --- a/system/CodeIgniter.php +++ b/system/CodeIgniter.php @@ -462,7 +462,7 @@ protected function handleRequest(?RouteCollectionInterface $routes, Cache $cache $uri = $this->request->getPath(); if ($this->enableFilters) { - $filters = Services::filters(); + $filters = service('filters'); // If any filters were specified within the routes file, // we need to ensure it's active for the current request @@ -518,7 +518,7 @@ protected function handleRequest(?RouteCollectionInterface $routes, Cache $cache $this->gatherOutput($cacheConfig, $returned); if ($this->enableFilters) { - $filters = Services::filters(); + $filters = service('filters'); $filters->setResponse($this->response); // Run "after" filters @@ -649,7 +649,7 @@ protected function getRequestObject() Services::createRequest($this->config); } - $this->request = Services::request(); + $this->request = service('request'); $this->spoofRequestMethod(); } @@ -817,7 +817,7 @@ protected function tryToRouteIt(?RouteCollectionInterface $routes = null) $this->benchmark->start('routing'); if ($routes === null) { - $routes = Services::routes()->loadRoutes(); + $routes = service('routes')->loadRoutes(); } // $routes is defined in Config/Routes.php diff --git a/system/Commands/Database/Migrate.php b/system/Commands/Database/Migrate.php index 50b3c8f9e0e4..b422e4a6db73 100644 --- a/system/Commands/Database/Migrate.php +++ b/system/Commands/Database/Migrate.php @@ -15,7 +15,6 @@ use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; -use Config\Services; use Throwable; /** @@ -68,7 +67,7 @@ class Migrate extends BaseCommand */ public function run(array $params) { - $runner = Services::migrations(); + $runner = service('migrations'); $runner->clearCliMessages(); CLI::write(lang('Migrations.latest'), 'yellow'); diff --git a/system/Commands/Database/MigrateRollback.php b/system/Commands/Database/MigrateRollback.php index 200dc303db2d..f206d7fc5162 100644 --- a/system/Commands/Database/MigrateRollback.php +++ b/system/Commands/Database/MigrateRollback.php @@ -15,7 +15,6 @@ use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; -use Config\Services; use Throwable; /** @@ -79,7 +78,7 @@ public function run(array $params) // @codeCoverageIgnoreEnd } - $runner = Services::migrations(); + $runner = service('migrations'); try { $batch = $params['b'] ?? CLI::getOption('b') ?? $runner->getLastBatch() - 1; diff --git a/system/Commands/Database/MigrateStatus.php b/system/Commands/Database/MigrateStatus.php index 98bda998bcc2..b4021a1bbb8f 100644 --- a/system/Commands/Database/MigrateStatus.php +++ b/system/Commands/Database/MigrateStatus.php @@ -15,7 +15,6 @@ use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; -use Config\Services; /** * Displays a list of all migrations and whether they've been run or not. @@ -83,11 +82,11 @@ class MigrateStatus extends BaseCommand */ public function run(array $params) { - $runner = Services::migrations(); + $runner = service('migrations'); $paramGroup = $params['g'] ?? CLI::getOption('g'); // Get all namespaces - $namespaces = Services::autoloader()->getNamespace(); + $namespaces = service('autoloader')->getNamespace(); // Collection of migration status $status = []; diff --git a/system/Commands/Generators/TestGenerator.php b/system/Commands/Generators/TestGenerator.php index 900f042a3f54..35019c72b826 100644 --- a/system/Commands/Generators/TestGenerator.php +++ b/system/Commands/Generators/TestGenerator.php @@ -16,7 +16,6 @@ use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\CLI\GeneratorTrait; -use Config\Services; /** * Generates a skeleton command file. @@ -82,7 +81,7 @@ public function run(array $params) $this->classNameLang = 'CLI.generator.className.test'; - $autoload = Services::autoloader(); + $autoload = service('autoloader'); $autoload->addNamespace('CodeIgniter', TESTPATH . 'system'); $autoload->addNamespace('Tests', ROOTPATH . 'tests'); @@ -112,7 +111,7 @@ protected function getNamespace(): string $class = $this->normalizeInputClassName(); $classPaths = explode('\\', $class); - $namespaces = Services::autoloader()->getNamespace(); + $namespaces = service('autoloader')->getNamespace(); while ($classPaths !== []) { array_pop($classPaths); @@ -176,7 +175,7 @@ protected function buildPath(string $class): string */ private function searchTestFilePath(string $namespace): ?string { - $bases = Services::autoloader()->getNamespace($namespace); + $bases = service('autoloader')->getNamespace($namespace); $base = null; diff --git a/system/Commands/Utilities/FilterCheck.php b/system/Commands/Utilities/FilterCheck.php index 7bcf0de42abd..56fcdb00b971 100644 --- a/system/Commands/Utilities/FilterCheck.php +++ b/system/Commands/Utilities/FilterCheck.php @@ -16,7 +16,6 @@ use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Commands\Utilities\Routes\FilterCollector; -use Config\Services; /** * Check filters for a route. @@ -88,7 +87,7 @@ public function run(array $params) $route = $params[1]; // Load Routes - Services::routes()->loadRoutes(); + service('routes')->loadRoutes(); $filterCollector = new FilterCollector(); diff --git a/system/Commands/Utilities/Namespaces.php b/system/Commands/Utilities/Namespaces.php index f3f047613eb9..c16f692cfb37 100644 --- a/system/Commands/Utilities/Namespaces.php +++ b/system/Commands/Utilities/Namespaces.php @@ -16,7 +16,6 @@ use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use Config\Autoload; -use Config\Services; /** * Lists namespaces set in Config\Autoload with their @@ -96,7 +95,7 @@ private function outputAllNamespaces(array $params): array { $maxLength = $params['m']; - $autoloader = Services::autoloader(); + $autoloader = service('autoloader'); $tbody = []; diff --git a/system/Commands/Utilities/Routes.php b/system/Commands/Utilities/Routes.php index 952961c8fbbb..f9575c063973 100644 --- a/system/Commands/Utilities/Routes.php +++ b/system/Commands/Utilities/Routes.php @@ -23,7 +23,6 @@ use CodeIgniter\Router\Router; use Config\Feature; use Config\Routing; -use Config\Services; /** * Lists all the routes. This will include any Routes files @@ -88,13 +87,13 @@ public function run(array $params) // Set HTTP_HOST if ($host) { - $request = Services::request(); + $request = service('request'); $_SERVER = $request->getServer(); $_SERVER['HTTP_HOST'] = $host; $request->setGlobal('server', $_SERVER); } - $collection = Services::routes()->loadRoutes(); + $collection = service('routes')->loadRoutes(); // Reset HTTP_HOST if ($host) { diff --git a/system/Commands/Utilities/Routes/ControllerFinder.php b/system/Commands/Utilities/Routes/ControllerFinder.php index 0b47ffbaad33..0dbd09ea5890 100644 --- a/system/Commands/Utilities/Routes/ControllerFinder.php +++ b/system/Commands/Utilities/Routes/ControllerFinder.php @@ -14,7 +14,6 @@ namespace CodeIgniter\Commands\Utilities\Routes; use CodeIgniter\Autoloader\FileLocatorInterface; -use CodeIgniter\Config\Services; /** * Finds all controllers in a namespace for auto route listing. @@ -36,7 +35,7 @@ final class ControllerFinder public function __construct(string $namespace) { $this->namespace = $namespace; - $this->locator = Services::locator(); + $this->locator = service('locator'); } /** diff --git a/system/Commands/Utilities/Routes/FilterCollector.php b/system/Commands/Utilities/Routes/FilterCollector.php index 9fe269661d78..e51e4595df61 100644 --- a/system/Commands/Utilities/Routes/FilterCollector.php +++ b/system/Commands/Utilities/Routes/FilterCollector.php @@ -101,7 +101,7 @@ public function getRequiredFilters(): array private function createRouter(Request $request): Router { - $routes = Services::routes(); + $routes = service('routes'); if ($this->resetRoutes) { $routes->resetRoutes(); @@ -114,6 +114,6 @@ private function createFilters(Request $request): Filters { $config = config(FiltersConfig::class); - return new Filters($config, $request, Services::response()); + return new Filters($config, $request, service('response')); } } diff --git a/system/Commands/Utilities/Routes/FilterFinder.php b/system/Commands/Utilities/Routes/FilterFinder.php index d2c210c4457e..f3c53b896568 100644 --- a/system/Commands/Utilities/Routes/FilterFinder.php +++ b/system/Commands/Utilities/Routes/FilterFinder.php @@ -18,7 +18,6 @@ use CodeIgniter\HTTP\Exceptions\RedirectException; use CodeIgniter\Router\Router; use Config\Feature; -use Config\Services; /** * Finds filters. @@ -32,8 +31,8 @@ final class FilterFinder public function __construct(?Router $router = null, ?Filters $filters = null) { - $this->router = $router ?? Services::router(); - $this->filters = $filters ?? Services::filters(); + $this->router = $router ?? service('router'); + $this->filters = $filters ?? service('filters'); } private function getRouteFilters(string $uri): array diff --git a/system/Commands/Utilities/Routes/SampleURIGenerator.php b/system/Commands/Utilities/Routes/SampleURIGenerator.php index 5ed0075c770c..3b71e2b1752d 100644 --- a/system/Commands/Utilities/Routes/SampleURIGenerator.php +++ b/system/Commands/Utilities/Routes/SampleURIGenerator.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Commands\Utilities\Routes; -use CodeIgniter\Config\Services; use CodeIgniter\Router\RouteCollection; use Config\App; @@ -42,7 +41,7 @@ final class SampleURIGenerator public function __construct(?RouteCollection $routes = null) { - $this->routes = $routes ?? Services::routes(); + $this->routes = $routes ?? service('routes'); } /** diff --git a/system/Common.php b/system/Common.php index 086c4db48b01..039942e3d80a 100644 --- a/system/Common.php +++ b/system/Common.php @@ -71,7 +71,7 @@ function app_timezone(): string */ function cache(?string $key = null) { - $cache = Services::cache(); + $cache = service('cache'); // No params - return cache object if ($key === null) { @@ -244,7 +244,7 @@ function cookie(string $name, string $value = '', array $options = []): Cookie function cookies(array $cookies = [], bool $getGlobal = true): CookieStore { if ($getGlobal) { - return Services::response()->getCookieStore(); + return service('response')->getCookieStore(); } return new CookieStore($cookies); @@ -259,7 +259,7 @@ function cookies(array $cookies = [], bool $getGlobal = true): CookieStore */ function csrf_token(): string { - return Services::security()->getTokenName(); + return service('security')->getTokenName(); } } @@ -271,7 +271,7 @@ function csrf_token(): string */ function csrf_header(): string { - return Services::security()->getHeaderName(); + return service('security')->getHeaderName(); } } @@ -283,7 +283,7 @@ function csrf_header(): string */ function csrf_hash(): string { - return Services::security()->getHash(); + return service('security')->getHash(); } } @@ -317,7 +317,7 @@ function csrf_meta(?string $id = null): string */ function csp_style_nonce(): string { - $csp = Services::csp(); + $csp = service('csp'); if (! $csp->enabled()) { return ''; @@ -333,7 +333,7 @@ function csp_style_nonce(): string */ function csp_script_nonce(): string { - $csp = Services::csp(); + $csp = service('csp'); if (! $csp->enabled()) { return ''; @@ -486,13 +486,13 @@ function force_https( ?RequestInterface $request = null, ?ResponseInterface $response = null ): void { - $request ??= Services::request(); + $request ??= service('request'); if (! $request instanceof IncomingRequest) { return; } - $response ??= Services::response(); + $response ??= service('response'); if ((ENVIRONMENT !== 'testing' && (is_cli() || $request->isSecure())) || $request->getServer('HTTPS') === 'test' @@ -503,7 +503,7 @@ function force_https( // If the session status is active, we should regenerate // the session ID for safety sake. if (ENVIRONMENT !== 'testing' && session_status() === PHP_SESSION_ACTIVE) { - Services::session()->regenerate(); // @codeCoverageIgnore + service('session')->regenerate(); // @codeCoverageIgnore } $uri = $request->getUri()->withScheme('https'); @@ -747,7 +747,7 @@ function is_windows(?bool $mock = null): bool */ function lang(string $line, array $args = [], ?string $locale = null) { - $language = Services::language(); + $language = service('language'); // Get active locale $activeLocale = $language->getLocale(); @@ -836,7 +836,7 @@ function old(string $key, $default = null, $escape = 'html') session(); // @codeCoverageIgnore } - $request = Services::request(); + $request = service('request'); $value = $request->getOldInput($key); @@ -934,7 +934,7 @@ function remove_invisible_characters(string $str, bool $urlEncoded = true): stri */ function request() { - return Services::request(); + return service('request'); } } @@ -944,7 +944,7 @@ function request() */ function response(): ResponseInterface { - return Services::response(); + return service('response'); } } @@ -965,7 +965,7 @@ function response(): ResponseInterface */ function route_to(string $method, ...$params) { - return Services::routes()->reverseRoute($method, ...$params); + return service('routes')->reverseRoute($method, ...$params); } } @@ -983,7 +983,7 @@ function route_to(string $method, ...$params) */ function session(?string $val = null) { - $session = Services::session(); + $session = service('session'); // Returning a single item? if (is_string($val)) { @@ -1009,6 +1009,10 @@ function session(?string $val = null) */ function service(string $name, ...$params): ?object { + if ($params === []) { + return Services::get($name); + } + return Services::$name(...$params); } } @@ -1137,7 +1141,7 @@ function stringify_attributes($attributes, bool $js = false): string */ function timer(?string $name = null, ?callable $callable = null) { - $timer = Services::timer(); + $timer = service('timer'); if ($name === null) { return $timer; @@ -1194,7 +1198,7 @@ function view(string $name, array $data = [], array $options = []): string */ function view_cell(string $library, $params = null, int $ttl = 0, ?string $cacheName = null): string { - return Services::viewcell() + return service('viewcell') ->render($library, $params, $ttl, $cacheName); } } diff --git a/system/Config/BaseConfig.php b/system/Config/BaseConfig.php index 6789c0e9c76b..51aac022b271 100644 --- a/system/Config/BaseConfig.php +++ b/system/Config/BaseConfig.php @@ -13,7 +13,6 @@ use Config\Encryption; use Config\Modules; -use Config\Services; use ReflectionClass; use ReflectionException; use RuntimeException; @@ -231,7 +230,7 @@ protected function registerProperties() } if (! static::$didDiscovery) { - $locator = Services::locator(); + $locator = service('locator'); $registrarsFiles = $locator->search('Config/Registrar.php'); foreach ($registrarsFiles as $file) { diff --git a/system/Config/BaseService.php b/system/Config/BaseService.php index 588f66534949..bc07a08d08ac 100644 --- a/system/Config/BaseService.php +++ b/system/Config/BaseService.php @@ -76,6 +76,7 @@ use Config\Toolbar as ConfigToolbar; use Config\Validation as ConfigValidation; use Config\View as ConfigView; +use InvalidArgumentException; /** * Services Configuration file. @@ -145,14 +146,21 @@ class BaseService * have been requested as a "shared" instance. * Keys should be lowercase service names. * - * @var array + * @var array [key => instance] */ protected static $instances = []; + /** + * Factory method list. + * + * @var array [key => callable] + */ + protected static array $factories = []; + /** * Mock objects for testing which are returned if exist. * - * @var array + * @var array [key => instance] */ protected static $mocks = []; @@ -177,6 +185,42 @@ class BaseService */ private static array $serviceNames = []; + /** + * Simple method to get an entry fast. + * + * @param string $key Identifier of the entry to look for. + * + * @return object|null Entry. + */ + public static function get(string $key): ?object + { + return static::$instances[$key] ?? static::__callStatic($key, []); + } + + /** + * Sets an entry. + * + * @param string $key Identifier of the entry. + */ + public static function set(string $key, object $value): void + { + if (isset(static::$instances[$key])) { + throw new InvalidArgumentException('The entry for "' . $key . '" is already set.'); + } + + static::$instances[$key] = $value; + } + + /** + * Overrides an existing entry. + * + * @param string $key Identifier of the entry. + */ + public static function override(string $key, object $value): void + { + static::$instances[$key] = $value; + } + /** * Returns a shared instance of any of the class' services. * @@ -252,6 +296,10 @@ public static function locator(bool $getShared = true) */ public static function __callStatic(string $name, array $arguments) { + if (isset(static::$factories[$name])) { + return static::$factories[$name](...$arguments); + } + $service = static::serviceExists($name); if ($service === null) { @@ -268,11 +316,14 @@ public static function __callStatic(string $name, array $arguments) public static function serviceExists(string $name): ?string { static::buildServicesCache(); + $services = array_merge(self::$serviceNames, [Services::class]); $name = strtolower($name); foreach ($services as $service) { if (method_exists($service, $name)) { + static::$factories[$name] = [$service, $name]; + return $service; } } @@ -289,6 +340,7 @@ public static function reset(bool $initAutoloader = true) { static::$mocks = []; static::$instances = []; + static::$factories = []; if ($initAutoloader) { static::autoloader()->initialize(new Autoload(), new Modules()); @@ -315,6 +367,7 @@ public static function resetSingle(string $name) */ public static function injectMock(string $name, $mock) { + static::$instances[$name] = $mock; static::$mocks[strtolower($name)] = $mock; } diff --git a/system/Config/Factories.php b/system/Config/Factories.php index c4f443cc3a2d..480aee1ec7d4 100644 --- a/system/Config/Factories.php +++ b/system/Config/Factories.php @@ -15,7 +15,6 @@ use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Model; -use Config\Services; use InvalidArgumentException; /** @@ -284,7 +283,7 @@ class_exists($alias, false) } // Have to do this the hard way... - $locator = Services::locator(); + $locator = service('locator'); // Check if the class alias was namespaced if (self::isNamespaced($alias)) { diff --git a/system/Config/Services.php b/system/Config/Services.php index 0ca36751dce5..4eeb599095a4 100644 --- a/system/Config/Services.php +++ b/system/Config/Services.php @@ -292,7 +292,7 @@ public static function filters(?FiltersConfig $config = null, bool $getShared = $config ??= config(FiltersConfig::class); - return new Filters($config, AppServices::request(), AppServices::response()); + return new Filters($config, AppServices::get('request'), AppServices::get('response')); } /** @@ -330,7 +330,7 @@ public static function honeypot(?HoneypotConfig $config = null, bool $getShared /** * Acts as a factory for ImageHandler classes and returns an instance - * of the handler. Used like Services::image()->withFile($path)->rotate(90)->save(); + * of the handler. Used like service('image')->withFile($path)->rotate(90)->save(); * * @return BaseHandler */ @@ -376,8 +376,8 @@ public static function language(?string $locale = null, bool $getShared = true) return static::getSharedInstance('language', $locale)->setLocale($locale); } - if (AppServices::request() instanceof IncomingRequest) { - $requestLocale = AppServices::request()->getLocale(); + if (AppServices::get('request') instanceof IncomingRequest) { + $requestLocale = AppServices::get('request')->getLocale(); } else { $requestLocale = Locale::getDefault(); } @@ -432,7 +432,7 @@ public static function negotiator(?RequestInterface $request = null, bool $getSh return static::getSharedInstance('negotiator', $request); } - $request ??= AppServices::request(); + $request ??= AppServices::get('request'); return new Negotiate($request); } @@ -449,7 +449,7 @@ public static function responsecache(?Cache $config = null, ?CacheInterface $cac } $config ??= config(Cache::class); - $cache ??= AppServices::cache(); + $cache ??= AppServices::get('cache'); return new ResponseCache($config, $cache); } @@ -485,7 +485,7 @@ public static function parser(?string $viewPath = null, ?ViewConfig $config = nu $viewPath = $viewPath ?: (new Paths())->viewDirectory; $config ??= config(ViewConfig::class); - return new Parser($config, $viewPath, AppServices::locator(), CI_DEBUG, AppServices::logger()); + return new Parser($config, $viewPath, AppServices::get('locator'), CI_DEBUG, AppServices::get('logger')); } /** @@ -504,7 +504,7 @@ public static function renderer(?string $viewPath = null, ?ViewConfig $config = $viewPath = $viewPath ?: (new Paths())->viewDirectory; $config ??= config(ViewConfig::class); - return new View($config, $viewPath, AppServices::locator(), CI_DEBUG, AppServices::logger()); + return new View($config, $viewPath, AppServices::get('locator'), CI_DEBUG, AppServices::get('logger')); } /** @@ -544,7 +544,7 @@ public static function createRequest(App $config, bool $isCli = false): void $request->setProtocolVersion($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1'); } - // Inject the request object into Services::request(). + // Inject the request object into Services. static::$instances['request'] = $request; } @@ -565,7 +565,7 @@ public static function incomingrequest(?App $config = null, bool $getShared = tr return new IncomingRequest( $config, - AppServices::uri(), + AppServices::get('uri'), 'php://input', new UserAgent() ); @@ -600,7 +600,7 @@ public static function redirectresponse(?App $config = null, bool $getShared = t $config ??= config(App::class); $response = new RedirectResponse($config); - $response->setProtocolVersion(AppServices::request()->getProtocolVersion()); + $response->setProtocolVersion(AppServices::get('request')->getProtocolVersion()); return $response; } @@ -617,7 +617,7 @@ public static function routes(bool $getShared = true) return static::getSharedInstance('routes'); } - return new RouteCollection(AppServices::locator(), config(Modules::class), config(Routing::class)); + return new RouteCollection(AppServices::get('locator'), config(Modules::class), config(Routing::class)); } /** @@ -632,8 +632,8 @@ public static function router(?RouteCollectionInterface $routes = null, ?Request return static::getSharedInstance('router', $routes, $request); } - $routes ??= AppServices::routes(); - $request ??= AppServices::request(); + $routes ??= AppServices::get('routes'); + $request ??= AppServices::get('request'); return new Router($routes, $request); } @@ -668,7 +668,7 @@ public static function session(?SessionConfig $config = null, bool $getShared = $config ??= config(SessionConfig::class); - $logger = AppServices::logger(); + $logger = AppServices::get('logger'); $driverName = $config->driver; @@ -685,7 +685,7 @@ public static function session(?SessionConfig $config = null, bool $getShared = } } - $driver = new $driverName($config, AppServices::request()->getIPAddress()); + $driver = new $driverName($config, AppServices::get('request')->getIPAddress()); $driver->setLogger($logger); $session = new Session($driver, $config); @@ -713,7 +713,7 @@ public static function siteurifactory( } $config ??= config('App'); - $superglobals ??= AppServices::superglobals(); + $superglobals ??= AppServices::get('superglobals'); return new SiteURIFactory($config, $superglobals); } @@ -747,7 +747,7 @@ public static function throttler(bool $getShared = true) return static::getSharedInstance('throttler'); } - return new Throttler(AppServices::cache()); + return new Throttler(AppServices::get('cache')); } /** @@ -796,7 +796,7 @@ public static function uri(?string $uri = null, bool $getShared = true) if ($uri === null) { $appConfig = config(App::class); - $factory = AppServices::siteurifactory($appConfig, AppServices::superglobals()); + $factory = AppServices::siteurifactory($appConfig, AppServices::get('superglobals')); return $factory->createFromGlobals(); } @@ -817,7 +817,7 @@ public static function validation(?ValidationConfig $config = null, bool $getSha $config ??= config(ValidationConfig::class); - return new Validation($config, AppServices::renderer()); + return new Validation($config, AppServices::get('renderer')); } /** @@ -832,7 +832,7 @@ public static function viewcell(bool $getShared = true) return static::getSharedInstance('viewcell'); } - return new Cell(AppServices::cache()); + return new Cell(AppServices::get('cache')); } /** diff --git a/system/Controller.php b/system/Controller.php index 67aeaf2bedb8..5d9de431fdce 100644 --- a/system/Controller.php +++ b/system/Controller.php @@ -18,7 +18,6 @@ use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Validation\Exceptions\ValidationException; use CodeIgniter\Validation\ValidationInterface; -use Config\Services; use Config\Validation; use Psr\Log\LoggerInterface; @@ -120,7 +119,7 @@ protected function forceHTTPS(int $duration = 31_536_000) */ protected function cachePage(int $time) { - Services::responsecache()->setTtl($time); + service('responsecache')->setTtl($time); } /** @@ -156,7 +155,7 @@ protected function validateData(array $data, $rules, array $messages = [], ?stri */ private function setValidator($rules, array $messages): void { - $this->validator = Services::validation(); + $this->validator = service('validation'); // If you replace the $rules array with the name of the group if (is_string($rules)) { diff --git a/system/Debug/Toolbar.php b/system/Debug/Toolbar.php index a319ab792b0e..22693e035e68 100644 --- a/system/Debug/Toolbar.php +++ b/system/Debug/Toolbar.php @@ -375,10 +375,10 @@ public function prepare(?RequestInterface $request = null, ?ResponseInterface $r * @var IncomingRequest|null $request */ if (CI_DEBUG && ! is_cli()) { - $app = Services::codeigniter(); + $app = service('codeigniter'); - $request ??= Services::request(); - $response ??= Services::response(); + $request ??= service('request'); + $response ??= service('response'); // Disable the toolbar for downloads if ($response instanceof DownloadResponse) { @@ -463,7 +463,7 @@ public function respond() return; } - $request = Services::request(); + $request = service('request'); // If the request contains '?debugbar then we're // simply returning the loading script @@ -512,7 +512,7 @@ protected function format(string $data, string $format = 'html'): string { $data = json_decode($data, true); - if ($this->config->maxHistory !== 0 && preg_match('/\d+\.\d{6}/s', (string) Services::request()->getGet('debugbar_time'), $debugbarTime)) { + if ($this->config->maxHistory !== 0 && preg_match('/\d+\.\d{6}/s', (string) service('request')->getGet('debugbar_time'), $debugbarTime)) { $history = new History(); $history->setFiles( $debugbarTime[0], diff --git a/system/Debug/Toolbar/Collectors/Config.php b/system/Debug/Toolbar/Collectors/Config.php index 1ed23d1cf51a..80673f979f6c 100644 --- a/system/Debug/Toolbar/Collectors/Config.php +++ b/system/Debug/Toolbar/Collectors/Config.php @@ -15,7 +15,6 @@ use CodeIgniter\CodeIgniter; use Config\App; -use Config\Services; /** * Debug toolbar configuration @@ -36,7 +35,7 @@ public static function display(): array 'environment' => ENVIRONMENT, 'baseURL' => $config->baseURL, 'timezone' => app_timezone(), - 'locale' => Services::request()->getLocale(), + 'locale' => service('request')->getLocale(), 'cspEnabled' => $config->CSPEnabled, ]; } diff --git a/system/Debug/Toolbar/Collectors/Views.php b/system/Debug/Toolbar/Collectors/Views.php index 839944e356fa..a63e172c3b8a 100644 --- a/system/Debug/Toolbar/Collectors/Views.php +++ b/system/Debug/Toolbar/Collectors/Views.php @@ -14,7 +14,6 @@ namespace CodeIgniter\Debug\Toolbar\Collectors; use CodeIgniter\View\RendererInterface; -use Config\Services; /** * Views collector @@ -77,7 +76,7 @@ class Views extends BaseCollector private function initViewer(): void { - $this->viewer ??= Services::renderer(); + $this->viewer ??= service('renderer'); } /** diff --git a/system/Events/Events.php b/system/Events/Events.php index ab865c3d7611..a06bd7903e69 100644 --- a/system/Events/Events.php +++ b/system/Events/Events.php @@ -14,7 +14,6 @@ namespace CodeIgniter\Events; use Config\Modules; -use Config\Services; /** * Events @@ -82,7 +81,7 @@ public static function initialize() $files = []; if ($config->shouldDiscover('events')) { - $files = Services::locator()->search('Config/Events.php'); + $files = service('locator')->search('Config/Events.php'); } $files = array_filter(array_map(static function (string $file) { diff --git a/system/Filters/CSRF.php b/system/Filters/CSRF.php index 501d09704ec7..3c1f4505b10e 100644 --- a/system/Filters/CSRF.php +++ b/system/Filters/CSRF.php @@ -18,7 +18,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Security\Exceptions\SecurityException; -use Config\Services; /** * CSRF filter. @@ -52,7 +51,7 @@ public function before(RequestInterface $request, $arguments = null) return; } - $security = Services::security(); + $security = service('security'); try { $security->verify($request); diff --git a/system/Filters/DebugToolbar.php b/system/Filters/DebugToolbar.php index 69e623799361..5ef294e212ac 100644 --- a/system/Filters/DebugToolbar.php +++ b/system/Filters/DebugToolbar.php @@ -15,7 +15,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; -use Config\Services; /** * Debug toolbar filter @@ -41,6 +40,6 @@ public function before(RequestInterface $request, $arguments = null) */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { - Services::toolbar()->prepare($request, $response); + service('toolbar')->prepare($request, $response); } } diff --git a/system/Filters/Filters.php b/system/Filters/Filters.php index ca9370e42231..5790859c4883 100644 --- a/system/Filters/Filters.php +++ b/system/Filters/Filters.php @@ -21,7 +21,6 @@ use Config\Feature; use Config\Filters as FiltersConfig; use Config\Modules; -use Config\Services; /** * Filters @@ -136,7 +135,7 @@ public function __construct($config, RequestInterface $request, ResponseInterfac */ private function discoverFilters(): void { - $locator = Services::locator(); + $locator = service('locator'); // for access by custom filters $filters = $this->config; diff --git a/system/Filters/ForceHTTPS.php b/system/Filters/ForceHTTPS.php index 3afc261eff75..f415bd00e3b8 100644 --- a/system/Filters/ForceHTTPS.php +++ b/system/Filters/ForceHTTPS.php @@ -17,7 +17,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Config\App; -use Config\Services; /** * Force HTTPS filter @@ -43,7 +42,7 @@ public function before(RequestInterface $request, $arguments = null) return; } - $response = Services::response(); + $response = service('response'); try { force_https(YEAR, $request, $response); diff --git a/system/Filters/Honeypot.php b/system/Filters/Honeypot.php index 6f26fff59872..6948d95be8aa 100644 --- a/system/Filters/Honeypot.php +++ b/system/Filters/Honeypot.php @@ -52,6 +52,6 @@ public function before(RequestInterface $request, $arguments = null) */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { - Services::honeypot()->attachHoneypot($response); + service('honeypot')->attachHoneypot($response); } } diff --git a/system/Filters/PageCache.php b/system/Filters/PageCache.php index 9fda34ba4e24..ea6121562d0a 100644 --- a/system/Filters/PageCache.php +++ b/system/Filters/PageCache.php @@ -20,7 +20,6 @@ use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; -use Config\Services; /** * Page Cache filter @@ -31,7 +30,7 @@ class PageCache implements FilterInterface public function __construct() { - $this->pageCache = Services::responsecache(); + $this->pageCache = service('responsecache'); } /** @@ -45,7 +44,7 @@ public function before(RequestInterface $request, $arguments = null) { assert($request instanceof CLIRequest || $request instanceof IncomingRequest); - $response = Services::response(); + $response = service('response'); $cachedResponse = $this->pageCache->get($request, $response); diff --git a/system/Filters/PerformanceMetrics.php b/system/Filters/PerformanceMetrics.php index 1e14d0c9bc05..f2371c7a8d6d 100644 --- a/system/Filters/PerformanceMetrics.php +++ b/system/Filters/PerformanceMetrics.php @@ -15,7 +15,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; -use Config\Services; /** * Performance Metrics filter @@ -43,7 +42,7 @@ public function after(RequestInterface $request, ResponseInterface $response, $a $body = $response->getBody(); if ($body !== null) { - $benchmark = Services::timer(); + $benchmark = service('timer'); $output = str_replace( [ diff --git a/system/HTTP/Exceptions/RedirectException.php b/system/HTTP/Exceptions/RedirectException.php index a574158cd4ff..5f2dcd05e3b7 100644 --- a/system/HTTP/Exceptions/RedirectException.php +++ b/system/HTTP/Exceptions/RedirectException.php @@ -16,7 +16,6 @@ use CodeIgniter\Exceptions\HTTPExceptionInterface; use CodeIgniter\HTTP\ResponsableInterface; use CodeIgniter\HTTP\ResponseInterface; -use Config\Services; use Exception; use InvalidArgumentException; use LogicException; @@ -71,13 +70,13 @@ public function __construct($message = '', int $code = 0, ?Throwable $previous = public function getResponse(): ResponseInterface { if (null === $this->response) { - $this->response = Services::response() + $this->response = service('response') ->redirect(base_url($this->getMessage()), 'auto', $this->getCode()); } - Services::logger()->info( + service('logger')->info( 'REDIRECTED ROUTE at ' - . ($this->response->getHeaderLine('Location') ?: substr($this->response->getHeaderLine('Refresh'), 6)) + . ($this->response->getHeaderLine('Location') ?: substr($this->response->getHeaderLine('Refresh'), 6)) ); return $this->response; diff --git a/system/HTTP/RedirectResponse.php b/system/HTTP/RedirectResponse.php index 5ce1d83b9273..cd1108fb2dbb 100644 --- a/system/HTTP/RedirectResponse.php +++ b/system/HTTP/RedirectResponse.php @@ -58,7 +58,7 @@ public function route(string $route, array $params = [], ?int $code = null, stri { $namedRoute = $route; - $route = Services::routes()->reverseRoute($route, ...$params); + $route = service('routes')->reverseRoute($route, ...$params); if (! $route) { throw HTTPException::forInvalidRedirectRoute($namedRoute); @@ -77,7 +77,7 @@ public function route(string $route, array $params = [], ?int $code = null, stri */ public function back(?int $code = null, string $method = 'auto') { - Services::session(); + service('session'); return $this->redirect(previous_url(), $method, $code); } @@ -92,7 +92,7 @@ public function back(?int $code = null, string $method = 'auto') */ public function withInput() { - $session = Services::session(); + $session = service('session'); $session->setFlashdata('_ci_old_input', [ 'get' => $_GET ?? [], 'post' => $_POST ?? [], @@ -114,10 +114,10 @@ public function withInput() */ private function withErrors(): self { - $validation = Services::validation(); + $validation = service('validation'); if ($validation->getErrors()) { - $session = Services::session(); + $session = service('session'); $session->setFlashdata('_ci_validation_errors', $validation->getErrors()); } @@ -133,7 +133,7 @@ private function withErrors(): self */ public function with(string $key, $message) { - Services::session()->setFlashdata($key, $message); + service('session')->setFlashdata($key, $message); return $this; } diff --git a/system/HTTP/ResponseTrait.php b/system/HTTP/ResponseTrait.php index 61cf0996234b..40b9c3f57067 100644 --- a/system/HTTP/ResponseTrait.php +++ b/system/HTTP/ResponseTrait.php @@ -21,7 +21,6 @@ use CodeIgniter\Pager\PagerInterface; use CodeIgniter\Security\Exceptions\SecurityException; use Config\Cookie as CookieConfig; -use Config\Services; use DateTime; use DateTimeZone; use InvalidArgumentException; @@ -190,7 +189,7 @@ public function getJSON() $body = $this->body; if ($this->bodyFormat !== 'json') { - $body = Services::format()->getFormatter('application/json')->format($body); + $body = service('format')->getFormatter('application/json')->format($body); } return $body ?: null; @@ -222,7 +221,7 @@ public function getXML() $body = $this->body; if ($this->bodyFormat !== 'xml') { - $body = Services::format()->getFormatter('application/xml')->format($body); + $body = service('format')->getFormatter('application/xml')->format($body); } return $body; @@ -247,7 +246,7 @@ protected function formatBody($body, string $format) // Nothing much to do for a string... if (! is_string($body) || $format === 'json-unencoded') { - $body = Services::format()->getFormatter($mime)->format($body); + $body = service('format')->getFormatter($mime)->format($body); } return $body; @@ -672,7 +671,7 @@ protected function sendCookies() private function dispatchCookies(): void { /** @var IncomingRequest $request */ - $request = Services::request(); + $request = service('request'); foreach ($this->cookieStore->display() as $cookie) { if ($cookie->isSecure() && ! $request->isSecure()) { diff --git a/system/Helpers/cookie_helper.php b/system/Helpers/cookie_helper.php index aa6ae2eb21c0..49e568346b68 100755 --- a/system/Helpers/cookie_helper.php +++ b/system/Helpers/cookie_helper.php @@ -13,7 +13,6 @@ use CodeIgniter\Cookie\Cookie; use Config\Cookie as CookieConfig; -use Config\Services; // ============================================================================= // CodeIgniter Cookie Helpers @@ -51,7 +50,7 @@ function set_cookie( ?bool $httpOnly = null, ?string $sameSite = null ) { - $response = Services::response(); + $response = service('response'); $response->setCookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httpOnly, $sameSite); } } @@ -77,7 +76,7 @@ function get_cookie($index, bool $xssClean = false, ?string $prefix = '') $prefix = $cookie->prefix; } - $request = Services::request(); + $request = service('request'); $filter = $xssClean ? FILTER_SANITIZE_FULL_SPECIAL_CHARS : FILTER_DEFAULT; return $request->getCookie($prefix . $index, $filter); @@ -99,7 +98,7 @@ function get_cookie($index, bool $xssClean = false, ?string $prefix = '') */ function delete_cookie($name, string $domain = '', string $path = '/', string $prefix = '') { - Services::response()->deleteCookie($name, $domain, $path, $prefix); + service('response')->deleteCookie($name, $domain, $path, $prefix); } } @@ -109,6 +108,6 @@ function delete_cookie($name, string $domain = '', string $path = '/', string $p */ function has_cookie(string $name, ?string $value = null, string $prefix = ''): bool { - return Services::response()->hasCookie($name, $value, $prefix); + return service('response')->hasCookie($name, $value, $prefix); } } diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index 54c0e48199ce..296504f214a8 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -13,7 +13,6 @@ use CodeIgniter\Validation\Exceptions\ValidationException; use Config\App; -use Config\Services; use Config\Validation; // CodeIgniter Form Helpers @@ -37,7 +36,7 @@ function form_open(string $action = '', $attributes = [], array $hidden = []): s elseif (strpos($action, '://') === false) { // If an action has {locale} if (strpos($action, '{locale}') !== false) { - $action = str_replace('{locale}', Services::request()->getLocale(), $action); + $action = str_replace('{locale}', service('request')->getLocale(), $action); } $action = site_url($action); @@ -61,7 +60,7 @@ function form_open(string $action = '', $attributes = [], array $hidden = []): s $form = '
\n"; // Add CSRF field if enabled, but leave it out for GET requests and requests to external websites - $before = Services::filters()->getFilters()['before']; + $before = service('filters')->getFilters()['before']; if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && strpos($action, base_url()) !== false && ! stripos($form, 'method="get"')) { $form .= csrf_field($csrfId ?? null); @@ -554,7 +553,7 @@ function form_close(string $extra = ''): string */ function set_value(string $field, $default = '', bool $htmlEscape = true) { - $request = Services::request(); + $request = service('request'); // Try any old input data we may have first $value = $request->getOldInput($field); @@ -575,7 +574,7 @@ function set_value(string $field, $default = '', bool $htmlEscape = true) */ function set_select(string $field, string $value = '', bool $default = false): string { - $request = Services::request(); + $request = service('request'); // Try any old input data we may have first $input = $request->getOldInput($field); @@ -611,7 +610,7 @@ function set_select(string $field, string $value = '', bool $default = false): s */ function set_checkbox(string $field, string $value = '', bool $default = false): string { - $request = Services::request(); + $request = service('request'); // Try any old input data we may have first $input = $request->getOldInput($field); @@ -631,7 +630,7 @@ function set_checkbox(string $field, string $value = '', bool $default = false): return ''; } - $session = Services::session(); + $session = service('session'); $hasOldInput = $session->has('_ci_old_input'); // Unchecked checkbox and radio inputs are not even submitted by browsers ... @@ -651,7 +650,7 @@ function set_checkbox(string $field, string $value = '', bool $default = false): */ function set_radio(string $field, string $value = '', bool $default = false): string { - $request = Services::request(); + $request = service('request'); // Try any old input data we may have first $oldInput = $request->getOldInput($field); @@ -705,7 +704,7 @@ function validation_errors() return $errors; } - $validation = Services::validation(); + $validation = service('validation'); return $validation->getErrors(); } @@ -720,7 +719,7 @@ function validation_errors() function validation_list_errors(string $template = 'list'): string { $config = config(Validation::class); - $view = Services::renderer(); + $view = service('renderer'); if (! array_key_exists($template, $config->templates)) { throw ValidationException::forInvalidTemplate($template); @@ -740,7 +739,7 @@ function validation_list_errors(string $template = 'list'): string function validation_show_error(string $field, string $template = 'single'): string { $config = config(Validation::class); - $view = Services::renderer(); + $view = service('renderer'); $errors = array_filter(validation_errors(), static fn ($key) => preg_match( '/^' . str_replace(['\.\*', '\*\.'], ['\..+', '.+\.'], preg_quote($field, '/')) . '$/', diff --git a/system/Helpers/security_helper.php b/system/Helpers/security_helper.php index b2cc833865fa..af6257e5e39c 100644 --- a/system/Helpers/security_helper.php +++ b/system/Helpers/security_helper.php @@ -11,8 +11,6 @@ * the LICENSE file that was distributed with this source code. */ -use Config\Services; - // CodeIgniter Security Helpers if (! function_exists('sanitize_filename')) { @@ -21,7 +19,7 @@ */ function sanitize_filename(string $filename): string { - return Services::security()->sanitizeFilename($filename); + return service('security')->sanitizeFilename($filename); } } diff --git a/system/Helpers/url_helper.php b/system/Helpers/url_helper.php index 76c2b159973f..1207a57b3dda 100644 --- a/system/Helpers/url_helper.php +++ b/system/Helpers/url_helper.php @@ -17,7 +17,6 @@ use CodeIgniter\HTTP\URI; use CodeIgniter\Router\Exceptions\RouterException; use Config\App; -use Config\Services; // CodeIgniter URL Helpers @@ -33,7 +32,7 @@ */ function site_url($relativePath = '', ?string $scheme = null, ?App $config = null): string { - $currentURI = Services::request()->getUri(); + $currentURI = service('request')->getUri(); assert($currentURI instanceof SiteURI); @@ -53,7 +52,7 @@ function site_url($relativePath = '', ?string $scheme = null, ?App $config = nul */ function base_url($relativePath = '', ?string $scheme = null): string { - $currentURI = Services::request()->getUri(); + $currentURI = service('request')->getUri(); assert($currentURI instanceof SiteURI); @@ -73,7 +72,7 @@ function base_url($relativePath = '', ?string $scheme = null): string */ function current_url(bool $returnObject = false, ?IncomingRequest $request = null) { - $request ??= Services::request(); + $request ??= service('request'); /** @var CLIRequest|IncomingRequest $request */ $uri = $request->getUri(); @@ -113,9 +112,9 @@ function previous_url(bool $returnObject = false) */ function uri_string(): string { - // The value of Services::request()->getUri()->getPath() returns + // The value of service('request')->getUri()->getPath() returns // full URI path. - $uri = Services::request()->getUri(); + $uri = service('request')->getUri(); $path = $uri instanceof SiteURI ? $uri->getRoutePath() : $uri->getPath(); diff --git a/system/Language/Language.php b/system/Language/Language.php index 1e5883327459..707590d4c6a4 100644 --- a/system/Language/Language.php +++ b/system/Language/Language.php @@ -13,7 +13,6 @@ namespace CodeIgniter\Language; -use Config\Services; use InvalidArgumentException; use MessageFormatter; @@ -250,7 +249,7 @@ protected function load(string $file, string $locale, bool $return = false) */ protected function requireFile(string $path): array { - $files = Services::locator()->search($path, 'php', false); + $files = service('locator')->search($path, 'php', false); $strings = []; foreach ($files as $file) { diff --git a/system/Router/RouteCollection.php b/system/Router/RouteCollection.php index 99a706d27665..28ac1bf1af49 100644 --- a/system/Router/RouteCollection.php +++ b/system/Router/RouteCollection.php @@ -1145,7 +1145,7 @@ public function cli(string $from, $to, ?array $options = null): RouteCollectionI */ public function view(string $from, string $view, ?array $options = null): RouteCollectionInterface { - $to = static fn (...$data) => Services::renderer() + $to = static fn (...$data) => service('renderer') ->setData(['segments' => $data], 'raw') ->render($view, $options); @@ -1258,7 +1258,7 @@ public function reverseRoute(string $search, ...$params) */ protected function localizeRoute(string $route): string { - return strtr($route, ['{locale}' => Services::request()->getLocale()]); + return strtr($route, ['{locale}' => service('request')->getLocale()]); } /** @@ -1423,7 +1423,7 @@ private function replaceLocale(string $route, ?string $locale = null): string } if ($locale === null) { - $locale = Services::request()->getLocale(); + $locale = service('request')->getLocale(); } return strtr($route, ['{locale}' => $locale]); diff --git a/system/Security/Security.php b/system/Security/Security.php index 33a9ba002b2d..2b80ad1d2af2 100644 --- a/system/Security/Security.php +++ b/system/Security/Security.php @@ -23,7 +23,6 @@ use CodeIgniter\Session\Session; use Config\Cookie as CookieConfig; use Config\Security as SecurityConfig; -use Config\Services; use ErrorException; use InvalidArgumentException; use LogicException; @@ -207,7 +206,7 @@ public function __construct(SecurityConfig $config) $this->configureSession(); } - $this->request = Services::request(); + $this->request = service('request'); $this->hashInCookie = $this->request->getCookie($this->cookieName); $this->restoreHash(); @@ -223,7 +222,7 @@ private function isCSRFCookie(): bool private function configureSession(): void { - $this->session = Services::session(); + $this->session = service('session'); } private function configureCookie(CookieConfig $cookie): void @@ -534,7 +533,7 @@ private function saveHashInCookie(): void ] ); - $response = Services::response(); + $response = service('response'); $response->setCookie($this->cookie); } diff --git a/system/Session/Session.php b/system/Session/Session.php index 85c5caf20b74..0aabcbe31d53 100644 --- a/system/Session/Session.php +++ b/system/Session/Session.php @@ -16,7 +16,6 @@ use CodeIgniter\Cookie\Cookie; use CodeIgniter\I18n\Time; use Config\Cookie as CookieConfig; -use Config\Services; use Config\Session as SessionConfig; use Psr\Log\LoggerAwareTrait; use SessionHandlerInterface; @@ -406,7 +405,7 @@ public function regenerate(bool $destroy = false) private function removeOldSessionCookie(): void { - $response = Services::response(); + $response = service('response'); $cookieStoreInResponse = $response->getCookieStore(); if (! $cookieStoreInResponse->has($this->config->cookieName)) { @@ -931,7 +930,7 @@ protected function setCookie() $expiration = $this->config->expiration === 0 ? 0 : Time::now()->getTimestamp() + $this->config->expiration; $this->cookie = $this->cookie->withValue(session_id())->withExpires($expiration); - $response = Services::response(); + $response = service('response'); $response->setCookie($this->cookie); } } diff --git a/system/Test/CIUnitTestCase.php b/system/Test/CIUnitTestCase.php index 32385c9c866e..3bc511c39738 100644 --- a/system/Test/CIUnitTestCase.php +++ b/system/Test/CIUnitTestCase.php @@ -497,7 +497,7 @@ public function assertCloseEnoughString($expected, $actual, string $message = '' protected function createApplication() { // Initialize the autoloader. - Services::autoloader()->initialize(new Autoload(), new Modules()); + service('autoloader')->initialize(new Autoload(), new Modules()); $app = new MockCodeIgniter(new App()); $app->initialize(); diff --git a/system/Test/ControllerTestTrait.php b/system/Test/ControllerTestTrait.php index af23d73f2be6..3be014194999 100644 --- a/system/Test/ControllerTestTrait.php +++ b/system/Test/ControllerTestTrait.php @@ -100,13 +100,13 @@ protected function setUpControllerTestTrait(): void } if (! $this->uri instanceof URI) { - $factory = Services::siteurifactory($this->appConfig, Services::superglobals(), false); + $factory = Services::siteurifactory($this->appConfig, service('superglobals'), false); $this->uri = $factory->createFromGlobals(); } if (empty($this->request)) { // Do some acrobatics, so we can use the Request service with our own URI - $tempUri = Services::uri(); + $tempUri = service('uri'); Services::injectMock('uri', $this->uri); $this->withRequest(Services::incomingrequest($this->appConfig, false)); @@ -120,7 +120,7 @@ protected function setUpControllerTestTrait(): void } if (empty($this->logger)) { - $this->logger = Services::logger(); + $this->logger = service('logger'); } } @@ -280,7 +280,7 @@ public function withLogger($logger) */ public function withUri(string $uri) { - $factory = Services::siteurifactory(); + $factory = service('siteurifactory'); $this->uri = $factory->createFromString($uri); Services::injectMock('uri', $this->uri); diff --git a/system/Test/FeatureTestTrait.php b/system/Test/FeatureTestTrait.php index 1b05bdd9d6a5..0f2467ffd897 100644 --- a/system/Test/FeatureTestTrait.php +++ b/system/Test/FeatureTestTrait.php @@ -48,7 +48,7 @@ trait FeatureTestTrait */ protected function withRoutes(?array $routes = null) { - $collection = Services::routes(); + $collection = service('routes'); if ($routes !== null) { $collection->resetRoutes(); @@ -190,7 +190,7 @@ public function call(string $method, string $path, ?array $params = null) // Initialize the RouteCollection if (! $routes = $this->routes) { - $routes = Services::routes()->loadRoutes(); + $routes = service('routes')->loadRoutes(); } $routes->setHTTPVerb($method); @@ -211,7 +211,7 @@ public function call(string $method, string $path, ?array $params = null) ->run($routes, true); // Reset directory if it has been set - Services::router()->setDirectory(null); + service('router')->setDirectory(null); return new TestResponse($response); } @@ -313,7 +313,7 @@ protected function setupRequest(string $method, ?string $path = null): IncomingR $path = $parts[0]; $query = $parts[1] ?? ''; - $superglobals = Services::superglobals(); + $superglobals = service('superglobals'); $superglobals->setServer('QUERY_STRING', $query); $uri->setPath($path); @@ -418,7 +418,7 @@ protected function setRequestBody(Request $request, ?array $params = null): Requ } if ($params !== null && $formatMime !== '') { - $formatted = Services::format()->getFormatter($formatMime)->format($params); + $formatted = service('format')->getFormatter($formatMime)->format($params); // "withBodyFormat() and $params of call()" has higher priority than withBody(). $request->setBody($formatted); } diff --git a/system/Test/FilterTestTrait.php b/system/Test/FilterTestTrait.php index ce9aeee7a554..791fc0c2a6d0 100644 --- a/system/Test/FilterTestTrait.php +++ b/system/Test/FilterTestTrait.php @@ -21,7 +21,6 @@ use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Router\RouteCollection; use Config\Filters as FiltersConfig; -use Config\Services; use InvalidArgumentException; use RuntimeException; @@ -96,15 +95,15 @@ protected function setUpFilterTestTrait(): void // Create our own Request and Response so we can // use the same ones for Filters and FilterInterface // yet isolate them from outside influence - $this->request ??= clone Services::request(); - $this->response ??= clone Services::response(); + $this->request ??= clone service('request'); + $this->response ??= clone service('response'); // Create our config and Filters instance to reuse for performance $this->filtersConfig ??= config(FiltersConfig::class); $this->filters ??= new Filters($this->filtersConfig, $this->request, $this->response); if ($this->collection === null) { - $this->collection = Services::routes()->loadRoutes(); + $this->collection = service('routes')->loadRoutes(); } $this->doneFilterSetUp = true; diff --git a/system/Test/TestResponse.php b/system/Test/TestResponse.php index e5fd50ff5faa..f36a9f8ff5e5 100644 --- a/system/Test/TestResponse.php +++ b/system/Test/TestResponse.php @@ -17,7 +17,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\I18n\Time; -use Config\Services; use PHPUnit\Framework\Assert; use PHPUnit\Framework\Constraint\IsEqual; @@ -390,7 +389,7 @@ public function assertJSONExact($test): void } if (is_array($test)) { - $test = Services::format()->getFormatter('application/json')->format($test); + $test = service('format')->getFormatter('application/json')->format($test); } Assert::assertJsonStringEqualsJsonString($test, $json, 'Response does not contain matching JSON.'); diff --git a/system/Validation/FileRules.php b/system/Validation/FileRules.php index a36e31872a36..77f8fa6482db 100644 --- a/system/Validation/FileRules.php +++ b/system/Validation/FileRules.php @@ -17,7 +17,6 @@ use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; use Config\Mimes; -use Config\Services; use InvalidArgumentException; /** @@ -40,7 +39,7 @@ class FileRules public function __construct(?RequestInterface $request = null) { if ($request === null) { - $request = Services::request(); + $request = service('request'); } assert($request instanceof IncomingRequest || $request instanceof CLIRequest); diff --git a/system/View/Cell.php b/system/View/Cell.php index 5b0bdc38040d..b3d00e00c0e9 100644 --- a/system/View/Cell.php +++ b/system/View/Cell.php @@ -93,7 +93,7 @@ public function render(string $library, $params = null, int $ttl = 0, ?string $c } if (method_exists($instance, 'initController')) { - $instance->initController(Services::request(), Services::response(), Services::logger()); + $instance->initController(Services::request(), service('response'), service('logger')); } if (! method_exists($instance, $method)) { diff --git a/system/View/Filters.php b/system/View/Filters.php index 872721c4369b..3f1730a473a7 100644 --- a/system/View/Filters.php +++ b/system/View/Filters.php @@ -13,7 +13,6 @@ namespace CodeIgniter\View; -use Config\Services; use NumberFormatter; /** @@ -194,7 +193,7 @@ public static function local_currency($value, string $currency, ?string $locale */ public static function nl2br(string $value): string { - $typography = Services::typography(); + $typography = service('typography'); return $typography->nl2brExceptPre($value); } @@ -205,7 +204,7 @@ public static function nl2br(string $value): string */ public static function prose(string $value): string { - $typography = Services::typography(); + $typography = service('typography'); return $typography->autoTypography($value); } diff --git a/system/View/Plugins.php b/system/View/Plugins.php index f419d422e92a..da147d097d06 100644 --- a/system/View/Plugins.php +++ b/system/View/Plugins.php @@ -14,7 +14,6 @@ namespace CodeIgniter\View; use CodeIgniter\HTTP\URI; -use Config\Services; /** * View plugins @@ -80,7 +79,7 @@ public static function lang(array $params = []): string */ public static function ValidationErrors(array $params = []): string { - $validator = Services::validation(); + $validator = service('validation'); if ($params === []) { return $validator->listErrors(); } diff --git a/system/View/View.php b/system/View/View.php index 0f17963ce412..cda3d64f6088 100644 --- a/system/View/View.php +++ b/system/View/View.php @@ -17,7 +17,6 @@ use CodeIgniter\Debug\Toolbar\Collectors\Views; use CodeIgniter\Filters\DebugToolbar; use CodeIgniter\View\Exceptions\ViewException; -use Config\Services; use Config\Toolbar; use Config\View as ViewConfig; use Psr\Log\LoggerInterface; @@ -152,8 +151,8 @@ public function __construct( ) { $this->config = $config; $this->viewPath = rtrim($viewPath, '\\/ ') . DIRECTORY_SEPARATOR; - $this->loader = $loader ?? Services::locator(); - $this->logger = $logger ?? Services::logger(); + $this->loader = $loader ?? service('locator'); + $this->logger = $logger ?? service('logger'); $this->debug = $debug ?? CI_DEBUG; $this->saveData = (bool) $config->saveData; } @@ -262,7 +261,7 @@ public function render(string $view, ?array $options = null, ?bool $saveData = n ); // Check if DebugToolbar is enabled. - $filters = Services::filters(); + $filters = service('filters'); $requiredAfterFilters = $filters->getRequiredFilters('after')[0]; if (in_array('toolbar', $requiredAfterFilters, true)) { $debugBarEnabled = true; diff --git a/tests/system/CommonSingleServiceTest.php b/tests/system/CommonSingleServiceTest.php index 976f8d977b0a..d537e20613ae 100644 --- a/tests/system/CommonSingleServiceTest.php +++ b/tests/system/CommonSingleServiceTest.php @@ -105,6 +105,9 @@ public static function provideServiceNames(): iterable { static $services = []; static $excl = [ + 'get', + 'set', + 'override', '__callStatic', 'createRequest', 'serviceExists',