Completed
Push — master ( 2215c7...0db5fc )
by Damian
10s
created

src/DataExtractor/CsvTableReader.php (3 issues)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
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
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
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