Completed
Push — master ( 240a22...a33d5f )
by Arkadiusz
02:53
created

CsvDataset::getColumnNames()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Dataset;
6
7
use Phpml\Exception\FileException;
8
9
class CsvDataset extends ArrayDataset
10
{
11
    /**
12
     * @var array
13
     */
14
    protected $columnNames;
15
16
    /**
17
     * @param string $filepath
18
     * @param int    $features
19
     * @param bool   $headingRow
20
     *
21
     * @throws FileException
22
     */
23
    public function __construct(string $filepath, int $features, bool $headingRow = true)
24
    {
25
        if (!file_exists($filepath)) {
26
            throw FileException::missingFile(basename($filepath));
27
        }
28
29
        if (false === $handle = fopen($filepath, 'rb')) {
30
            throw FileException::cantOpenFile(basename($filepath));
31
        }
32
33
        if ($headingRow) {
34
            $data = fgetcsv($handle, 1000, ',');
35
            $this->columnNames = array_slice($data, 0, $features);
36
        } else {
37
            $this->columnNames = range(0, $features - 1);
38
        }
39
40
        while (($data = fgetcsv($handle, 1000, ',')) !== false) {
41
            $this->samples[] = array_slice($data, 0, $features);
42
            $this->targets[] = $data[$features];
43
        }
44
        fclose($handle);
45
    }
46
47
    /**
48
     * @return array
49
     */
50
    public function getColumnNames()
51
    {
52
        return $this->columnNames;
53
    }
54
}
55