Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion system/CLI/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ public static function strlen(?string $string): int
*/
public static function streamSupports(string $function, $resource): bool
{
if (ENVIRONMENT === 'testing') {
if (service('environmentdetector')->isTesting()) {
// In the current setup of the tests we cannot fully check
// if the stream supports the function since we are using
// filtered streams.
Expand Down
2 changes: 1 addition & 1 deletion system/CLI/InputOutput.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function __construct()
public function input(?string $prefix = null): string
{
// readline() can't be tested.
if ($this->readlineSupport && ENVIRONMENT !== 'testing') {
if ($this->readlineSupport && ! service('environmentdetector')->isTesting()) {
return readline($prefix); // @codeCoverageIgnore
}

Expand Down
2 changes: 1 addition & 1 deletion system/Commands/Database/CreateDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public function run(array $params)
$config = config(Database::class);

// Set to an empty database to prevent connection errors.
$group = ENVIRONMENT === 'testing' ? 'tests' : $config->defaultGroup;
$group = service('environmentdetector')->isTesting() ? 'tests' : $config->defaultGroup;

$config->{$group}['database'] = '';

Expand Down
2 changes: 1 addition & 1 deletion system/Commands/Database/MigrateRefresh.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public function run(array $params)
{
$params['b'] = 0;

if (ENVIRONMENT === 'production') {
if (service('environmentdetector')->isProduction()) {
// @codeCoverageIgnoreStart
$force = array_key_exists('f', $params) || CLI::getOption('f');

Expand Down
2 changes: 1 addition & 1 deletion system/Commands/Database/MigrateRollback.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class MigrateRollback extends BaseCommand
*/
public function run(array $params)
{
if (ENVIRONMENT === 'production') {
if (service('environmentdetector')->isProduction()) {
// @codeCoverageIgnoreStart
$force = array_key_exists('f', $params) || CLI::getOption('f');

Expand Down
2 changes: 1 addition & 1 deletion system/Commands/Database/MigrateStatus.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public function run(array $params)
$status = [];

foreach (array_keys($namespaces) as $namespace) {
if (ENVIRONMENT !== 'testing') {
if (! service('environmentdetector')->isTesting()) {
// Make Tests\\Support discoverable for testing
$this->ignoredNamespaces[] = 'Tests\Support'; // @codeCoverageIgnore
}
Expand Down
2 changes: 1 addition & 1 deletion system/Commands/Translation/LocalizationFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function run(array $params)
$currentDir = APPPATH;
$this->languagePath = $currentDir . 'Language';

if (ENVIRONMENT === 'testing') {
if (service('environmentdetector')->isTesting()) {
$currentDir = SUPPORTPATH . 'Services' . DIRECTORY_SEPARATOR;
$this->languagePath = SUPPORTPATH . 'Language';
}
Expand Down
2 changes: 1 addition & 1 deletion system/Commands/Translation/LocalizationSync.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function run(array $params)
return EXIT_USER_INPUT;
}

if (ENVIRONMENT === 'testing') {
if (service('environmentdetector')->isTesting()) {
$this->languagePath = SUPPORTPATH . 'Language';
}

Expand Down
18 changes: 18 additions & 0 deletions system/Config/Services.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use CodeIgniter\Email\Email;
use CodeIgniter\Encryption\EncrypterInterface;
use CodeIgniter\Encryption\Encryption;
use CodeIgniter\EnvironmentDetector;
use CodeIgniter\Filters\Filters;
use CodeIgniter\Format\Format;
use CodeIgniter\Honeypot\Honeypot;
Expand Down Expand Up @@ -259,6 +260,23 @@ public static function encrypter(?EncryptionConfig $config = null, $getShared =
return $encryption->initialize($config);
}

/**
* Provides a simple way to determine the current environment
* of the application.
*
Comment thread
paulbalandan marked this conversation as resolved.
* Primarily intended for testing environment-specific branches by
* mocking this service. Mocking it does not modify the `ENVIRONMENT`
* constant. It only affects code paths that resolve and use this service.
*/
public static function environmentdetector(?string $environment = null, bool $getShared = true): EnvironmentDetector
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add to system/Config/BaseService.php:

 * @method static EnvironmentDetector environmentdetector(?string $environment = null, bool $getShared = true)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would also shorten (19 > 11 chars) the name to envdetector, env_detector, although a clear description is more important.

{
if ($getShared) {
return static::getSharedInstance('environmentdetector', $environment);
}

return new EnvironmentDetector($environment);
}

/**
* The Exceptions class holds the methods that handle:
*
Expand Down
2 changes: 1 addition & 1 deletion system/Database/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public static function connect($group = null, bool $getShared = true)
$dbConfig = config(DbConfig::class);

if ($group === null) {
$group = (ENVIRONMENT === 'testing') ? 'tests' : $dbConfig->defaultGroup;
$group = service('environmentdetector')->isTesting() ? 'tests' : $dbConfig->defaultGroup;
}

assert(is_string($group));
Expand Down
4 changes: 2 additions & 2 deletions system/Database/MigrationRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ public function findMigrations(): array
$migrations = [];

foreach ($namespaces as $namespace) {
if (ENVIRONMENT !== 'testing' && $namespace === 'Tests\Support') {
if (! service('environmentdetector')->isTesting() && $namespace === 'Tests\Support') {
continue;
}

Expand Down Expand Up @@ -985,7 +985,7 @@ protected function migrate($direction, $migration): bool
$instance = new $class(Database::forge($this->db));
$group = $instance->getDBGroup() ?? $this->group;

if (ENVIRONMENT !== 'testing' && $group === 'tests' && $this->groupFilter !== 'tests') {
if (! service('environmentdetector')->isTesting() && $group === 'tests' && $this->groupFilter !== 'tests') {
// @codeCoverageIgnoreStart
$this->groupSkip = true;

Expand Down
4 changes: 2 additions & 2 deletions system/Debug/ExceptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public function handle(

$this->respond($data, $statusCode)->send();

if (ENVIRONMENT !== 'testing') {
if (! service('environmentdetector')->isTesting()) {
exit($exitCode); // @codeCoverageIgnore
}

Expand Down Expand Up @@ -123,7 +123,7 @@ public function handle(
// Displays the HTML or CLI error code.
$this->render($exception, $statusCode, $viewFile);

if (ENVIRONMENT !== 'testing') {
if (! service('environmentdetector')->isTesting()) {
exit($exitCode); // @codeCoverageIgnore
}
}
Expand Down
2 changes: 1 addition & 1 deletion system/Debug/Toolbar.php
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ public function prepare(?RequestInterface $request = null, ?ResponseInterface $r
*/
public function respond(): void
{
if (ENVIRONMENT === 'testing') {
if (service('environmentdetector')->isTesting()) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion system/Debug/Toolbar/Collectors/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static function display(): array
'ciVersion' => CodeIgniter::CI_VERSION,
'phpVersion' => PHP_VERSION,
'phpSAPI' => PHP_SAPI,
'environment' => ENVIRONMENT,
'environment' => service('environmentdetector')->get(),
'baseURL' => $config->baseURL,
'timezone' => app_timezone(),
'locale' => service('request')->getLocale(),
Expand Down
79 changes: 79 additions & 0 deletions system/EnvironmentDetector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter;

use CodeIgniter\Exceptions\InvalidArgumentException;

/**
* Provides a simple way to determine the current environment of the application.
*
Comment thread
paulbalandan marked this conversation as resolved.
* Primarily intended as a mockable seam for testing environment-specific code
* paths that resolve this class via the `environmentdetector` service.
*
* It does not redefine the `ENVIRONMENT` constant. It affects only code paths
* that resolve and use this class, while code that still reads `ENVIRONMENT`
* directly keeps its current behavior.
*
* For custom environment names beyond the built-in production/development/testing,
* use {@see self::is()}.
*
* @see \CodeIgniter\EnvironmentDetectorTest
*/
final readonly class EnvironmentDetector
{
private string $environment;

/**
* @param non-empty-string|null $environment The environment to use, or null to
* fall back to the `ENVIRONMENT` constant.
*/
public function __construct(?string $environment = null)
{
if ($environment !== null && trim($environment) === '') {
throw new InvalidArgumentException('Environment cannot be an empty string.');
}

$this->environment = $environment !== null ? trim($environment) : ENVIRONMENT;
}
Comment on lines +41 to +48
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe skip double trim()?

Suggested change
public function __construct(?string $environment = null)
{
if ($environment !== null && trim($environment) === '') {
throw new InvalidArgumentException('Environment cannot be an empty string.');
}
$this->environment = $environment !== null ? trim($environment) : ENVIRONMENT;
}
public function __construct(?string $environment = null)
{
$environment = $environment !== null ? trim($environment) : ENVIRONMENT;
if ($environment === '') {
throw new InvalidArgumentException('Environment cannot be an empty string.');
}
$this->environment = $environment;
}


public function get(): string
{
return $this->environment;
}

/**
* Checks if the current environment matches any of the given environments.
*
* @param string ...$environments One or more environment names to check against.
*/
public function is(string ...$environments): bool
{
return in_array($this->environment, $environments, true);
}

public function isProduction(): bool
{
return $this->is('production');
}

public function isDevelopment(): bool
{
return $this->is('development');
}

public function isTesting(): bool
{
return $this->is('testing');
}
}
2 changes: 1 addition & 1 deletion system/Format/JSONFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function format($data)
$options = $config->formatterOptions['application/json'] ?? JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
$options |= JSON_PARTIAL_OUTPUT_ON_ERROR;

if (ENVIRONMENT !== 'production') {
if (! service('environmentdetector')->isProduction()) {
$options |= JSON_PRETTY_PRINT;
}

Expand Down
2 changes: 1 addition & 1 deletion system/HTTP/DownloadResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ public function noCache(): self
public function send()
{
// Turn off output buffering completely, even if php.ini output_buffering is not off
if (ENVIRONMENT !== 'testing') {
if (! service('environmentdetector')->isTesting()) {
while (ob_get_level() > 0) {
ob_end_clean();
}
Expand Down
4 changes: 2 additions & 2 deletions system/HTTP/SSEResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ private function write(string $output): bool
{
echo $output;

if (ENVIRONMENT !== 'testing') {
if (! service('environmentdetector')->isTesting()) {
if (ob_get_level() > 0) {
ob_flush();
}
Expand All @@ -156,7 +156,7 @@ private function write(string $output): bool
public function send()
{
// Turn off output buffering completely, even if php.ini output_buffering is not off
if (ENVIRONMENT !== 'testing') {
if (! service('environmentdetector')->isTesting()) {
set_time_limit(0);
ini_set('zlib.output_compression', 'Off');

Expand Down
2 changes: 1 addition & 1 deletion system/Helpers/form_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ function validation_errors()

// Check the session to see if any were
// passed along from a redirect withErrors() request.
if ($errors !== null && (ENVIRONMENT === 'testing' || ! is_cli())) {
if ($errors !== null && (service('environmentdetector')->isTesting() || ! is_cli())) {
return $errors;
}

Expand Down
2 changes: 1 addition & 1 deletion system/Log/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ protected function interpolate($message, array $context = [])

$replace['{post_vars}'] = '$_POST: ' . print_r(service('superglobals')->getPostArray(), true);
$replace['{get_vars}'] = '$_GET: ' . print_r(service('superglobals')->getGetArray(), true);
$replace['{env}'] = ENVIRONMENT;
$replace['{env}'] = service('environmentdetector')->get();

// Allow us to log the file/line that we are logging from
if (str_contains($message, '{file}') || str_contains($message, '{line}')) {
Expand Down
2 changes: 1 addition & 1 deletion system/Router/Attributes/Restrict.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ protected function checkEnvironment(): void
return;
}

$currentEnv = ENVIRONMENT;
$currentEnv = service('environmentdetector')->get();
$allowed = [];
$denied = [];

Expand Down
2 changes: 1 addition & 1 deletion system/Router/RouteCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1163,7 +1163,7 @@ public function view(string $from, string $view, ?array $options = null): RouteC
*/
public function environment(string $env, Closure $callback): RouteCollectionInterface
{
if ($env === ENVIRONMENT) {
if (service('environmentdetector')->is($env)) {
$callback($this);
}

Expand Down
8 changes: 4 additions & 4 deletions system/Session/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public function __construct(SessionHandlerInterface $driver, SessionConfig $conf
*/
public function start()
{
if (is_cli() && ENVIRONMENT !== 'testing') {
if (is_cli() && ! service('environmentdetector')->isTesting()) {
// @codeCoverageIgnoreStart
$this->logger->debug('Session: Initialization under CLI aborted.');

Expand Down Expand Up @@ -273,7 +273,7 @@ private function removeOldSessionCookie(): void

public function destroy()
{
if (ENVIRONMENT === 'testing') {
if (service('environmentdetector')->isTesting()) {
return;
}

Expand All @@ -287,7 +287,7 @@ public function destroy()
*/
public function close()
{
if (ENVIRONMENT === 'testing') {
if (service('environmentdetector')->isTesting()) {
return;
}

Expand Down Expand Up @@ -616,7 +616,7 @@ protected function setSaveHandler()
*/
protected function startSession()
{
if (ENVIRONMENT === 'testing') {
if (service('environmentdetector')->isTesting()) {
$_SESSION = [];

return;
Expand Down
19 changes: 8 additions & 11 deletions system/Validation/StrictRules/FileRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,14 @@ public function uploaded(?string $blank, string $name): bool
return false;
}

if (ENVIRONMENT === 'testing') {
if ($file->getError() !== 0) {
return false;
}
} else {
// Note: cannot unit test this; no way to over-ride ENVIRONMENT?
// @codeCoverageIgnoreStart
if (! $file->isValid()) {
return false;
}
// @codeCoverageIgnoreEnd
// In the testing env is_uploaded_file() always returns false
// (fixtures aren't real HTTP uploads), so check the error code directly.
$isValid = service('environmentdetector')->isTesting()
? $file->getError() === UPLOAD_ERR_OK
: $file->isValid();

if (! $isValid) {
return false;
}
}

Expand Down
Loading
Loading