| 1 |
<?php |
| 2 |
/** |
| 3 |
* Helper trait for MCP handlers. |
| 4 |
* |
| 5 |
* @package McpAdapter |
| 6 |
*/ |
| 7 |
|
| 8 |
declare( strict_types=1 ); |
| 9 |
|
| 10 |
namespace WP\MCP\Handlers; |
| 11 |
|
| 12 |
use WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface; |
| 13 |
|
| 14 |
/** |
| 15 |
* Provides common helper methods for MCP handlers. |
| 16 |
*/ |
| 17 |
trait HandlerHelperTrait { |
| 18 |
/** |
| 19 |
* Extracts parameters from a request message. |
| 20 |
* |
| 21 |
* Handles both direct params and nested params structure for backward compatibility. |
| 22 |
* This normalizes the dual parameter patterns found throughout handlers. |
| 23 |
* |
| 24 |
* @param array $data Request data that may have params at root or nested. |
| 25 |
* |
| 26 |
* @return array Extracted parameters. |
| 27 |
*/ |
| 28 |
protected function extract_params( array $data ): array { |
| 29 |
return $data['params'] ?? $data; |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Validate that a filtered list value is still an array. |
| 34 |
* |
| 35 |
* If a filter callback returns a non-array value, logs a warning |
| 36 |
* and falls back to the original unfiltered array to prevent |
| 37 |
* downstream type errors. |
| 38 |
* |
| 39 |
* @since 0.5.0 |
| 40 |
* |
| 41 |
* @param mixed $filtered The value returned by apply_filters. |
| 42 |
* @param array $original The original unfiltered array. |
| 43 |
* @param string $filter_name The filter hook name (for logging). |
| 44 |
* @param \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface $error_handler The error handler for logging. |
| 45 |
* |
| 46 |
* @return array The validated array (filtered if valid, original if not). |
| 47 |
*/ |
| 48 |
protected function validate_filtered_list( $filtered, array $original, string $filter_name, McpErrorHandlerInterface $error_handler ): array { |
| 49 |
if ( is_array( $filtered ) ) { |
| 50 |
return $filtered; |
| 51 |
} |
| 52 |
|
| 53 |
$error_handler->log( |
| 54 |
'Filter returned non-array value, falling back to original list', |
| 55 |
array( |
| 56 |
'filter' => $filter_name, |
| 57 |
'returned_type' => gettype( $filtered ), |
| 58 |
), |
| 59 |
'warning' |
| 60 |
); |
| 61 |
|
| 62 |
return $original; |
| 63 |
} |
| 64 |
} |
| 65 |
|