CliResultFormatter.php
76 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Automattic\WooCommerce\Blueprint\ResultFormatters; |
| 4 | |
| 5 | use Automattic\WooCommerce\Blueprint\StepProcessorResult; |
| 6 | use function WP_CLI\Utils\format_items; |
| 7 | |
| 8 | /** |
| 9 | * Class CliResultFormatter |
| 10 | */ |
| 11 | class CliResultFormatter { |
| 12 | /** |
| 13 | * The results to format. |
| 14 | * |
| 15 | * @var StepProcessorResult[] |
| 16 | */ |
| 17 | private array $results; |
| 18 | |
| 19 | /** |
| 20 | * CliResultFormatter constructor. |
| 21 | * |
| 22 | * @param array $results The results to format. |
| 23 | */ |
| 24 | public function __construct( array $results ) { |
| 25 | $this->results = $results; |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Format the results. |
| 30 | * |
| 31 | * @param string $message_type The message type to format. |
| 32 | * |
| 33 | * @return void |
| 34 | * |
| 35 | * @throws \Exception If WP CLI Utils is not found. |
| 36 | */ |
| 37 | public function format( $message_type = 'debug' ) { |
| 38 | $header = array( 'Step Processor', 'Type', 'Message' ); |
| 39 | $items = array(); |
| 40 | |
| 41 | foreach ( $this->results as $result ) { |
| 42 | $step_name = $result->get_step_name(); |
| 43 | foreach ( $result->get_messages( $message_type ) as $message ) { |
| 44 | $items[] = array( |
| 45 | 'Step Processor' => $step_name, |
| 46 | 'Type' => $message['type'], |
| 47 | 'Message' => $message['message'], |
| 48 | ); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | $format_items_exist = function_exists( '\WP_CLI\Utils\format_items' ); |
| 53 | |
| 54 | if ( ! $format_items_exist ) { |
| 55 | throw new \Exception( 'WP CLI Utils not found' ); |
| 56 | } |
| 57 | |
| 58 | format_items( 'table', $items, $header ); |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Check if all results are successful. |
| 63 | * |
| 64 | * @return bool True if all results are successful, false otherwise. |
| 65 | */ |
| 66 | public function is_success() { |
| 67 | foreach ( $this->results as $result ) { |
| 68 | $is_success = $result->is_success(); |
| 69 | if ( ! $is_success ) { |
| 70 | return false; |
| 71 | } |
| 72 | } |
| 73 | return true; |
| 74 | } |
| 75 | } |
| 76 |