diff --git a/features/formatter.feature b/features/formatter.feature index 62753cbd0..b7eedb162 100644 --- a/features/formatter.feature +++ b/features/formatter.feature @@ -189,3 +189,55 @@ Feature: Format output | | | banana | | | | mango | | 1 | bar | br | + + Scenario: Format boolean values in table and JSON + Given an empty directory + And a file.php file: + """ + 1, + 'status' => true, + ), + array( + 'id' => 2, + 'status' => false, + ), + ); + $assoc_args = array(); + $formatter = new WP_CLI\Formatter( $assoc_args, array( 'id', 'status' ) ); + $formatter->display_items( $items ); + """ + + When I run `wp eval-file file.php --skip-wordpress` + Then STDOUT should be a table containing rows: + | id | status | + | 1 | true | + | 2 | false | + + Scenario: Format boolean values as JSON preserves boolean type + Given an empty directory + And a file.php file: + """ + 1, + 'status' => true, + ), + array( + 'id' => 2, + 'status' => false, + ), + ); + $assoc_args = array( 'format' => 'json' ); + $formatter = new WP_CLI\Formatter( $assoc_args, array( 'id', 'status' ) ); + $formatter->display_items( $items ); + """ + + When I run `wp eval-file file.php --skip-wordpress` + Then STDOUT should be JSON containing: + """ + [{"id":1,"status":true},{"id":2,"status":false}] + """ diff --git a/php/WP_CLI/Formatter.php b/php/WP_CLI/Formatter.php index 87480a24a..ce17fe35b 100644 --- a/php/WP_CLI/Formatter.php +++ b/php/WP_CLI/Formatter.php @@ -356,7 +356,11 @@ private function assoc_array_to_rows( $fields ) { } /** - * Transforms objects and arrays to JSON as necessary + * Transforms item values for string-based output formats (table/CSV). + * + * Converts complex types to strings: + * - Objects and arrays are converted to JSON strings + * - Booleans are converted to "true" or "false" * * @param array|object $item * @return mixed @@ -371,6 +375,13 @@ public function transform_item_values_to_json( $item ) { } elseif ( is_array( $item ) ) { $item[ $true_field ] = json_encode( $value ); } + } elseif ( is_bool( $value ) ) { + // Convert boolean to string representation for table/CSV display + if ( is_object( $item ) ) { + $item->$true_field = $value ? 'true' : 'false'; + } elseif ( is_array( $item ) ) { + $item[ $true_field ] = $value ? 'true' : 'false'; + } } } return $item;