-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathFormatter.php
More file actions
861 lines (764 loc) · 26.7 KB
/
Copy pathFormatter.php
File metadata and controls
861 lines (764 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
<?php
namespace WP_CLI;
use cli\Colors;
use cli\Table;
use Mustangostang\Spyc;
use Traversable;
use WP_CLI;
/**
* Output one or more items in a given format (e.g. table, JSON).
*
* Supports built-in formats (table, json, csv, yaml, count, ids) and allows
* extensions to register custom formats via Formatter::add_format().
*
* @phpstan-type FormatterArgs array{format?: string, fields?: string|array<string>, field?: string, alignments?: array<string, int>, ascii?: bool, ...}
*
* @property-read string $format
* @property-read string[] $fields
* @property-read string|null $field
* @property-read array<string, int> $alignments
*/
class Formatter {
/**
* Maximum width for a table cell value.
* Values longer than this will be truncated to improve performance.
*
* @var int
*/
const MAX_CELL_WIDTH = 2048;
/**
* Custom format handlers registered by extensions.
*
* @var array<string, callable>
*/
private static $custom_formatters = [];
/**
* Options for custom format handlers.
*
* @var array<string, array{single_item?: bool}>
*/
private static $format_options = [];
/**
* Single-value format handlers for WP_CLI::print_value().
*
* @var array<string, callable>
*/
private static $single_value_formatters = [];
/**
* Whether the built-in format handlers have been registered yet.
*
* @var bool
*/
private static $builtin_formats_registered = false;
/**
* How the items should be output.
*
* @var array{format: string, fields: string[], field: string|null, alignments: array<string, int>}
*/
private $args;
/**
* Standard prefix for object fields.
*
* @var string|false
*/
private $prefix;
/**
* @param array<string, mixed> $assoc_args Output format arguments.
* @param-out array<string, mixed> $assoc_args
* @param array<string>|string|null $fields Fields to display of each item.
* @param string|false $prefix Check if fields have a standard prefix.
* False indicates empty prefix.
*/
public function __construct( &$assoc_args, $fields = null, $prefix = false ) {
$format_args = [
'format' => 'table',
'fields' => $fields,
'field' => null,
'alignments' => [],
];
foreach ( array_keys( $format_args ) as $key ) {
if ( isset( $assoc_args[ $key ] ) ) {
$format_args[ $key ] = $assoc_args[ $key ];
unset( $assoc_args[ $key ] );
}
}
if ( is_string( $format_args['fields'] ) ) {
$format_args['fields'] = array_map( 'trim', explode( ',', $format_args['fields'] ) );
} elseif ( ! is_array( $format_args['fields'] ) ) {
$format_args['fields'] = [];
}
/** @var array<int, string> $fields_array */
$fields_array = is_array( $format_args['fields'] ) ? $format_args['fields'] : [];
$format_args['fields'] = array_map(
function ( $v ) {
return (string) $v;
},
$fields_array
);
/** @var array{format: string, fields: array<string>, field: string|null, alignments: array<string, int>} $format_args */
$this->args = $format_args;
$this->prefix = $prefix;
self::register_builtin_formats();
}
/**
* Register a custom format handler.
*
* Allows extensions to add custom output formats. The handler receives an array
* of items (each item is an array of field => value pairs), an array of field
* names, the Formatter instance, and a key/value args array, and should output
* the formatted data directly.
*
* Built-in formats can be overridden by registering a handler with the same name.
*
* ## EXAMPLE
*
* // Register a custom XML format
* WP_CLI\Formatter::add_format( 'xml', function( $items, $fields, $formatter, $args ) {
* echo "<?xml version=\"1.0\"?>\n<items>\n";
* foreach ( $items as $item ) {
* echo " <item>\n";
* foreach ( $item as $key => $value ) {
* echo " <{$key}>" . htmlspecialchars( $value ) . "</{$key}>\n";
* }
* echo " </item>\n";
* }
* echo "</items>\n";
* });
*
* @param string $format_name Name of the format (e.g. 'xml', 'nagios').
* @param callable $handler Callback to handle formatting. Receives ($items, $fields, $formatter, $args) and should output directly.
* @param array{single_item?: bool} $options Optional metadata/options.
* @return void
*/
public static function add_format( $format_name, $handler, $options = [] ) {
if ( ! is_callable( $handler ) ) {
WP_CLI::error( 'Format handler must be callable.' );
}
// Make sure the built-ins are in place first, so that registering a
// handler for an existing format name always overrides the built-in one.
self::register_builtin_formats();
self::$custom_formatters[ $format_name ] = $handler;
self::$format_options[ $format_name ] = $options;
}
/**
* Register a custom single-value format handler for WP_CLI::print_value().
*
* Allows extensions to add custom output formats for single values. The handler
* receives a single value and should return the formatted string (without trailing newline).
*
* Built-in single-value formats can be overridden by registering a handler with the same name.
*
* ## EXAMPLE
*
* // Register a custom format for single values
* WP_CLI\Formatter::add_single_value_format( 'plaintext', function( $value ) {
* if ( is_array( $value ) || is_object( $value ) ) {
* return var_export( $value, true );
* }
* return (string) $value;
* });
*
* @param string $format_name Name of the format (e.g. 'json', 'yaml', 'plaintext').
* @param callable $handler Callback to handle formatting. Receives ($value) and should return formatted string.
* @return void
*/
public static function add_single_value_format( $format_name, $handler ) {
if ( ! is_callable( $handler ) ) {
WP_CLI::error( 'Single-value format handler must be callable.' );
}
// Make sure the built-ins are in place first, so that registering a
// handler for an existing format name always overrides the built-in one.
self::register_builtin_formats();
self::$single_value_formatters[ $format_name ] = $handler;
}
/**
* Format a single value using registered formatters.
*
* Used by WP_CLI::print_value() to format single values.
*
* @param mixed $value The value to format.
* @param string $format The format to use (e.g. 'json', 'yaml', 'var_export').
* @return string The formatted value (without trailing newline).
*/
public static function format_single_value( $value, $format ) {
self::register_builtin_formats();
if ( isset( self::$single_value_formatters[ $format ] ) ) {
return call_user_func( self::$single_value_formatters[ $format ], $value );
}
// Fallback to default behavior if format not registered
if ( is_array( $value ) || is_object( $value ) ) {
return var_export( $value, true );
}
// @phpstan-ignore cast.string
return (string) $value;
}
/**
* Register built-in format handlers.
*
* This method registers the default format handlers (table, json, csv, yaml, count, ids)
* using the add_format() API, allowing them to be overridden like custom formats.
*
* It is called during bootstrap, but is also self-triggered from every entry
* point into the registry, so that the Formatter keeps working when it is used
* without the WP-CLI bootstrap having run for this particular copy of the class
* (as a Composer library, in unit tests, or when a second copy of WP-CLI on the
* autoloader stack wins the class lookup).
*
* Repeat calls are a no-op, so registering built-ins never clobbers a handler
* that an extension registered for the same format name.
*
* @return void
*/
public static function register_builtin_formats() {
if ( self::$builtin_formats_registered ) {
return;
}
// Set before registering, as add_format() calls back into this method.
self::$builtin_formats_registered = true;
// Register 'table' format
self::add_format(
'table',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- $args required for API consistency
static function ( $items, $fields, $formatter = null, $args = [] ) {
$ascii_pre_colorized = $args['ascii_pre_colorized'] ?? false;
if ( $formatter instanceof Formatter ) {
$formatter->show_table( $items, $fields, $ascii_pre_colorized );
} else {
// Fallback if no formatter instance provided
$table = new Table();
$table->setHeaders( $fields );
foreach ( $items as $item ) {
$table->addRow( array_values( (array) $item ) );
}
foreach ( $table->getDisplayLines() as $line ) {
WP_CLI::line( $line );
}
}
}
);
// Register 'json' format
self::add_format(
'json',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- $formatter required for API consistency
static function ( $items, $fields, $formatter = null, $args = [] ) {
// For single-item display, output the item directly without array wrapper
if ( ! empty( $args['single_item'] ) && count( $items ) === 1 ) {
$item = reset( $items );
if ( defined( 'JSON_PARTIAL_OUTPUT_ON_ERROR' ) ) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.json_partial_output_on_errorFound
echo json_encode( $item, JSON_PARTIAL_OUTPUT_ON_ERROR );
} else {
echo json_encode( $item );
}
} elseif ( defined( 'JSON_PARTIAL_OUTPUT_ON_ERROR' ) ) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.json_partial_output_on_errorFound
echo json_encode( $items, JSON_PARTIAL_OUTPUT_ON_ERROR );
} else {
echo json_encode( $items );
}
}
);
// Register 'csv' format
self::add_format(
'csv',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- $formatter, $args required for API consistency
static function ( $items, $fields, $formatter = null, $args = [] ) {
Utils\write_csv( STDOUT, $items, $fields );
}
);
// Register 'yaml' format
self::add_format(
'yaml',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- $formatter required for API consistency
static function ( $items, $fields, $formatter = null, $args = [] ) {
// For single-item display, output the item directly without array wrapper
if ( ! empty( $args['single_item'] ) && count( $items ) === 1 ) {
$item = reset( $items );
echo Spyc::YAMLDump( $item, 2, 0 );
} else {
echo Spyc::YAMLDump( $items, 2, 0 );
}
}
);
// Register 'count' format
self::add_format(
'count',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- $fields, $formatter, $args required for API consistency
static function ( $items, $fields, $formatter = null, $args = [] ) {
echo count( $items );
},
[ 'single_item' => false ]
);
// Register 'ids' format
self::add_format(
'ids',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- $fields, $formatter, $args required for API consistency
static function ( $items, $fields, $formatter = null, $args = [] ) {
echo implode( ' ', $items );
},
[ 'single_item' => false ]
);
// Register single-value formats for WP_CLI::print_value()
// Register 'json' single-value format
self::add_single_value_format(
'json',
static function ( $value ) {
return json_encode( $value );
}
);
// Register 'yaml' single-value format
self::add_single_value_format(
'yaml',
static function ( $value ) {
/**
* @var array<mixed> $value
*/
return Spyc::YAMLDump( $value, 2, 0 );
}
);
$var_export_handler = static function ( $value ) {
if ( is_array( $value ) || is_object( $value ) ) {
return var_export( $value, true );
}
return (string) $value;
};
// Register 'var_export' single-value format (default for arrays/objects)
self::add_single_value_format( 'var_export', $var_export_handler );
// Register 'plaintext' single-value format
self::add_single_value_format( 'plaintext', $var_export_handler );
}
/**
* Get list of all available format names.
*
* Returns built-in formats plus any custom formats that have been registered.
* The list can be filtered via the 'formatter_available_formats' hook.
*
* ## EXAMPLE
*
* // Get all available formats
* $formats = WP_CLI\Formatter::get_available_formats();
* // Returns: [ 'table', 'json', 'csv', 'yaml', 'count', 'ids', ... custom formats ]
*
* // Filter to add a format to the list
* WP_CLI::add_hook( 'formatter_available_formats', function( $formats ) {
* $formats[] = 'my_custom_format';
* return $formats;
* });
*
* @return string[] Array of format names.
*/
public static function get_available_formats() {
self::register_builtin_formats();
$all_formats = array_keys( self::$custom_formatters );
/**
* Filter the list of available output formats.
*
* @param string[] $formats Array of format names.
*/
return WP_CLI::do_hook( 'formatter_available_formats', $all_formats );
}
/**
* Magic getter for arguments.
*
* @param string $key
* @return mixed
*/
public function __get( $key ) {
return $this->args[ $key ];
}
/**
* Display multiple items according to the output arguments.
*
* @param iterable<mixed> $items The items to display.
* @param bool|array<int, bool> $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `format()` if items in the table are pre-colorized. Default false.
* @return void
*/
public function display_items( $items, $ascii_pre_colorized = false ) {
if ( $this->args['field'] ) {
$this->show_single_field( $items, $this->args['field'] );
} else {
// Convert Traversable to array early to avoid consumption issues and enable validation
if ( $items instanceof Traversable ) {
$items = iterator_to_array( $items );
}
// Check if this is a custom formatter or a built-in format that needs field validation
// Skip validation for count/ids formats as they don't use fields
$skip_field_validation = in_array( $this->args['format'], [ 'count', 'ids' ], true );
$is_custom_format = isset( self::$custom_formatters[ $this->args['format'] ] );
$needs_field_validation = ! $skip_field_validation && ( in_array( $this->args['format'], [ 'csv', 'json', 'table', 'yaml' ], true ) || $is_custom_format );
if ( $needs_field_validation ) {
// Validate fields exist in at least one item and resolve field names with prefix support
if ( ! empty( $this->args['fields'] ) ) {
$this->validate_fields( $items );
}
}
if ( in_array( $this->args['format'], [ 'table', 'csv' ], true ) ) {
/** @var array<int, mixed> $transformed */
$transformed = array_map(
function ( $item ) {
return $this->transform_item_values_to_json( is_object( $item ) ? clone $item : $item );
},
(array) $items
);
$this->format( $transformed, $ascii_pre_colorized );
} else {
$this->format( $items, $ascii_pre_colorized );
}
}
}
/**
* Display a single item according to the output arguments.
*
* @param mixed $item
* @param bool|array<int, bool> $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_multiple_fields()` if the item in the table is pre-colorized. Default false.
* @return void
*/
public function display_item( $item, $ascii_pre_colorized = false ) {
if ( isset( $this->args['field'] ) ) {
$item = (object) $item;
$key = $this->find_item_key( $item, $this->args['field'], true );
if ( null === $key ) {
WP_CLI::warning( "Field not found in item: {$this->args['field']}." );
$value = null;
} else {
$value = $item->$key;
}
if ( in_array( $this->args['format'], [ 'table', 'csv' ], true ) && ( is_object( $value ) || is_array( $value ) ) ) {
$value = json_encode( $value );
}
WP_CLI::print_value(
$value,
[
'format' => $this->args['format'],
]
);
} else {
/**
* @var array<string, mixed> $item
*/
$this->show_multiple_fields( $item, $this->args['format'], $ascii_pre_colorized );
}
}
/**
* Format items according to arguments.
*
* @param iterable<mixed> $items Items.
* @param bool|array<int, bool> $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_table()` if items in the table are pre-colorized. Default false.
*/
private function format( $items, $ascii_pre_colorized = false ): void {
$fields = $this->args['fields'];
// Convert iterator to array if needed
if ( ! is_array( $items ) ) {
$items = iterator_to_array( $items );
}
// Check if a formatter is registered for this format
if ( isset( self::$custom_formatters[ $this->args['format'] ] ) ) {
// Special handling for 'ids' and 'count' formats - they work with raw items
if ( in_array( $this->args['format'], [ 'ids', 'count' ], true ) ) {
call_user_func( self::$custom_formatters[ $this->args['format'] ], $items, $fields, $this, [] );
return;
}
// Filter columns exactly once
$formatted_items = [];
foreach ( $items as $item ) {
if ( is_array( $item ) || is_object( $item ) ) {
$formatted_items[] = Utils\pick_fields( $item, $fields );
} else {
$formatted_items[] = $item;
}
}
// Truncate cell values exactly once for table/CSV output
if ( in_array( $this->args['format'], [ 'table', 'csv' ], true ) ) {
foreach ( $formatted_items as &$row ) {
if ( ! is_array( $row ) && ! is_object( $row ) ) {
continue;
}
foreach ( $row as $key => $value ) {
if ( is_string( $value ) && strlen( $value ) > self::MAX_CELL_WIDTH ) {
$row[ $key ] = substr( $value, 0, self::MAX_CELL_WIDTH ) . '...';
}
}
}
unset( $row );
}
$args = [ 'ascii_pre_colorized' => $ascii_pre_colorized ];
$handler = self::$custom_formatters[ $this->args['format'] ];
call_user_func( $handler, $formatted_items, $fields, $this, $args );
return;
}
// If no formatter is registered, show error
WP_CLI::error( 'Invalid format: ' . $this->args['format'] );
}
/**
* Show a single field from a list of items.
*
* @param iterable<mixed> $items An iterable of items to show fields from.
* @param string $field The field to show
*/
private function show_single_field( $items, $field ): void {
$key = null;
$values = [];
$field_found = false;
$item_count = 0;
foreach ( $items as $item ) {
++$item_count;
$item = (object) $item;
// Resolve the key on first item that has the field
if ( ! $field_found && null === $key ) {
$key = $this->find_item_key( $item, $field, true );
if ( null !== $key ) {
$field_found = true;
}
}
// Get value if key exists
$value = ( null !== $key && isset( $item->$key ) ) ? $item->$key : null;
if ( 'json' === $this->args['format'] ) {
$values[] = $value;
} else {
WP_CLI::print_value(
$value,
[
'format' => $this->args['format'],
]
);
}
}
if ( ! $field_found && $item_count > 0 ) {
WP_CLI::warning( "Field not found in any item: $field." );
}
if ( 'json' === $this->args['format'] ) {
echo json_encode( $values );
}
}
/**
* Validate that requested fields exist in at least one item.
* Warns if a field doesn't exist in any item.
* Also resolves field names to their actual keys (including prefixes).
*
* @param iterable<mixed> $items Items to validate
*/
private function validate_fields( $items ): void {
// Track which fields have been found and their resolved keys
$fields_to_find = array_flip( $this->args['fields'] );
$resolved_fields = [];
$fields_count = count( $fields_to_find );
$found_count = 0;
$item_count = 0;
// Iterate through items once and check all fields
foreach ( $items as $item ) {
++$item_count;
// Check each field that hasn't been found yet
foreach ( $fields_to_find as $field => $_ ) {
$key = $this->find_item_key( $item, $field, true );
if ( null !== $key ) {
// Store the resolved field name
$resolved_fields[ $field ] = $key;
// Mark this field as found
unset( $fields_to_find[ $field ] );
++$found_count;
// If all fields found, we can stop early
if ( $found_count === $fields_count ) {
break 2;
}
}
}
}
// Update the fields array with resolved field names
foreach ( $this->args['fields'] as &$field ) {
if ( isset( $resolved_fields[ $field ] ) ) {
$field = $resolved_fields[ $field ];
}
}
unset( $field ); // Break the reference to avoid issues with subsequent foreach loops
// Only warn about missing fields if there were items to check
if ( $item_count > 0 ) {
// Warn about any fields that weren't found in any item
foreach ( $fields_to_find as $missing_field => $_ ) {
WP_CLI::warning( "Field not found in any item: $missing_field." );
}
}
}
/**
* Check if an object property is accessible.
*
* @param object $item
* @param string $key
* @return bool
*/
private function is_object_property_accessible( $item, $key ): bool {
if ( ! is_object( $item ) ) {
return false;
}
if ( isset( $item->$key ) ) {
return true;
}
if ( property_exists( $item, $key ) ) {
return ( new \ReflectionProperty( $item, $key ) )->isPublic();
}
return false;
}
/**
* Find an object's key.
* If $prefix is set, a key with that prefix will be prioritized.
*
* @param mixed $item
* @param string $field
* @param bool $lenient If true, return null instead of erroring when field is not found.
* @return string|null
*/
private function find_item_key( $item, $field, $lenient = false ) {
foreach ( [ $field, $this->prefix . '_' . $field ] as $maybe_key ) {
if (
( is_object( $item ) && $this->is_object_property_accessible( $item, $maybe_key ) ) ||
( is_array( $item ) && array_key_exists( $maybe_key, $item ) )
) {
$key = $maybe_key;
break;
}
}
if ( ! isset( $key ) ) {
if ( $lenient ) {
return null;
}
WP_CLI::error( "Invalid field: $field." );
}
return $key;
}
/**
* Show multiple fields of an object.
*
* @param array<string, mixed>|object $data Data to display
* @param string $format Format to display the data in
* @param bool|array<int, bool> $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_table()` if the item in the table is pre-colorized. Default false.
*/
private function show_multiple_fields( $data, $format, $ascii_pre_colorized = false ): void {
$true_fields = [];
foreach ( $this->args['fields'] as $field ) {
$key = $this->find_item_key( $data, $field, true );
if ( null === $key ) {
// Field doesn't exist, show warning
WP_CLI::warning( "Field not found in item: $field." );
} else {
$true_fields[] = $key;
}
}
$ordered_data = [];
foreach ( $true_fields as $field ) {
$ordered_data[ $field ] = is_object( $data ) ? $data->$field : $data[ $field ];
}
// Check if a formatter is registered for this format
if ( isset( self::$custom_formatters[ $format ] ) ) {
// Verify the format supports single-item display
$options = self::$format_options[ $format ] ?? [];
if ( isset( $options['single_item'] ) && ! $options['single_item'] ) {
WP_CLI::error( 'Invalid format: ' . $format );
}
// For table and csv formats in single-item display, convert to rows format
if ( in_array( $format, [ 'table', 'csv' ], true ) ) {
$rows = $this->assoc_array_to_rows( $ordered_data );
$fields = [ 'Field', 'Value' ];
$args = [
'single_item' => true,
'ascii_pre_colorized' => $ascii_pre_colorized,
];
call_user_func( self::$custom_formatters[ $format ], $rows, $fields, $this, $args );
} else {
$args = [ 'single_item' => true ];
call_user_func( self::$custom_formatters[ $format ], [ $ordered_data ], array_keys( $ordered_data ), $this, $args );
}
return;
}
// If no formatter is registered, show error
WP_CLI::error( 'Invalid format: ' . $format );
}
/**
* Show items in a \cli\Table.
*
* @param iterable<int, array<string, mixed>|object> $items Items.
* @param array<int, string> $fields Fields.
* @param bool|array<int, bool> $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `Table::setAsciiPreColorized()` if items in the table are pre-colorized. Default false.
* @return void
*/
private function show_table( $items, $fields, $ascii_pre_colorized = false ) {
$table = new Table();
$enabled = WP_CLI::get_runner()->in_color();
if ( $enabled ) {
Colors::disable( true );
}
$table->setAsciiPreColorized( $ascii_pre_colorized );
$table->setHeaders( $fields );
$table->setAlignments(
$this->args['alignments']
);
foreach ( $items as $item ) {
$table->addRow( array_values( (array) $item ) );
}
foreach ( $table->getDisplayLines() as $line ) {
WP_CLI::line( $line );
}
if ( $enabled ) {
Colors::enable( true );
}
}
/**
* Format an associative array as a table.
*
* @param array<string, mixed> $fields Fields and values to format
* @return array<int, \stdClass>
*/
private function assoc_array_to_rows( $fields ) {
$rows = [];
foreach ( $fields as $field => $value ) {
if ( ! is_string( $value ) ) {
$value = json_encode( $value );
}
// Truncate large values for table/CSV output performance
if ( is_string( $value ) && strlen( $value ) > self::MAX_CELL_WIDTH ) {
$value = substr( $value, 0, self::MAX_CELL_WIDTH ) . '...';
}
$rows[] = (object) [
'Field' => $field,
'Value' => $value,
];
}
return $rows;
}
/**
* 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 mixed $item
* @return mixed
*/
public function transform_item_values_to_json( $item ) {
if ( ! is_object( $item ) && ! is_array( $item ) ) {
return $item;
}
foreach ( $this->args['fields'] as $field ) {
$true_field = $this->find_item_key( $item, $field, true );
if ( null === $true_field ) {
// Field doesn't exist in this item, skip it
continue;
}
$value = is_object( $item ) ? $item->$true_field : $item[ $true_field ];
if ( is_array( $value ) || is_object( $value ) ) {
if ( is_object( $item ) ) {
$item->$true_field = json_encode( $value );
} 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;
}
}