Completed
Pull Request — master (#45)
by Greg
02:00
created

WordWrapper::longestWordLength()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
namespace Consolidation\OutputFormatters\Transformations;
3
4
use Symfony\Component\Console\Helper\TableStyle;
5
6
class WordWrapper
7
{
8
    protected $width;
9
    protected $minimumWidths = [];
10
11
    // For now, hardcode these to match what the Symfony Table helper does.
12
    // Note that these might actually need to be adjusted depending on the
13
    // table style.
14
    protected $extraPaddingAtBeginningOfLine = 0;
15
    protected $extraPaddingAtEndOfLine = 0;
16
    protected $paddingInEachCell = 3;
17
18
    public function __construct($width)
19
    {
20
        $this->width = $width;
21
    }
22
23
    /**
24
     * Calculate our padding widths from the specified table style.
25
     * @param TableStyle $style
26
     */
27
    public function setPaddingFromStyle(TableStyle $style)
28
    {
29
        $verticalBorderLen = strlen(sprintf($style->getBorderFormat(), $style->getVerticalBorderChar()));
30
        $paddingLen = strlen($style->getPaddingChar());
31
32
        $this->extraPaddingAtBeginningOfLine = 0;
33
        $this->extraPaddingAtEndOfLine = $verticalBorderLen;
34
        $this->paddingInEachCell = $verticalBorderLen + $paddingLen + 1;
35
    }
36
37
    /**
38
     * If columns have minimum widths, then set them here.
39
     * @param array $minimumWidths
40
     */
41
    public function setMinimumWidths($minimumWidths)
42
    {
43
        $this->minimumWidths = $minimumWidths;
44
    }
45
46
    /**
47
     * Wrap the cells in each part of the provided data table
48
     * @param array $rows
49
     * @return array
50
     */
51
    public function wrap($rows, $widths = [])
52
    {
53
        // If the width was not set, then disable wordwrap.
54
        if (!$this->width) {
55
            return $rows;
56
        }
57
58
        // Calculate the column widths to use based on the content.
59
        $auto_widths = $this->columnAutowidth($rows, $widths);
60
61
        // Do wordwrap on all cells.
62
        $newrows = array();
63
        foreach ($rows as $rowkey => $row) {
64
            foreach ($row as $colkey => $cell) {
65
                $newrows[$rowkey][$colkey] = $this->wrapCell($cell, $auto_widths[$colkey]);
66
            }
67
        }
68
69
        return $newrows;
70
    }
71
72
    /**
73
     * Wrap one cell.  Guard against modifying non-strings and
74
     * then call through to wordwrap().
75
     *
76
     * @param mixed $cell
77
     * @param string $cellWidth
78
     * @return mixed
79
     */
80
    protected function wrapCell($cell, $cellWidth)
81
    {
82
        if (!is_string($cell)) {
83
            return $cell;
84
        }
85
        return wordwrap($cell, $cellWidth, "\n", true);
86
    }
87
88
    /**
89
     * Determine the best fit for column widths. Ported from Drush.
90
     *
91
     * @param array $rows The rows to use for calculations.
92
     * @param array $widths Manually specified widths of each column
93
     *   (in characters) - these will be left as is.
94
     */
95
    protected function columnAutowidth($rows, $widths)
96
    {
97
        $auto_widths = $widths;
98
99
        // First we determine the distribution of row lengths in each column.
100
        // This is an array of descending character length keys (i.e. starting at
101
        // the rightmost character column), with the value indicating the number
102
        // of rows where that character column is present.
103
        $col_dist = [];
104
        // We will also calculate the longest word in each column
105
        $max_word_lens = [];
106
        foreach ($rows as $rowkey => $row) {
107
            foreach ($row as $col_id => $cell) {
108
                $longest_word_len = static::longestWordLength($cell);
109
                if ((!isset($max_word_lens[$col_id]) || ($max_word_lens[$col_id] < $longest_word_len))) {
110
                    $max_word_lens[$col_id] = $longest_word_len;
111
                }
112
                if (empty($widths[$col_id])) {
113
                    $length = strlen($cell);
114
                    if ($length == 0) {
115
                        $col_dist[$col_id][0] = 0;
116
                    }
117
                    while ($length > 0) {
118
                        if (!isset($col_dist[$col_id][$length])) {
119
                            $col_dist[$col_id][$length] = 0;
120
                        }
121
                        $col_dist[$col_id][$length]++;
122
                        $length--;
123
                    }
124
                }
125
            }
126
        }
127
128
        foreach ($col_dist as $col_id => $count) {
129
            // Sort the distribution in decending key order.
130
            krsort($col_dist[$col_id]);
131
            // Initially we set all columns to their "ideal" longest width
132
            // - i.e. the width of their longest column.
133
            $auto_widths[$col_id] = max(array_keys($col_dist[$col_id]));
134
        }
135
136
        // We determine what width we have available to use, and what width the
137
        // above "ideal" columns take up.
138
        $available_width = $this->width - ($this->extraPaddingAtBeginningOfLine + $this->extraPaddingAtEndOfLine + (count($auto_widths) * $this->paddingInEachCell));
139
        $auto_width_current = array_sum($auto_widths);
140
141
        // If we cannot fit into the minimum width anyway, then just return
142
        // the max word length of each column as the 'ideal'
143
        $minimumIdealLength = array_sum($this->minimumWidths);
144
        if ($minimumIdealLength && ($available_width < $minimumIdealLength)) {
145
            return $max_word_lens;
146
        }
147
148
        // If we need to reduce a column so that we can fit the space we use this
149
        // loop to figure out which column will cause the "least wrapping",
150
        // (relative to the other columns) and reduce the width of that column.
151
        while ($auto_width_current > $available_width) {
152
153
            list($column, $count, $width) = $this->selectColumnToReduce($col_dist, $auto_widths, $max_word_lens);
0 ignored issues
show
Unused Code introduced by
The assignment to $count is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
154
155
            if (!$column || $width <= 1) {
156
                // If we have reached a width of 1 then give up, so wordwrap can still progress.
157
                break;
158
            }
159
            // Reduce the width of the selected column.
160
            $auto_widths[$column]--;
161
            // Reduce our overall table width counter.
162
            $auto_width_current--;
163
            // Remove the corresponding data from the disctribution, so next time
164
            // around we use the data for the row to the left.
165
            unset($col_dist[$column][$width]);
166
        }
167
        return $auto_widths;
168
    }
169
170
    protected function selectColumnToReduce($col_dist, $auto_widths, $max_word_lens)
171
    {
172
        $column = false;
173
        $count = 0;
174
        $width = 0;
175
        foreach ($col_dist as $col_id => $counts) {
176
            // Of the columns whose length is still > than the the lenght
177
            // of their maximum word length
178
            if ($auto_widths[$col_id] > $max_word_lens[$col_id]) {
179 View Code Duplication
                if ($this->shouldSelectThisColumn($count, $counts, $width)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
                    $column = $col_id;
181
                    $count = current($counts);
182
                    $width = key($counts);
183
                }
184
            }
185
        }
186
        if ($column !== false) {
187
            return [$column, $count, $width];
188
        }
189
        foreach ($col_dist as $col_id => $counts) {
190
            if (empty($this->minimumWidths) || ($auto_widths[$col_id] > $this->minimumWidths[$col_id])) {
191 View Code Duplication
                if ($this->shouldSelectThisColumn($count, $counts, $width)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
192
                    $column = $col_id;
193
                    $count = current($counts);
194
                    $width = key($counts);
195
                }
196
            }
197
        }
198
        return [$column, $count, $width];
199
    }
200
201
    protected function shouldSelectThisColumn($count, $counts, $width)
202
    {
203
        return
204
            // If we are just starting out, select the first column.
205
            ($count == 0) ||
206
            // OR: if this column would cause less wrapping than the currently
207
            // selected column, then select it.
208
            (current($counts) < $count) ||
209
            // OR: if this column would cause the same amount of wrapping, but is
210
            // longer, then we choose to wrap the longer column (proportionally
211
            // less wrapping, and helps avoid triple line wraps).
212
            (current($counts) == $count && key($counts) > $width);
213
    }
214
215
    /**
216
     * Remove from consideration any short column (max word length less than
217
     * 1/4th the available width, and current length <= max word length) from
218
     * consideration this time through the loop.  Once all columns are in this
219
     * state, then return all again.
220
     *
221
     * @param array $col_dist
222
     * @param array $auto_widths
223
     * @param array $max_word_lens
224
     * @param int $available_width
225
     * @return array
226
     */
227
    protected static function removeSmallColumns($col_dist, $auto_widths, $max_word_lens, $available_width)
0 ignored issues
show
Unused Code introduced by
The parameter $available_width is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
228
    {
229
        $col_dist_subset = [];
230
231
        // Start by removing columns whose length is <= their max word length
232
        foreach ($col_dist as $col_id => $counts) {
233
            $length = $auto_widths[$col_id];
234
            $max_word_len = $max_word_lens[$col_id];
235
            if ($length > $max_word_len) {
236
                $col_dist_subset[$col_id] = $counts;
237
            }
238
        }
239
        if (!empty($col_dist_subset)) {
240
            return $col_dist_subset;
241
        }
242
        // Next, remove columns whose max word length is smallest -- or
243
        // at least smaller than the average max length.
244
        $average_of_max_lens = static::average($max_word_lens);
0 ignored issues
show
Bug introduced by
The method average() does not seem to exist on object<Consolidation\Out...formations\WordWrapper>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
245
        foreach ($col_dist as $col_id => $counts) {
246
            if ($max_word_lens[$col_id] >= $average_of_max_lens) {
247
                $col_dist_subset[$col_id] = $counts;
248
            }
249
        }
250
        if (!empty($col_dist_subset)) {
251
            return $col_dist_subset;
252
        }
253
        return $col_dist;
254
    }
255
256
    /**
257
     * Return the length of the longest word in the string.
258
     * @param string $str
259
     * @return int
260
     */
261
    protected static function longestWordLength($str)
262
    {
263
        $words = preg_split('/[ -]/', $str);
264
        $lengths = array_map(function ($s) { return strlen($s); }, $words);
265
        return max($lengths);
266
    }
267
}
268