Passed
Pull Request — master (#183)
by Luke
03:12
created

functions.php ➔ stream_resource()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 10
nop 4
dl 0
loc 23
ccs 15
cts 15
cp 1
crap 5
rs 8.5906
c 0
b 0
f 0
1
<?php
2
/**
3
 * CSVelte: Slender, elegant CSV for PHP
4
 *
5
 * Inspired by Python's CSV module and Frictionless Data and the W3C's CSV
6
 * standardization efforts, CSVelte was written in an effort to take all the
7
 * suck out of working with CSV.
8
 *
9
 * @copyright Copyright (c) 2018 Luke Visinoni
10
 * @author    Luke Visinoni <[email protected]>
11
 * @license   See LICENSE file (MIT license)
12
 */
13
namespace CSVelte;
14
15
use Iterator;
16
use InvalidArgumentException;
17
use CSVelte\Contract\Streamable;
18
use CSVelte\IO\Stream;
19
use CSVelte\IO\StreamResource;
20
use CSVelte\IO\IteratorStream;
21
22
/**
23
 * Stream - streams various types of values and objects.
24
 *
25
 * You can pass a string, or an iterator, or an object with a __toString()
26
 * method to this function and it will find the best possible way to stream the
27
 * data from that object.
28
 *
29
 * @param mixed $obj The item you want to stream
30
 *
31
 * @throws InvalidArgumentException
32
 *
33
 * @return Streamable
34
 *
35
 * @since v0.3
36
 */
37
function to_stream($obj = '')
38
{
39 31
    if ($obj instanceof Streamable) {
40 1
        return $obj;
41
    }
42
43 31
    if ($obj instanceof StreamResource) {
44 1
        return $obj();
45
    }
46
47 30
    if (is_resource($obj) && get_resource_type($obj) == 'stream') {
48 17
        return new Stream(new StreamResource($obj));
49
    }
50
51
    // @todo this is currently how SplFileObject objects are handled; there's gotta be a better way
52 13
    if ($obj instanceof Iterator) {
53 1
        return new IteratorStream($obj);
54
    }
55
56 12
    if (is_object($obj) && method_exists($obj, '__toString')) {
57 1
        $obj = (string) $obj;
58 1
    }
59 12
    if (is_string($obj)) {
60 10
        $stream = Stream::open('php://temp', 'r+');
61 10
        if ($obj !== '') {
62 7
            $res = $stream->getResource();
63 7
            fwrite($res->getHandle(), $obj);
64 7
            fseek($res->getHandle(), 0);
65 7
        }
66
67 10
        return $stream;
68
    }
69
70 2
    throw new InvalidArgumentException(sprintf(
71 2
        'Invalid argument type for %s: %s',
72 2
        __FUNCTION__,
73 2
        gettype($obj)
74
    ));
75
}