Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions features/formatter.feature
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,58 @@ Feature: Format output
| | | mango |
| 1 | bar | br |

Scenario: Format boolean values in table and JSON
Given an empty directory
And a file.php file:
"""
<?php
$items = array(
array(
'id' => 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: JSON format preserves boolean types
Given an empty directory
And a file.php file:
"""
<?php
$items = array(
array(
'id' => 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}]
"""

Scenario: Custom fields that exist in some items but not others
Given an empty directory
And a custom-fields.php file:
Expand Down
13 changes: 12 additions & 1 deletion php/WP_CLI/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,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
Expand All @@ -513,6 +517,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;
Expand Down
Loading