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

TabularDataStream   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 67
rs 10
c 0
b 0
f 0
wmc 12
lcom 2
cbo 6

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 3
A getDataSourceObject() 0 4 1
A rewind() 0 4 1
A save() 0 4 1
A current() 0 10 3
A key() 0 4 1
A next() 0 4 1
A valid() 0 4 1
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