Completed
Pull Request — master (#120)
by
unknown
02:42
created

TableNode::fromList()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 2
cts 2
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Behat Gherkin.
5
 * (c) Konstantin Kudryashov <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Behat\Gherkin\Node;
12
13
use ArrayIterator;
14
use Behat\Gherkin\Exception\NodeException;
15
use Iterator;
16
use IteratorAggregate;
17
18
/**
19
 * Represents Gherkin Table argument.
20
 *
21
 * @author Konstantin Kudryashov <[email protected]>
22
 */
23
class TableNode implements ArgumentInterface, IteratorAggregate
24
{
25
    /**
26
     * @var array
27
     */
28
    private $table;
29
    /**
30
     * @var integer
31
     */
32
    private $maxLineLength = array();
33
34
    /**
35
     * Initializes table.
36
     *
37
     * @param array $table Table in form of [$rowLineNumber => [$val1, $val2, $val3]]
38
     * 
39
     * @throws NodeException If the number of columns is not the same in each row
40
     */
41 51
    public function __construct(array $table)
42
    {
43 51
        $this->table = $table;
44 51
        $columnCount = null;
45
46 51
        foreach ($this->getRows() as $row) {
47 38
            if ($columnCount === null) {
48 38
                $columnCount = count($row);
49 38
            }
50
51 38
            if (count($row) !== $columnCount) {
52 1
                throw new NodeException('Table does not have same number of columns in every row.');
53
            }
54
55 38
            foreach ($row as $column => $string) {
56 38
                if (!isset($this->maxLineLength[$column])) {
57 38
                    $this->maxLineLength[$column] = 0;
58 38
                }
59
60 38
                $this->maxLineLength[$column] = max($this->maxLineLength[$column], mb_strlen($string, 'utf8'));
61 38
            }
62 51
        }
63 50
    }
64
65
    /**
66
     * Creates a table from a given list.
67
     *
68
     * @param array $list One-dimensional array
69
     *
70
     * @return TableNode
71
     *
72
     * @throws NodeException If the given list is not a one-dimensional array
73
     */
74
    public static function fromList(array $list)
75
    {
76
        if (count($list) !== count($list, COUNT_RECURSIVE)) {
77
            throw new NodeException('List is not a one-dimensional array.');
78
        }
79
80 4
        array_walk($list, function (&$item) {
81
            $item = [$item];
82 4
        });
83
        return new self($list);
84
    }
85
86
    /**
87
     * Returns node type.
88
     *
89
     * @return string
90 19
     */
91
    public function getNodeType()
92 19
    {
93 19
        return 'Table';
94
    }
95 19
96 19
    /**
97 11
     * Returns table hash, formed by columns (ColumnsHash).
98 19
     *
99
     * @return array
100 19
     */
101
    public function getHash()
102
    {
103
        return $this->getColumnsHash();
104
    }
105
106
    /**
107
     * Returns table hash, formed by columns.
108 2
     *
109
     * @return array
110 2
     */
111
    public function getColumnsHash()
112 2
    {
113 2
        $rows = $this->getRows();
114 2
        $keys = array_shift($rows);
115
116 2
        $hash = array();
117
        foreach ($rows as $row) {
118
            $hash[] = array_combine($keys, $row);
119
        }
120
121
        return $hash;
122
    }
123
124
    /**
125 4
     * Returns table hash, formed by rows.
126
     *
127 4
     * @return array
128
     */
129
    public function getRowsHash()
130
    {
131
        $hash = array();
132
133
        foreach ($this->getRows() as $row) {
134
            $hash[array_shift($row)] = (1 == count($row)) ? $row[0] : $row;
135 51
        }
136
137 51
        return $hash;
138
    }
139
140
    /**
141
     * Returns numerated table lines.
142
     * Line numbers are keys, lines are values.
143
     *
144
     * @return array
145 5
     */
146
    public function getTable()
147 5
    {
148
        return $this->table;
149
    }
150
151
    /**
152
     * Returns table rows.
153
     *
154
     * @return array
155
     */
156
    public function getRows()
157
    {
158
        return array_values($this->table);
159 8
    }
160
161 8
    /**
162
     * Returns table definition lines.
163 8
     *
164
     * @return array
165
     */
166
    public function getLines()
167 8
    {
168
        return array_keys($this->table);
169
    }
170
171
    /**
172
     * Returns specific row in a table.
173
     *
174
     * @param integer $index Row number
175
     *
176
     * @return array
177
     *
178
     * @throws NodeException If row with specified index does not exist
179 1
     */
180 View Code Duplication
    public function getRow($index)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
181 1
    {
182
        $rows = $this->getRows();
183
184
        if (!isset($rows[$index])) {
185 1
            throw new NodeException(sprintf('Rows #%d does not exist in table.', $index));
186 1
        }
187
188 1
        return $rows[$index];
189 1
    }
190 1
191
    /**
192 1
     * Returns specific column in a table.
193
     *
194
     * @param integer $index Column number
195
     *
196
     * @return array
197
     *
198
     * @throws NodeException If column with specified index does not exist
199
     */
200
    public function getColumn($index)
201
    {
202
        if ($index >= count($this->getRow(0))) {
203
            throw new NodeException(sprintf('Column #%d does not exist in table.', $index));
204 4
        }
205
206 4
        $rows = $this->getRows();
207
        $column = array();
208 4
209
        foreach ($rows as $row) {
210
            $column[] = $row[$index];
211
        }
212 4
213
        return $column;
214
    }
215
216
    /**
217
     * Returns line number at which specific row was defined.
218
     *
219
     * @param integer $index
220
     *
221
     * @return integer
222 5
     *
223
     * @throws NodeException If row with specified index does not exist
224 5
     */
225 5 View Code Duplication
    public function getRowLine($index)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
226 5
    {
227 5
        $lines = array_keys($this->table);
228
229 5
        if (!isset($lines[$index])) {
230
            throw new NodeException(sprintf('Rows #%d does not exist in table.', $index));
231
        }
232
233
        return $lines[$index];
234
    }
235
236
    /**
237
     * Converts row into delimited string.
238
     *
239
     * @param integer $rowNum Row number
240
     *
241
     * @return string
242
     */
243
    public function getRowAsString($rowNum)
244
    {
245
        $values = array();
246
        foreach ($this->getRow($rowNum) as $column => $value) {
247
            $values[] = $this->padRight(' ' . $value . ' ', $this->maxLineLength[$column] + 2);
248
        }
249
250
        return sprintf('|%s|', implode('|', $values));
251
    }
252
253
    /**
254
     * Converts row into delimited string.
255
     *
256
     * @param integer  $rowNum  Row number
257 2
     * @param callable $wrapper Wrapper function
258
     *
259 2
     * @return string
260 2
     */
261 2
    public function getRowAsStringWithWrappedValues($rowNum, $wrapper)
262 2
    {
263
        $values = array();
264 2
        foreach ($this->getRow($rowNum) as $column => $value) {
265
            $value = $this->padRight(' ' . $value . ' ', $this->maxLineLength[$column] + 2);
266
267
            $values[] = call_user_func($wrapper, $value, $column);
268
        }
269
270
        return sprintf('|%s|', implode('|', $values));
271
    }
272
273
    /**
274
     * Converts entire table into string
275
     *
276
     * @return string
277
     */
278
    public function getTableAsString()
279
    {
280
        $lines = array();
281
        for ($i = 0; $i < count($this->getRows()); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
282
            $lines[] = $this->getRowAsString($i);
283
        }
284
285
        return implode("\n", $lines);
286
    }
287
288
    /**
289
     * Returns line number at which table was started.
290
     *
291
     * @return integer
292 1
     */
293
    public function getLine()
294 1
    {
295
        return $this->getRowLine(0);
296
    }
297
298
    /**
299
     * Converts table into string
300
     *
301
     * @return string
302
     */
303
    public function __toString()
304
    {
305 5
        return $this->getTableAsString();
306
    }
307 5
308 5
    /**
309 5
     * Retrieves a hash iterator.
310
     *
311 5
     * @return Iterator
312
     */
313
    public function getIterator()
314
    {
315
        return new ArrayIterator($this->getHash());
316
    }
317
318
    /**
319
     * Pads string right.
320
     *
321
     * @param string  $text   Text to pad
322
     * @param integer $length Length
323
     *
324
     * @return string
325
     */
326
    protected function padRight($text, $length)
327
    {
328
        while ($length > mb_strlen($text, 'utf8')) {
329
            $text = $text . ' ';
330
        }
331
332
        return $text;
333
    }
334
}
335