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

DefaultDataStream   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 63
rs 10
c 0
b 0
f 0
wmc 10
lcom 2
cbo 2

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A __destruct() 0 4 1
A rewind() 0 9 2
A save() 0 6 1
A current() 0 4 1
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\DataStreamOpenException;
6
7
/**
8
 * streams the raw data without processing - used for default data package resources.
9
 */
10
class DefaultDataStream extends BaseDataStream
11
{
12
    public $fopenResource;
13
14
    /**
15
     * @param string $dataSource
16
     *
17
     * @throws DataStreamOpenException
18
     */
19
    public function __construct($dataSource, $dataSourceOptions = null)
20
    {
21
        parent::__construct($dataSource, $dataSourceOptions);
22
        try {
23
            $this->fopenResource = fopen($this->dataSource, 'r');
24
        } catch (\Exception $e) {
25
            throw new DataStreamOpenException('Failed to open data source '.json_encode($this->dataSource).': '.json_encode($e->getMessage()));
26
        }
27
    }
28
29
    public function __destruct()
30
    {
31
        fclose($this->fopenResource);
32
    }
33
34
    public function rewind()
35
    {
36
        if ($this->currentLineNumber == 0) {
37
            // starting iterations
38
            $this->currentLineNumber = 1;
39
        } else {
40
            throw new \Exception('DataStream does not support rewinding a stream, sorry');
41
        }
42
    }
43
44
    public function save($filename)
45
    {
46
        $target = fopen($filename, 'w');
47
        stream_copy_to_stream($this->fopenResource, $target);
48
        fclose($target);
49
    }
50
51
    public function current()
52
    {
53
        return fgets($this->fopenResource);
54
    }
55
56
    public function key()
57
    {
58
        return $this->currentLineNumber;
59
    }
60
61
    public function next()
62
    {
63
        ++$this->currentLineNumber;
64
    }
65
66
    public function valid()
67
    {
68
        return !feof($this->fopenResource);
69
    }
70
71
    protected $currentLineNumber = 0;
72
}
73