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

Add php.defineConstant() public API #748

Merged
merged 8 commits into from
Nov 17, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 46 additions & 0 deletions packages/php-wasm/universal/src/lib/base-php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,32 @@ export abstract class BasePHP implements IsomorphicLocalPHP {
}

#initWebRuntime() {
/**
* This creates a consts.php file in an in-memory
* /tmp directory and sets the auto_prepend_file PHP option
* to always load that file.
* @see https://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
*
* Technically, this is a workaround. In the future, let's implement a
* WASM SAPI method to pass consts directly.
* @see https://github.com/WordPress/wordpress-playground/issues/750
*/
this.setPhpIniEntry('auto_prepend_file', '/tmp/consts.php');
if (!this.fileExists('/tmp/consts.php')) {
this.writeFile(
'/tmp/consts.php',
`<?php
if(file_exists('/tmp/consts.json')) {
$consts = json_decode(file_get_contents('/tmp/consts.json'), true);
foreach ($consts as $const => $value) {
if (!defined($const) && is_scalar($value)) {
define($const, $value);
}
}
}`
);
}

if (this.#phpIniOverrides.length > 0) {
const overridesAsIni =
this.#phpIniOverrides
Expand Down Expand Up @@ -420,6 +446,26 @@ export abstract class BasePHP implements IsomorphicLocalPHP {
}
}

defineConstant(key: string, value: string | number | null) {
let consts = {};
try {
consts = JSON.parse(
this.fileExists('/tmp/consts.json')
? this.readFileAsText('/tmp/consts.json') || '{}'
: '{}'
);
} catch (e) {
// ignore
}
this.writeFile(
'/tmp/consts.json',
JSON.stringify({
...consts,
[key]: value,
})
);
}

/**
* Adds file information to $_FILES superglobal in PHP.
*
Expand Down
7 changes: 7 additions & 0 deletions packages/php-wasm/universal/src/lib/universal-php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,13 @@ export interface RequestHandler {
}

export interface IsomorphicLocalPHP extends RequestHandler {
/**
* Defines a constant in the PHP runtime.
* @param key - The name of the constant.
* @param value - The value of the constant.
*/
defineConstant(key: string, value: string | number | null): void;

/**
* Adds an event listener for a PHP event.
* @param eventType - The type of event to listen for.
Expand Down
4 changes: 4 additions & 0 deletions packages/php-wasm/util/src/lib/paths.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ describe('dirname', () => {
it('should return the directory name of a path', () => {
expect(dirname('/path/to/file.txt')).toEqual('/path/to');
expect(dirname('/path/to/directory/')).toEqual('/path/to');
expect(dirname('/path/to//file')).toEqual('/path/to');
expect(dirname('/path/to')).toEqual('/path');
expect(dirname('/')).toEqual('/');
expect(dirname('')).toEqual('');
expect(dirname('/path/to/')).toEqual('/path');
expect(dirname('/path')).toEqual('/');
expect(dirname('path/to/file.txt')).toEqual('path/to');
Expand Down
5 changes: 5 additions & 0 deletions packages/php-wasm/web/src/lib/web-php-endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,11 @@ export class WebPHPEndpoint implements IsomorphicLocalPHP {
_private.get(this)!.php.onMessage(listener);
}

/** @inheritDoc @php-wasm/web!WebPHP.defineConstant */
defineConstant(key: string, value: string | number | null): void {
_private.get(this)!.php.defineConstant(key, value);
}

/** @inheritDoc @php-wasm/web!WebPHP.addEventListener */
addEventListener(
eventType: PHPEvent['type'],
Expand Down
16 changes: 3 additions & 13 deletions packages/playground/blueprints/src/lib/compile.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ import {
runBlueprintSteps,
validateBlueprint,
} from './compile';
import {
VFS_TMP_DIRECTORY,
defineWpConfigConsts,
} from './steps/define-wp-config-consts';
import { defineWpConfigConsts } from './steps/define-wp-config-consts';

const phpVersion = '8.0';
describe('Blueprints', () => {
Expand Down Expand Up @@ -39,7 +36,7 @@ describe('Blueprints', () => {
);
});

it('should define the consts in a json and auto load the constants in VFS_TMP_DIRECTORY/wp-config.php file', async () => {
it('should define the consts in a json and auto load the defined constants', async () => {
// Define the constants to be tested
const consts = {
TEST_CONST: 'test_value',
Expand All @@ -49,16 +46,9 @@ describe('Blueprints', () => {

// Call the function with the constants and the playground client
// Step1: define the constants
const configFile = await defineWpConfigConsts(php, {
await defineWpConfigConsts(php, {
consts,
});
expect(configFile.startsWith(VFS_TMP_DIRECTORY)).toBe(true);
expect(
php.fileExists(`${VFS_TMP_DIRECTORY}/playground-consts.json`)
).toBe(true);
expect(
php.fileExists(`${php.documentRoot}/playground-consts.json`)
).toBe(false);

// Assert execution of echo statements
php.writeFile('/index.php', '<?php echo TEST_CONST;');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const defineSiteUrl: StepHandler<DefineSiteUrlStep> = async (
playground,
{ siteUrl }
) => {
return await defineWpConfigConsts(playground, {
await defineWpConfigConsts(playground, {
consts: {
WP_HOME: siteUrl,
WP_SITEURL: siteUrl,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import { StepHandler } from '.';
import { updateFile } from './common';

export const VFS_TMP_DIRECTORY = '/vfs-blueprints';

/**
* @inheritDoc defineWpConfigConsts
Expand Down Expand Up @@ -32,11 +29,6 @@ export interface DefineWpConfigConstsStep {
/**
* Defines constants to be used in wp-config.php file.
*
* Technically, this creates a wp-consts.php file in an in-memory
* /vfs-blueprints directory and sets the auto_prepend_file PHP option
* to always load that file.
* @see https://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
*
* This step can be called multiple times, and the constants will be merged.
*
* @param playground The playground client.
Expand All @@ -45,29 +37,7 @@ export interface DefineWpConfigConstsStep {
export const defineWpConfigConsts: StepHandler<
DefineWpConfigConstsStep
> = async (playground, { consts }) => {
await playground.mkdir(VFS_TMP_DIRECTORY);
const phpConstsFilePath = `${VFS_TMP_DIRECTORY}/wp-consts.php`;
const jsonPath = `${VFS_TMP_DIRECTORY}/playground-consts.json`;
await updateFile(playground, phpConstsFilePath, (contents) => {
if (!contents.includes(jsonPath)) {
return `<?php
$consts = json_decode(file_get_contents('${jsonPath}'), true);
foreach ($consts as $const => $value) {
if (!defined($const)) {
define($const, $value);
}
for (const key in consts) {
await playground.defineConstant(key, consts[key] as string);
}
?>${contents}`;
}
return contents;
});
await updateFile(playground, jsonPath, (contents) =>
JSON.stringify({
...JSON.parse(contents || '{}'),
...consts,
})
);

await playground.setPhpIniEntry('auto_prepend_file', phpConstsFilePath);
return phpConstsFilePath;
};