Skip to content

Commit

Permalink
feat(WPConfigFile) inherit env while parsing
Browse files Browse the repository at this point in the history
This updates the `WPConfigFile` class, and the classes used by it, to
inherit the environment variables and allow setups configuring the
`wp-config.php` file based on those (e.g. `ddev`) to work correctly
during setup.
  • Loading branch information
lucatume committed Nov 27, 2024
1 parent 21ee6b1 commit de856c9
Show file tree
Hide file tree
Showing 10 changed files with 139 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ This project adheres to [Semantic Versioning](http://semver.org/).

## [unreleased] Unreleased

## Changed

- Inherit environment variables while parsing configuration files in the `WPConfigFile` class.

## [4.3.8] 2024-11-27;

## Added
Expand Down
1 change: 1 addition & 0 deletions config/typos.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ extend-exclude = [
".git/",
"includes/",
"vendor/",
"tests/_data"
]
ignore-hidden = false

Expand Down
17 changes: 14 additions & 3 deletions src/Process/Loop.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class Loop

private bool $fastFailureFlagRaised = false;
private bool $useFilePayloads = false;
private bool $inheritEnv = false;

/**
* @param array<int|string,Worker|callable> $workers
Expand All @@ -67,7 +68,8 @@ public function __construct(
* rethrow?: bool,
* requireFiles?: array<string>,
* cwd?: string,
* use_file_payloads?: bool,
* useFilePayloads?: bool,
* inheritEnv?: bool
* } $options
*
* @throws ProcessException
Expand All @@ -78,10 +80,14 @@ public static function executeClosure(Closure $closure, int $timeout = 30, array
{
$loop = new self([$closure], 1, true, $timeout, $options);

if (!empty($options['use_file_payloads'])) {
if (!empty($options['useFilePayloads'])) {
$loop->setUseFilePayloads(true);
}

if (!empty($options['inheritEnv'])) {
$loop->setInheritEnv(true);
}

$loop->run();
$results = $loop->getResults();
$result = $results[0];
Expand Down Expand Up @@ -191,7 +197,7 @@ private function startWorker(): void
}

try {
$w = Running::fromWorker($runnableWorker, $this->useFilePayloads);
$w = Running::fromWorker($runnableWorker, $this->useFilePayloads, $this->inheritEnv);
$this->started[$w->getId()] = $w;
$this->running[$w->getId()] = $w;
$this->peakParallelism = max((int)$this->peakParallelism, count($this->running));
Expand Down Expand Up @@ -382,4 +388,9 @@ private function buildWorker(string $id, callable $worker): Worker
{
return new Worker($id, $worker, [], []);
}

public function setInheritEnv(bool $inheritEnv):void
{
$this->inheritEnv = $inheritEnv;
}
}
8 changes: 7 additions & 1 deletion src/Process/Worker/Running.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function __construct(
/**
* @throws ConfigurationException|ProcessException
*/
public static function fromWorker(Worker $worker, bool $useFilePayloads = false): Running
public static function fromWorker(Worker $worker, bool $useFilePayloads = false, bool $inheritEnv = false): Running
{
$workerCallable = $worker->getCallable();
$workerClosure = $workerCallable instanceof Closure ?
Expand All @@ -48,11 +48,17 @@ public static function fromWorker(Worker $worker, bool $useFilePayloads = false)

$workerScriptPathname = __DIR__ . '/worker-script.php';
$control = $worker->getControl();

if ($inheritEnv) {
$control['env'] = array_merge($control['env'] ?? [], getenv());
}

$workerSerializableClosure = new SerializableClosure($workerClosure);

$request = new Request($control, $workerSerializableClosure);
$request->setUseFilePayloads($useFilePayloads);


try {
$workerProcess = new WorkerProcess([PHP_BINARY, $workerScriptPathname, $request->getPayload()]);
$workerProcess->start();
Expand Down
2 changes: 1 addition & 1 deletion src/WordPress/WPConfigFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ private function includeFile(): void
try {
$result = Loop::executeClosure(function () use ($wpSettingsFile, $wpConfigFile): array {
return $this->toIncludeFile($wpConfigFile, $wpSettingsFile);
});
}, 30, ['inheritEnv' => true]);

$returnValue = $result->getReturnValue();

Expand Down
41 changes: 41 additions & 0 deletions tests/_data/wp-config-files/ddev/wp-config-ddev.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php
/**
* #ddev-generated: Automatically generated WordPress settings file.
* ddev manages this file and may delete or overwrite the file unless this comment is removed.
*
* @package ddevapp
*/

if ( getenv( 'IS_DDEV_PROJECT' ) == 'true' ) {
/** The name of the database for WordPress */
defined( 'DB_NAME' ) || define( 'DB_NAME', 'db' );

/** MySQL database username */
defined( 'DB_USER' ) || define( 'DB_USER', 'db' );

/** MySQL database password */
defined( 'DB_PASSWORD' ) || define( 'DB_PASSWORD', 'db' );

/** MySQL hostname */
defined( 'DB_HOST' ) || define( 'DB_HOST', 'ddev-ddev-project-db' );

/** WP_HOME URL */
defined( 'WP_HOME' ) || define( 'WP_HOME', 'https://ddev-project.ddev.site:33001' );

/** WP_SITEURL location */
defined( 'WP_SITEURL' ) || define( 'WP_SITEURL', WP_HOME . '/' );

/** Enable debug */
defined( 'WP_DEBUG' ) || define( 'WP_DEBUG', true );

/**
* Set WordPress Database Table prefix if not already set.
*
* @global string $table_prefix
*/
if ( ! isset( $table_prefix ) || empty( $table_prefix ) ) {
// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
$table_prefix = 'wp_';
// phpcs:enable
}
}
44 changes: 44 additions & 0 deletions tests/_data/wp-config-files/ddev/wp-config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php
/**
* #ddev-generated: Automatically generated WordPress settings file.
* ddev manages this file and may delete or overwrite the file unless this comment is removed.
* It is recommended that you leave this file alone.
*
* @package ddevapp
*/

/** Database charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );

/** The database collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

/** Authentication Unique Keys and Salts. */
define( 'AUTH_KEY', 'tCGZUeKbIdopaFexrGoPqNNlLNsfaJPrHlXPBoPwhGZFvguTIpelFEFsNwCgyQWP' );
define( 'SECURE_AUTH_KEY', 'EdTQtDpfrFpzuwMOIFljwQcyusSTVPtqMfpGhBfKEAJwFxDmFaBdOKiNGPwJsDWA' );
define( 'LOGGED_IN_KEY', 'oWUgUNaIPqTZAeTAAyPALbLWwnRHFVSPYSJooRBpuRlphdjogVDIYLYRRqhwZXIm' );
define( 'NONCE_KEY', 'kHzVnpmLOgkzfNyESZslNHZNzxsatEAJVVnmxJqbKjnooSmdSoVJHzxcWxAxNUwA' );
define( 'AUTH_SALT', 'kGENEUGicWfvwDvjjMtncIOmLQAJztohoqSMRumqjlmhexnRLocvZCjfXGnftfTL' );
define( 'SECURE_AUTH_SALT', 'WLPqqvorXIIPCnPOBPLopTADMtDVGYpvJDSMHOvpgaIpTADVZYNNWakSKtiXhJKg' );
define( 'LOGGED_IN_SALT', 'KZTqsQCEnJMPaYMGHOkpSEBsjnMznCPdzKVxFCHWldfnlNSYpdRaWzXFsBxiTcsk' );
define( 'NONCE_SALT', 'jeBUcIcVAFQjsWbOpomcvjIBARyiEQWwHWSGDzUyLIBixJnHJPtZTdjNUkIgDFow' );

/* Add any custom values between this line and the "stop editing" line. */



/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
defined( 'ABSPATH' ) || define( 'ABSPATH', dirname( __FILE__ ) . '/' );

// Include for settings managed by ddev.
$ddev_settings = __DIR__ . '/wp-config-ddev.php';
if ( ! defined( 'DB_USER' ) && getenv( 'IS_DDEV_PROJECT' ) == 'true' && is_readable( $ddev_settings ) ) {
require_once( $ddev_settings );
}

/** Include wp-settings.php */
if ( file_exists( ABSPATH . '/wp-settings.php' ) ) {
require_once ABSPATH . '/wp-settings.php';
}
2 changes: 2 additions & 0 deletions tests/_data/wp-config-files/ddev/wp-settings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<?php
// Nothing to see here.
2 changes: 1 addition & 1 deletion tests/_support/Traits/LoopIsolation.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ protected function assertInIsolation(
}

$options['cwd'] = !empty($options['cwd']) ? $options['cwd'] : getcwd();
$options['use_file_payloads'] = true;
$options['useFilePayloads'] = true;

$timeout = Debug::isEnabled() ? PHP_INT_MAX : 30;
$result = Loop::executeClosure($runAssertions, $timeout, $options);
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/lucatume/WPBrowser/WordPress/WPConfigFileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,21 @@

class WPConfigFileTest extends Unit
{
private string|null $isDdevProjectEnvVar = null;

protected function setUp(): void
{
parent::setUp();
$this->isDdevProjectEnvVar = (string)getenv('IS_DDEV_PROJECT');
}

protected function tearDown(): void
{
parent::tearDown();
putenv('IS_DDEV_PROJECT=' . (string)$this->isDdevProjectEnvVar);
}


/**
* It should throw if building on non existing root directory
*
Expand Down Expand Up @@ -225,4 +240,13 @@ public function should_detect_use_of_sq_lite_database(): void
$this->assertFalse($wpConfigFile->usesMySQL());
$this->assertTrue($wpConfigFile->usesSQLite());
}

public function test_it_inherits_env():void{
$configFile = codecept_data_dir('wp-config-files/ddev/wp-config.php');
putenv('IS_DDEV_PROJECT=true');

$wpConfigFile = new WPConfigFile(dirname($configFile), $configFile);

$this->assertEquals($wpConfigFile->getConstant('DB_NAME'),'db');
}
}

0 comments on commit de856c9

Please sign in to comment.