Skip to content

Commit 867bc04

Browse files
Copilotswissspidy
andcommitted
Refactor: Use class constant for valid wrapping modes and optimize width tracking
- Define VALID_WRAPPING_MODES as a private class constant for better maintainability - Optimize wordWrap() by tracking width incrementally instead of recalculating Colors::width() on every iteration - Addresses code review feedback from @swissspidy Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent a28b281 commit 867bc04

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

‎lib/cli/table/Ascii.php‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@
1919
* The ASCII renderer renders tables with ASCII borders.
2020
*/
2121
class Ascii extends Renderer {
22+
/**
23+
* Valid wrapping modes.
24+
*/
25+
private const VALID_WRAPPING_MODES = array( 'wrap', 'word-wrap', 'truncate' );
26+
2227
protected $_characters = array(
2328
'corner' => '+',
2429
'line' => '-',
@@ -104,9 +109,8 @@ public function setConstraintWidth( $constraintWidth ) {
104109
* 'word-wrap' (wrap at word boundaries), or 'truncate' (truncate with ellipsis).
105110
*/
106111
public function setWrappingMode( $mode ) {
107-
$valid_modes = array( 'wrap', 'word-wrap', 'truncate' );
108-
if ( ! in_array( $mode, $valid_modes, true ) ) {
109-
throw new \InvalidArgumentException( "Invalid wrapping mode '$mode'. Must be one of: " . implode( ', ', $valid_modes ) );
112+
if ( ! in_array( $mode, self::VALID_WRAPPING_MODES, true ) ) {
113+
throw new \InvalidArgumentException( "Invalid wrapping mode '$mode'. Must be one of: " . implode( ', ', self::VALID_WRAPPING_MODES ) );
110114
}
111115
$this->_wrapping_mode = $mode;
112116
}
@@ -312,13 +316,13 @@ protected function wrapText( $text, $width, $encoding, $is_precolorized ) {
312316
protected function wordWrap( $text, $width, $encoding, $is_precolorized ) {
313317
$wrapped_lines = array();
314318
$current_line = '';
319+
$current_line_width = 0;
315320

316321
// Split by spaces and hyphens while keeping the delimiters
317322
$words = preg_split( '/(\s+|-)/u', $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
318323

319324
foreach ( $words as $word ) {
320325
$word_width = Colors::width( $word, $is_precolorized, $encoding );
321-
$current_line_width = Colors::width( $current_line, $is_precolorized, $encoding );
322326

323327
// If this word alone exceeds the width, we need to split it
324328
if ( $word_width > $width ) {
@@ -344,9 +348,11 @@ protected function wordWrap( $text, $width, $encoding, $is_precolorized ) {
344348
// Start a new line
345349
$wrapped_lines[] = $current_line;
346350
$current_line = $word;
351+
$current_line_width = $word_width;
347352
} else {
348353
// Add to current line
349354
$current_line .= $word;
355+
$current_line_width += $word_width;
350356
}
351357
}
352358

0 commit comments

Comments
 (0)