Completed
Push — master ( ae0103...9b98c5 )
by Joao
04:23 queued 56s
created

SocketDataSet::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 9
cp 0
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 6
crap 2
1
<?php
2
/**
3
 * Access a delimited string content from a HTTP server and iterate it.
4
 *
5
 * The string have the format:
6
 * COLUMN1;COLUMN2;COLUMN3|COLUMN1;COLUMN2;COLUMN3|COLUMN1;COLUMN2;COLUMN3
7
 *
8
 * You can customize the field and row separators.
9
 */
10
11
namespace ByJG\AnyDataset\Dataset;
12
13
use ByJG\AnyDataset\Exception\DatasetException;
14
15
class SocketDataSet
16
{
17
18
    private $server = null;
19
    private $colsep = null;
20
    private $rowsep = null;
21
    /**
22
     * @var array
23
     */
24
    private $fields = [];
25
    private $port = null;
26
    private $path = null;
27
28
    /**
29
     * SocketDataSet constructor.
30
     * @param string $server
31
     * @param string $path
32
     * @param string $rowsep
33
     * @param string $colsep
34
     * @param array $fieldnames
35
     * @param int $port
36
     */
37
    public function __construct($server, $path, $rowsep, $colsep, $fieldnames, $port = 80)
38
    {
39
        $this->server = $server;
40
        $this->rowsep = $rowsep;
41
        $this->colsep = $colsep;
42
        $this->fields = $fieldnames;
43
        $this->port = $port;
44
        $this->path = $path;
45
    }
46
47
    /**
48
     * @return GenericIterator
49
     * @throws DatasetException
50
     */
51
    public function getIterator()
52
    {
53
        $errno = null;
54
        $errstr = null;
55
        $handle = fsockopen($this->server, $this->port, $errno, $errstr, 30);
56
        if (!$handle) {
57
            throw new DatasetException("Socket error: $errstr ($errno)");
58
        }
59
60
        $out = "GET " . $this->path . " HTTP/1.1\r\n";
61
        $out .= "Host: " . $this->server . "\r\n";
62
        $out .= "Connection: Close\r\n\r\n";
63
64
        fwrite($handle, $out);
65
66
        $iterator = new SocketIterator($handle, $this->fields, $this->rowsep, $this->colsep);
67
        return $iterator;
68
    }
69
}
70