PluginProbe
FlyWP Helper – Page Cache, Page Optimization, Emails for FlyWP Server Control Panel / 1.8.0
FlyWP Helper – Page Cache, Page Optimization, Emails for FlyWP Server Control Panel v1.8.0
1.8.0 1.7.1 1.7.0 1.6.0 1.5.2 trunk 0.1 0.2.0 0.2.1 0.3 0.3.1 0.3.2 0.3.3 0.3.4 0.4 0.4.1 0.4.2 0.4.3 1.0 1.1 1.2 1.3.1 1.4.0 1.4.1 1.5.0 All 27 releases
flywp / includes / StaticSite / Engine / Cli / JsonCommand.php

JsonCommand.php in FlyWP Helper – Page Cache, Page Optimization, Emails for FlyWP Server Control Panel 1.8.0, at includes/StaticSite/Engine/Cli/JsonCommand.php

73 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 // phpcs:disable WordPress.WP.AlternativeFunctions -- WP-CLI output: STDOUT and plain JSON lines, no WP_Filesystem.
3
4 namespace FlyWP\StaticSite\Engine\Cli;
5
6 /**
7 * A WP-CLI command that prints one JSON result line to stdout:
8 * `{"event":"result","status":"success|failed","message":null}`.
9 *
10 * - PHP notices and other output go to STDERR, so the result line is the only stdout line.
11 * - Exit code 0 on success, 1 on failure.
12 *
13 * @since 1.8.0
14 */
15 abstract class JsonCommand {
16
17 /**
18 * @var callable function( string $line ). Writes one stdout line.
19 */
20 private $output;
21
22 /**
23 * @param callable|null $output Line writer. STDOUT when null.
24 */
25 public function __construct( $output = null ) {
26 $this->output = $output ? $output : function ( $line ) {
27 fwrite( STDOUT, $line . "\n" );
28 };
29 }
30
31 /**
32 * Run the command.
33 *
34 * @param array $assoc_args Named arguments.
35 *
36 * @return int Exit code.
37 */
38 abstract public function run( array $assoc_args );
39
40 /**
41 * Run the command from WP-CLI and exit with its code. Each command calls it from __invoke(),
42 * because WP-CLI reads the options from the __invoke() docblock.
43 *
44 * @param array $assoc_args Named arguments.
45 *
46 * @return void
47 */
48 protected function execute( array $assoc_args ) {
49 ini_set( 'display_errors', 'stderr' ); // phpcs:ignore WordPress.PHP.IniSet -- stdout keeps only the JSON result line.
50
51 \WP_CLI::halt( $this->run( $assoc_args ) );
52 }
53
54 /**
55 * Print the result line.
56 *
57 * @param string|null $error Error message. Null on success.
58 *
59 * @return int Exit code.
60 */
61 protected function result( $error = null ) {
62 $line = [
63 'event' => 'result',
64 'status' => $error === null ? 'success' : 'failed',
65 'message' => $error,
66 ];
67
68 call_user_func( $this->output, (string) json_encode( $line, JSON_UNESCAPED_SLASHES ) );
69
70 return $error === null ? 0 : 1;
71 }
72 }
73