Completed
Pull Request — master (#42)
by Sam
02:33
created

CsvTableReader::getIterator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
1
<?php
2
3
namespace SilverStripe\SsPak\DataExtractor;
4
5
class CsvTableReader implements TableReader
6
{
7
8
	private $filename;
9
	private $handle;
10
	private $columns;
11
12
	function __construct($filename) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
13
		$this->filename = $filename;
14
	}
15
16
	function getColumns() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
17
		if (!$this->columns) {
18
			$this->initColumns();
19
		}
20
		return $this->columns;
21
	}
22
23
	function getIterator() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
24
		$this->columns = null;
25
		$this->initColumns();
26
27
		while(($row = $this->getRow()) !== false) {
28
			yield $this->mapToColumns($row);
29
		}
30
31
		$this->close();
32
	}
33
34
	private function mapToColumns($row) {
35
		$record = [];
36
		foreach($row as $i => $value)
37
		{
38
			if(isset($this->columns[$i])) {
39
				$record[$this->columns[$i]] = $value;
40
			} else {
41
				throw new \LogicException("Row contains invalid column #$i\n" . var_export($row, true));
42
			}
43
		}
44
		return $record;
45
	}
46
47
	private function initColumns() {
48
		$this->open();
49
		$this->columns = $this->getRow();
50
	}
51
52
	private function getRow() {
53
		return fgetcsv($this->handle);
54
	}
55
56
	private function open() {
57
		if ($this->handle) {
58
			fclose($this->handle);
59
			$this->handle = null;
60
		}
61
		$this->handle = fopen($this->filename, 'r');
62
	}
63
64
	private function close() {
65
		if ($this->handle) {
66
			fclose($this->handle);
67
			$this->handle = null;
68
		}
69
	}
70
}
71