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