Skip to content

Commit 46051ea

Browse files
authored
Merge pull request #5928 from tfirdaus/fix/5542-boolean-output
2 parents 853d319 + f9b4b49 commit 46051ea

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

features/formatter.feature

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,41 @@ Feature: Format output
153153
| gaa/gaa-log | * | ✔ |
154154
| gaa/gaa-nonsense | v3.0.11 | 🛇 |
155155
| gaa/gaa-100%new | v100%new | ✔ |
156+
157+
Scenario: Format data with boolean value
158+
Given an empty directory
159+
And a file.php file:
160+
"""
161+
<?php
162+
$items = array(
163+
array(
164+
'id' => 1,
165+
'status' => true,
166+
'object' => new stdClass(),
167+
'number' => 10,
168+
'string' => 'foo',
169+
),
170+
array(
171+
'id' => 2,
172+
'status' => false,
173+
'object' => new stdClass(),
174+
'number' => 20,
175+
'string' => 'bar',
176+
),
177+
);
178+
$iterator = \WP_CLI\Utils\iterator_map(
179+
$items,
180+
function (array $item) {
181+
return $item;
182+
}
183+
);
184+
$assoc_args = array( 'format' => 'table' );
185+
$formatter = new WP_CLI\Formatter( $assoc_args, array( 'id', 'status', 'object', 'number', 'string' ) );
186+
$formatter->display_items($iterator);
187+
"""
188+
189+
When I run `wp eval-file file.php --skip-wordpress`
190+
Then STDOUT should be a table containing rows:
191+
| id | status | object | number | string |
192+
| 1 | true | {} | 10 | foo |
193+
| 2 | false | {} | 20 | bar |

php/WP_CLI/Formatter.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ private function assoc_array_to_rows( $fields ) {
347347
}
348348

349349
/**
350-
* Transforms objects and arrays to JSON as necessary
350+
* Transforms into shell-friendly output, as necessary
351351
*
352352
* @param mixed $item
353353
* @return mixed
@@ -356,12 +356,28 @@ public function transform_item_values_to_json( $item ) {
356356
foreach ( $this->args['fields'] as $field ) {
357357
$true_field = $this->find_item_key( $item, $field );
358358
$value = is_object( $item ) ? $item->$true_field : $item[ $true_field ];
359+
360+
// Transform into JSON.
359361
if ( is_array( $value ) || is_object( $value ) ) {
360362
if ( is_object( $item ) ) {
361363
$item->$true_field = json_encode( $value );
362364
} elseif ( is_array( $item ) ) {
363365
$item[ $true_field ] = json_encode( $value );
364366
}
367+
368+
continue;
369+
}
370+
371+
// Transform boolean.
372+
// See: https://github.com/wp-cli/wp-cli/issues/5542
373+
if ( is_bool( $value ) ) {
374+
if ( is_object( $item ) ) {
375+
$item->$true_field = $value ? 'true' : 'false';
376+
} elseif ( is_array( $item ) ) {
377+
$item[ $true_field ] = $value ? 'true' : 'false';
378+
}
379+
380+
continue;
365381
}
366382
}
367383
return $item;

0 commit comments

Comments
 (0)