Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blueprints: Define constants in auto_prepend_file, silence warnings related to redefining those constants #1400

Merged
merged 4 commits into from
May 15, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { NodePHP } from '@php-wasm/node';
import { rewriteDefineCalls, defineBeforeRun } from './define-wp-config-consts';
import { RecommendedPHPVersion } from '@wp-playground/common';
import {
enablePlatformMuPlugins,
preloadRequiredMuPlugin,
} from '@wp-playground/wordpress';

describe('rewriteDefineCalls', () => {
let php: NodePHP;
Expand Down Expand Up @@ -236,4 +240,32 @@ describe('defineBeforeRun', () => {
})
).rejects.toThrow('PHP.run() failed with exit code');
});

it('should not raise a warning when conflicting with a user-defined constant', async () => {
// Preload the warning-silencing error handler
await enablePlatformMuPlugins(php);
await preloadRequiredMuPlugin(php);
Copy link
Member

@brandonpayton brandonpayton May 15, 2024

Choose a reason for hiding this comment

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

nitpicking something that wasn't added in this PR:
Should this name be a plural preloadRequiredMuPlugins?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Perhaps! Also, I'm questioning whether these two functions should be separate :-)


const constants = {
SITE_URL: 'http://test.url',
};
await defineBeforeRun(php, constants);
php.writeFile(
'/index.php',
`<?php
// This should be warning-free:
define('SITE_URL', 'another value');

// This should trigger a warning:
define('ANOTHER_CONSTANT', 'first');
define('ANOTHER_CONSTANT', 'second');
`
);
const response = await php.run({
scriptPath: '/index.php',
});
expect(response.errors).toEqual(
'PHP Warning: Constant ANOTHER_CONSTANT already defined in /index.php on line 7\n'
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export interface DefineWpConfigConstsStep {
*/
export const defineWpConfigConsts: StepHandler<
DefineWpConfigConstsStep
> = async (playground, { consts, method = 'rewrite-wp-config' }) => {
> = async (playground, { consts, method = 'define-before-run' }) => {
switch (method) {
case 'define-before-run':
await defineBeforeRun(playground, consts);
Expand Down
29 changes: 3 additions & 26 deletions packages/playground/blueprints/src/lib/steps/unzip.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { phpVars } from '@php-wasm/util';
import { StepHandler } from '.';
import { runPhpWithZipFunctions } from '../utils/run-php-with-zip-functions';
import { unzipFile } from '@wp-playground/common';
import { logger } from '@php-wasm/logger';

/**
Expand Down Expand Up @@ -31,8 +30,6 @@ export interface UnzipStep<ResourceType> {
extractToPath: string;
}

const tmpPath = '/tmp/file.zip';

/**
* Unzip a zip file.
*
Expand All @@ -45,33 +42,13 @@ export const unzip: StepHandler<UnzipStep<File>> = async (
{ zipFile, zipPath, extractToPath }
) => {
if (zipPath) {
// Compatibility with the old Blueprints API
// @TODO: Remove the zipPath option in the next major version
await playground.writeFile(
tmpPath,
await playground.readFileAsBuffer(zipPath)
);
logger.warn(
`The "zipPath" option of the unzip() Blueprint step is deprecated and will be removed. ` +
`Use "zipFile" instead.`
);
} else if (zipFile) {
await playground.writeFile(
tmpPath,
new Uint8Array(await zipFile.arrayBuffer())
);
} else {
} else if (!zipFile) {
throw new Error('Either zipPath or zipFile must be provided');
}
const js = phpVars({
zipPath: tmpPath,
extractToPath,
});
await runPhpWithZipFunctions(
playground,
`unzip(${js.zipPath}, ${js.extractToPath});`
);
if (playground.fileExists(tmpPath)) {
await playground.unlink(tmpPath);
}
await unzipFile(playground, (zipFile || zipPath)!, extractToPath);
};
5 changes: 1 addition & 4 deletions packages/playground/common/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,7 @@
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"packages/playground/common/**/*.ts",
"packages/playground/common/package.json"
]
"lintFilePatterns": ["packages/playground/common/**/*.ts"]
}
}
},
Expand Down
129 changes: 129 additions & 0 deletions packages/playground/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,133 @@
* Let's always consider these questions before adding new code here.
*/

import { UniversalPHP } from '@php-wasm/universal';
import { phpVars } from '@php-wasm/util';

export const RecommendedPHPVersion = '8.0';

// @TODO Make these ZIP functions more versatile and
// move them to one of the @php-wasm packages.

/**
* Unzip a zip file inside Playground.
*/
export const unzipFile = async (
php: UniversalPHP,
zipPath: string | File,
extractToPath: string
) => {
if (zipPath instanceof File) {
const zipFile = zipPath;
zipPath = '/tmp/file.zip';
await php.writeFile(
zipPath,
new Uint8Array(await zipFile.arrayBuffer())
);
}
const js = phpVars({
zipPath,
extractToPath,
});
await runPhpWithZipFunctions(
php,
`unzip(${js.zipPath}, ${js.extractToPath});`
);
if (php.fileExists(zipPath)) {
await php.unlink(zipPath);
}
};

const zipFunctions = `<?php

function zipDir($root, $output, $options = array())
{
$root = rtrim($root, '/');
$additionalPaths = array_key_exists('additional_paths', $options) ? $options['additional_paths'] : array();
$excludePaths = array_key_exists('exclude_paths', $options) ? $options['exclude_paths'] : array();
$zip_root = array_key_exists('zip_root', $options) ? $options['zip_root'] : $root;

$zip = new ZipArchive;
$res = $zip->open($output, ZipArchive::CREATE);
if ($res === TRUE) {
$directories = array(
$root . '/'
);
while (sizeof($directories)) {
$current_dir = array_pop($directories);

if ($handle = opendir($current_dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry == '.' || $entry == '..') {
continue;
}

$entry = join_paths($current_dir, $entry);
if (in_array($entry, $excludePaths)) {
continue;
}

if (is_dir($entry)) {
$directory_path = $entry . '/';
array_push($directories, $directory_path);
} else if (is_file($entry)) {
$zip->addFile($entry, substr($entry, strlen($zip_root)));
}
}
closedir($handle);
}
}
foreach ($additionalPaths as $disk_path => $zip_path) {
$zip->addFile($disk_path, $zip_path);
}
$zip->close();
chmod($output, 0777);
}
}

function join_paths()
{
$paths = array();

foreach (func_get_args() as $arg) {
if ($arg !== '') {
$paths[] = $arg;
}
}

return preg_replace('#/+#', '/', join('/', $paths));
}

function unzip($zipPath, $extractTo, $overwrite = true)
{
if (!is_dir($extractTo)) {
mkdir($extractTo, 0777, true);
}
$zip = new ZipArchive;
$res = $zip->open($zipPath);
if ($res === TRUE) {
$zip->extractTo($extractTo);
$zip->close();
chmod($extractTo, 0777);
}
}


function delTree($dir)
{
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
`;

export async function runPhpWithZipFunctions(
playground: UniversalPHP,
code: string
) {
return await playground.run({
code: zipFunctions + code,
});
}
89 changes: 57 additions & 32 deletions packages/playground/wordpress/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { UniversalPHP } from '@php-wasm/universal';
import { joinPaths, phpVar } from '@php-wasm/util';
import { unzip } from '@wp-playground/blueprints';
import { unzipFile } from '@wp-playground/common';

export * from './rewrite-rules';

Expand Down Expand Up @@ -79,33 +79,6 @@ export async function preloadRequiredMuPlugin(php: UniversalPHP) {
if(!file_exists(WP_CONTENT_DIR . '/fonts')) {
mkdir(WP_CONTENT_DIR . '/fonts');
}
?>`,
silenceUnfixableErrors: `<?php
set_error_handler(function($severity, $message, $file, $line) {
/**
* This is a temporary workaround to hide the 32bit integer warnings that
* appear when using various time related function, such as strtotime and mktime.
* Examples of the warnings that are displayed:
* Warning: mktime(): Epoch doesn't fit in a PHP integer in <file>
* Warning: strtotime(): Epoch doesn't fit in a PHP integer in <file>
*/
if (strpos($message, "fit in a PHP integer") !== false) {
return;
}
/**
* Don't complain about network errors when not connected to the network.
*/
if (
(
! defined('USE_FETCH_FOR_REQUESTS') ||
! USE_FETCH_FOR_REQUESTS
) &&
strpos($message, "WordPress could not establish a secure connection to WordPress.org") !== false)
{
return;
}
return false;
});
?>`,
configureErrorLogging: `<?php
$log_file = WP_CONTENT_DIR . '/debug.log';
Expand All @@ -125,6 +98,61 @@ export async function preloadRequiredMuPlugin(php: UniversalPHP) {
'/internal/shared/mu-plugins/0-playground.php',
playgroundMuPlugin
);

// Load the error handler before any other PHP file to ensure it
// treats all the errors, even those trigerred before mu-plugins
// are loaded.
await php.writeFile(
'/internal/shared/preload/error-handler.php',
`<?php
(function() {
$playground_consts = [];
if(file_exists('/internal/shared/consts.json')) {
$playground_consts = @json_decode(file_get_contents('/internal/shared/consts.json'), true) ?: [];
$playground_consts = array_keys($playground_consts);
}
set_error_handler(function($severity, $message, $file, $line) use($playground_consts) {
/**
* This is a temporary workaround to hide the 32bit integer warnings that
* appear when using various time related function, such as strtotime and mktime.
* Examples of the warnings that are displayed:
*
* Warning: mktime(): Epoch doesn't fit in a PHP integer in <file>
* Warning: strtotime(): Epoch doesn't fit in a PHP integer in <file>
*/
if (strpos($message, "fit in a PHP integer") !== false) {
return;
}
/**
* Playground defines some constants upfront, and some of them may be redefined
* in wp-config.php. For example, SITE_URL or WP_DEBUG. This is expected and
* we want Playground constants to take priority without showing warnings like:
*
* Warning: Constant SITE_URL already defined in
*/
if (strpos($message, "already defined") !== false) {
foreach($playground_consts as $const) {
if(strpos($message, "Constant $const already defined") !== false) {
return;
}
}
}
/**
* Don't complain about network errors when not connected to the network.
*/
if (
(
! defined('USE_FETCH_FOR_REQUESTS') ||
! USE_FETCH_FOR_REQUESTS
) &&
strpos($message, "WordPress could not establish a secure connection to WordPress.org") !== false)
{
return;
}
return false;
});
})();`
);
}

/**
Expand Down Expand Up @@ -156,10 +184,7 @@ export async function preloadSqliteIntegration(
});
}
await php.mkdir('/tmp/sqlite-database-integration');
await unzip(php, {
zipFile: sqliteZip,
extractToPath: '/tmp/sqlite-database-integration',
});
await unzipFile(php, sqliteZip, '/tmp/sqlite-database-integration');
const SQLITE_PLUGIN_FOLDER = '/internal/shared/sqlite-database-integration';
await php.mv(
'/tmp/sqlite-database-integration/sqlite-database-integration-main',
Expand Down
Loading