| 1 |
<?php |
| 2 |
/** |
| 3 |
* WP_CLI shim for the MCP CLI bridge. |
| 4 |
* |
| 5 |
* xSpeed's CLI command callbacks emit output via \WP_CLI::log/success/ |
| 6 |
* warning/error. In a normal web (MCP) request the real WP_CLI class |
| 7 |
* isn't loaded, so those calls would fatal. This shim provides a minimal |
| 8 |
* global \WP_CLI whose methods forward to a swappable output buffer. |
| 9 |
* |
| 10 |
* Class definition is one-shot (PHP can't redefine a class), so the |
| 11 |
* global \WP_CLI delegates to Cli_Shim's current target buffer, which |
| 12 |
* Cli_Bridge swaps per command run. If the REAL WP_CLI is already loaded |
| 13 |
* (running under actual wp-cli), we do NOT define ours — the native one |
| 14 |
* wins and the bridge simply isn't used in that context. |
| 15 |
* |
| 16 |
* @package XSpeed |
| 17 |
*/ |
| 18 |
|
| 19 |
declare(strict_types=1); |
| 20 |
|
| 21 |
namespace XSpeed\Modules\Mcp; |
| 22 |
|
| 23 |
defined( 'ABSPATH' ) || exit; |
| 24 |
|
| 25 |
final class Cli_Shim { |
| 26 |
|
| 27 |
/** @var Cli_Output_Buffer|null */ |
| 28 |
private static $target = null; |
| 29 |
|
| 30 |
/** Point the global \WP_CLI shim at a buffer for the duration of a run. */ |
| 31 |
public static function bind( Cli_Output_Buffer $buffer ): void { |
| 32 |
self::$target = $buffer; |
| 33 |
self::ensure_class(); |
| 34 |
} |
| 35 |
|
| 36 |
public static function unbind(): void { |
| 37 |
self::$target = null; |
| 38 |
} |
| 39 |
|
| 40 |
/** Forwarded from the global \WP_CLI shim. */ |
| 41 |
public static function emit( string $prefix, string $message ): void { |
| 42 |
if ( null !== self::$target ) { |
| 43 |
self::$target->push( '' === $prefix ? $message : $prefix . $message ); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Load the global \WP_CLI shim class routing to this shim — ONLY if |
| 49 |
* the real one isn't present (i.e. we're not under actual wp-cli). |
| 50 |
*/ |
| 51 |
private static function ensure_class(): void { |
| 52 |
if ( class_exists( '\\WP_CLI', false ) ) { |
| 53 |
return; |
| 54 |
} |
| 55 |
require_once __DIR__ . '/wp-cli-shim-class.php'; |
| 56 |
} |
| 57 |
} |
| 58 |
|