Completed
Push — master ( 22d7bb...dd90a8 )
by Ori
03:00
created

TabularDataStream::save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace frictionlessdata\datapackage\DataStreams;
4
5
use frictionlessdata\datapackage\Exceptions\DataStreamValidationException;
6
use frictionlessdata\datapackage\Exceptions\DataStreamOpenException;
7
use frictionlessdata\tableschema\DataSources\CsvDataSource;
8
use frictionlessdata\tableschema\Schema;
9
use frictionlessdata\tableschema\Table;
10
use frictionlessdata\tableschema\Exceptions\FieldValidationException;
11
use frictionlessdata\tableschema\Exceptions\DataSourceException;
12
13
class TabularDataStream extends BaseDataStream
14
{
15
    public $table;
16
    public $schema;
17
18
    public function __construct($dataSource, $dataSourceOptions = null)
19
    {
20
        parent::__construct($dataSource, $dataSourceOptions);
21
        $schema = $this->dataSourceOptions;
22
        if (empty($schema)) {
23
            throw new \Exception('schema is required for tabular data stream');
24
        } else {
25
            try {
26
                $this->schema = new Schema($schema);
27
                $this->table = new Table($this->getDataSourceObject(), $this->schema);
28
            } catch (\Exception $e) {
29
                throw new DataStreamOpenException('Failed to open tabular data source '.json_encode($dataSource).': '.json_encode($e->getMessage()));
30
            }
31
        }
32
    }
33
34
    protected function getDataSourceObject()
35
    {
36
        return new CsvDataSource($this->dataSource);
37
    }
38
39
    public function rewind()
40
    {
41
        $this->table->rewind();
42
    }
43
44
    public function save($filename)
45
    {
46
        $this->table->save($filename);
47
    }
48
49
    /**
50
     * @return array
51
     *
52
     * @throws DataStreamValidationException
53
     */
54
    public function current()
55
    {
56
        try {
57
            return $this->table->current();
58
        } catch (DataSourceException $e) {
59
            throw new DataStreamValidationException($e->getMessage());
60
        } catch (FieldValidationException $e) {
61
            throw new DataStreamValidationException($e->getMessage());
62
        }
63
    }
64
65
    public function key()
66
    {
67
        return $this->table->key();
68
    }
69
70
    public function next()
71
    {
72
        $this->table->next();
73
    }
74
75
    public function valid()
76
    {
77
        return $this->table->valid();
78
    }
79
}
80