Completed
Pull Request — master (#112)
by Christophe
02:45
created

TableNode::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
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
     * Returns node type.
67
     *
68
     * @return string
69
     */
70
    public function getNodeType()
71
    {
72
        return 'Table';
73
    }
74
75
    /**
76
     * Returns table hash, formed by columns (ColumnsHash).
77
     *
78
     * @return array
79
     */
80 4
    public function getHash()
81
    {
82 4
        return $this->getColumnsHash();
83
    }
84
85
    /**
86
     * Returns table hash, formed by columns.
87
     *
88
     * @return array
89
     */
90 19
    public function getColumnsHash()
91
    {
92 19
        $rows = $this->getRows();
93 19
        $keys = array_shift($rows);
94
95 19
        $hash = array();
96 19
        foreach ($rows as $row) {
97 11
            $hash[] = array_combine($keys, $row);
98 19
        }
99
100 19
        return $hash;
101
    }
102
103
    /**
104
     * Returns table hash, formed by rows.
105
     *
106
     * @return array
107
     */
108 2
    public function getRowsHash()
109
    {
110 2
        $hash = array();
111
112 2
        foreach ($this->getRows() as $row) {
113 2
            $hash[array_shift($row)] = (1 == count($row)) ? $row[0] : $row;
114 2
        }
115
116 2
        return $hash;
117
    }
118
119
    /**
120
     * Returns numerated table lines.
121
     * Line numbers are keys, lines are values.
122
     *
123
     * @return array
124
     */
125 4
    public function getTable()
126
    {
127 4
        return $this->table;
128
    }
129
130
    /**
131
     * Returns table rows.
132
     *
133
     * @return array
134
     */
135 51
    public function getRows()
136
    {
137 51
        return array_values($this->table);
138
    }
139
140
    /**
141
     * Returns table definition lines.
142
     *
143
     * @return array
144
     */
145 5
    public function getLines()
146
    {
147 5
        return array_keys($this->table);
148
    }
149
150
    /**
151
     * Returns specific row in a table.
152
     *
153
     * @param integer $index Row number
154
     *
155
     * @return array
156
     *
157
     * @throws NodeException If row with specified index does not exist
158
     */
159 8 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...
160
    {
161 8
        $rows = $this->getRows();
162
163 8
        if (!isset($rows[$index])) {
164
            throw new NodeException(sprintf('Rows #%d does not exist in table.', $index));
165
        }
166
167 8
        return $rows[$index];
168
    }
169
170
    /**
171
     * Returns specific column in a table.
172
     *
173
     * @param integer $index Column number
174
     *
175
     * @return array
176
     *
177
     * @throws NodeException If column with specified index does not exist
178
     */
179 1
    public function getColumn($index)
180
    {
181 1
        if ($index >= count($this->getRow(0))) {
182
            throw new NodeException(sprintf('Column #%d does not exist in table.', $index));
183
        }
184
185 1
        $rows = $this->getRows();
186 1
        $column = array();
187
188 1
        foreach ($rows as $row) {
189 1
            $column[] = $row[$index];
190 1
        }
191
192 1
        return $column;
193
    }
194
195
    /**
196
     * Returns line number at which specific row was defined.
197
     *
198
     * @param integer $index
199
     *
200
     * @return integer
201
     *
202
     * @throws NodeException If row with specified index does not exist
203
     */
204 4 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...
205
    {
206 4
        $lines = array_keys($this->table);
207
208 4
        if (!isset($lines[$index])) {
209
            throw new NodeException(sprintf('Rows #%d does not exist in table.', $index));
210
        }
211
212 4
        return $lines[$index];
213
    }
214
215
    /**
216
     * Converts row into delimited string.
217
     *
218
     * @param integer $rowNum Row number
219
     *
220
     * @return string
221
     */
222 5
    public function getRowAsString($rowNum)
223
    {
224 5
        $values = array();
225 5
        foreach ($this->getRow($rowNum) as $column => $value) {
226 5
            $values[] = $this->padRight(' ' . $value . ' ', $this->maxLineLength[$column] + 2);
227 5
        }
228
229 5
        return sprintf('|%s|', implode('|', $values));
230
    }
231
232
    /**
233
     * Converts row into delimited string.
234
     *
235
     * @param integer  $rowNum  Row number
236
     * @param callable $wrapper Wrapper function
237
     *
238
     * @return string
239
     */
240
    public function getRowAsStringWithWrappedValues($rowNum, $wrapper)
241
    {
242
        $values = array();
243
        foreach ($this->getRow($rowNum) as $column => $value) {
244
            $value = $this->padRight(' ' . $value . ' ', $this->maxLineLength[$column] + 2);
245
246
            $values[] = call_user_func($wrapper, $value, $column);
247
        }
248
249
        return sprintf('|%s|', implode('|', $values));
250
    }
251
252
    /**
253
     * Converts entire table into string
254
     *
255
     * @return string
256
     */
257 2
    public function getTableAsString()
258
    {
259 2
        $lines = array();
260 2
        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...
261 2
            $lines[] = $this->getRowAsString($i);
262 2
        }
263
264 2
        return implode("\n", $lines);
265
    }
266
267
    /**
268
     * Returns line number at which table was started.
269
     *
270
     * @return integer
271
     */
272
    public function getLine()
273
    {
274
        return $this->getRowLine(0);
275
    }
276
277
    /**
278
     * Converts table into string
279
     *
280
     * @return string
281
     */
282
    public function __toString()
283
    {
284
        return $this->getTableAsString();
285
    }
286
287
    /**
288
     * Retrieves a hash iterator.
289
     *
290
     * @return Iterator
291
     */
292 1
    public function getIterator()
293
    {
294 1
        return new ArrayIterator($this->getHash());
295
    }
296
297
    /**
298
     * Pads string right.
299
     *
300
     * @param string  $text   Text to pad
301
     * @param integer $length Length
302
     *
303
     * @return string
304
     */
305 5
    protected function padRight($text, $length)
306
    {
307 5
        while ($length > mb_strlen($text, 'utf8')) {
308 5
            $text = $text . ' ';
309 5
        }
310
311 5
        return $text;
312
    }
313
}
314