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

PHP.run(): Throw JS exception on runtime error, remove throwOnError flag #1137

Merged
merged 5 commits into from
Mar 29, 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
21 changes: 13 additions & 8 deletions packages/php-wasm/node/src/test/php.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -922,37 +922,42 @@ describe.each(SupportedPHPVersions)('PHP %s', (phpVersion) => {
)) {
// Run via `code`
it(testName, async () => {
const result = await php.run({
const promise = php.run({
code: testSnippet,
});
expect(result.exitCode).toBeGreaterThan(0);
await expect(promise).rejects.toThrow();
});

// Run via the request handler
it(testName, async () => {
php.writeFile('/test.php', testSnippet);
const result = await php.run({
const promise = php.run({
scriptPath: '/test.php',
});
expect(result.exitCode).toBeGreaterThan(0);
await expect(promise).rejects.toThrow();
});
}
});
it('Returns the correct exit code on subsequent runs', async () => {
const result1 = await php.run({
const promise1 = php.run({
code: '<?php throw new Exception();',
});
expect(result1.exitCode).toBe(255);
// expect(result1.exitCode).toBe(255);
await expect(promise1).rejects.toThrow(
'PHP.run() failed with exit code 255'
);

const result2 = await php.run({
code: '<?php exit(0);',
});
expect(result2.exitCode).toBe(0);

const result3 = await php.run({
const promise3 = php.run({
code: '<?php exit(1);',
});
expect(result3.exitCode).toBe(1);
await expect(promise3).rejects.toThrow(
'PHP.run() failed with exit code 1'
);
});
});

Expand Down
2 changes: 1 addition & 1 deletion packages/php-wasm/universal/src/lib/base-php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ export abstract class BasePHP implements IsomorphicLocalPHP {
}

const response = await this.#handleRequest();
if (request.throwOnError && response.exitCode !== 0) {
if (response.exitCode !== 0) {
const output = {
stdout: response.text,
stderr: response.errors,
Expand Down
6 changes: 0 additions & 6 deletions packages/php-wasm/universal/src/lib/universal-php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,12 +542,6 @@ export interface PHPRunOptions {
* The code snippet to eval instead of a php file.
*/
code?: string;

/**
* Whether to throw an error if the PHP process exits with a non-zero code
* or outputs to stderr.
*/
throwOnError?: boolean;
}

/**
Expand Down
4 changes: 0 additions & 4 deletions packages/playground/blueprints/public/blueprint-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -1411,10 +1411,6 @@
"code": {
"type": "string",
"description": "The code snippet to eval instead of a php file."
},
"throwOnError": {
"type": "boolean",
"description": "Whether to throw an error if the PHP process exits with a non-zero code or outputs to stderr."
}
},
"additionalProperties": false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ export const activatePlugin: StepHandler<ActivatePluginStep> = async (

const docroot = await playground.documentRoot;
await playground.run({
throwOnError: true,
code: `<?php
define( 'WP_ADMIN', true );
require_once( ${phpVar(docroot)}. "/wp-load.php" );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export const activateTheme: StepHandler<ActivateThemeStep> = async (
progress?.tracker.setCaption(`Activating ${themeFolderName}`);
const docroot = await playground.documentRoot;
await playground.run({
throwOnError: true,
code: `<?php
define( 'WP_ADMIN', true );
require_once( ${phpVar(docroot)}. "/wp-load.php" );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ describe('rewriteDefineCalls', () => {
define('WP_DEBUG', true);

// The third define() argument is also supported:
@define('SAVEQUERIES', false, true);
@define('SAVEQUERIES', false, true);

// Expression
define(true ? 'WP_DEBUG_LOG' : 'WP_DEBUG_LOG', 123);
Expand Down Expand Up @@ -230,9 +230,10 @@ describe('defineBeforeRun', () => {
SITE_URL: 'http://test.url',
};
await defineBeforeRun(php, constants);
const response = await php.run({
code: `<?php echo json_encode(['SITE_URL' => SITE_URL]);`,
});
expect(response.errors).toContain('PHP Fatal error:');
await expect(
php.run({
code: `<?php echo json_encode(['SITE_URL' => SITE_URL]);`,
})
).rejects.toThrow('PHP.run() failed with exit code');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ export async function rewriteDefineCalls(
consts,
});
await playground.run({
throwOnError: true,
code: `${rewriteWpConfigToDefineConstants}
$wp_config_path = '/tmp/code.php';
$wp_config = file_get_contents($wp_config_path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ export const enableMultisite: StepHandler<EnableMultisiteStep> = async (

// Deactivate all the plugins as required by the multisite installation.
const result = await playground.run({
throwOnError: true,
code: `<?php
define( 'WP_ADMIN', true );
require_once(${phpVar(docroot)} . "/wp-load.php");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ export const importWordPressFiles: StepHandler<
joinPaths(documentRoot, 'wp-admin', 'upgrade.php')
);
await playground.run({
throwOnError: true,
code: `<?php
$_GET['step'] = 'upgrade_db';
require ${upgradePhp};
Expand Down
2 changes: 1 addition & 1 deletion packages/playground/blueprints/src/lib/steps/run-php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ export const runPHP: StepHandler<RunPHPStep, Promise<PHPResponse>> = async (
playground,
{ code }
) => {
return await playground.run({ code, throwOnError: true });
return await playground.run({ code });
};
2 changes: 0 additions & 2 deletions packages/playground/blueprints/src/lib/steps/site-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export const setSiteOptions: StepHandler<SetSiteOptionsStep> = async (
) => {
const docroot = await php.documentRoot;
await php.run({
throwOnError: true,
code: `<?php
include ${phpVar(docroot)} . '/wp-load.php';
$site_options = ${phpVar(options)};
Expand Down Expand Up @@ -81,7 +80,6 @@ export const updateUserMeta: StepHandler<UpdateUserMetaStep> = async (
) => {
const docroot = await php.documentRoot;
await php.run({
throwOnError: true,
code: `<?php
include ${phpVar(docroot)} . '/wp-load.php';
$meta = ${phpVar(meta)};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export async function runPhpWithZipFunctions(
code: string
) {
return await playground.run({
throwOnError: true,
code: zipFunctions + code,
});
}
3 changes: 0 additions & 3 deletions packages/playground/remote/src/lib/worker-thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,15 +403,13 @@ try {

if (args.includes('-r')) {
result = await childPHP.run({
throwOnError: true,
code: `${cliBootstrapScript} ${
args[args.indexOf('-r') + 1]
}`,
env: options.env,
});
} else if (args[1] === 'wp-cli.phar') {
result = await childPHP.run({
throwOnError: true,
code: `${cliBootstrapScript} require( "/wordpress/wp-cli.phar" );`,
env: {
...options.env,
Expand All @@ -423,7 +421,6 @@ try {
});
} else {
result = await childPHP.run({
throwOnError: true,
scriptPath: args[1],
env: options.env,
});
Expand Down
21 changes: 10 additions & 11 deletions packages/playground/website/demos/php-blueprints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ try {
*
* > echo file_get_contents('http://localhost:5400/website-server/');
* > <b>Warning</b>: PHP Request Startup: Failed to open stream: Operation timed out in <b>php-wasm run script</b> on line <b>13</b><br />
*
*
* The check is therefore disabled for now.
*/
require '/wordpress/blueprints.phar';

$blueprint = BlueprintBuilder::create()
// This isn't a WordPress zip file since wordpress.org
// doesn't expose the right CORS headers. It is a HTTPS-hosted
Expand All @@ -105,7 +105,7 @@ try {
'https://downloads.wordpress.org/plugin/hello-dolly.zip',
// When the regular UrlDataSource is used, the second
// downloaded zip file always errors with:
// > Failed to open stream: Operation timed out
// > Failed to open stream: Operation timed out
'https://downloads.wordpress.org/plugin/classic-editor.zip',
'https://downloads.wordpress.org/plugin/gutenberg.17.7.0.zip',
] )
Expand All @@ -120,26 +120,26 @@ try {
->withFile( 'wordpress.txt', 'Data' )
->toBlueprint()
;

echo "Running the following Blueprint:\n";
echo json_encode($blueprint, JSON_PRETTY_PRINT)."\n\n";

$subscriber = new class implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return [
ProgressEvent::class => 'onProgress',
DoneEvent::class => 'onDone',
];
}

public function onProgress( ProgressEvent $event ) {
post_message_to_js(json_encode([
'type' => 'progress',
'caption' => $event->caption,
'progress' => $event->progress,
]));
}

public function onDone( DoneEvent $event ) {
post_message_to_js(json_encode([
'type' => 'progress',
Expand All @@ -148,7 +148,7 @@ try {
}
};


$results = run_blueprint(
$blueprint,
[
Expand All @@ -158,13 +158,12 @@ try {
'progressType' => 'steps',
]
);

echo "Blueprint execution finished!\n";
echo "Contents of /wordpress/wp-content/plugins:";
print_r(glob('/wordpress/wp-content/plugins/*'));

`,
throwOnError: true,
});

outputDiv.textContent += result.text;
Expand Down
Loading