Completed
Pull Request — master (#183)
by Luke
07:00 queued 02:56
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.2.1
36
 */
37
function streamize($obj = '')
38
{
39 8
    if ($obj instanceof Streamable) {
40 1
        return $obj;
41
    }
42
43 8
    if ($obj instanceof StreamResource) {
44
        return $obj();
45
    }
46
47 8
    if (is_resource($obj) && get_resource_type($obj) == 'stream') {
48
        return new Stream(new StreamResource($obj));
49
    }
50
51 8
    if ($obj instanceof Iterator) {
52 1
        return new IteratorStream($obj);
53
    }
54
55 7
    if (is_object($obj) && method_exists($obj, '__toString')) {
56 1
        $obj = (string) $obj;
57 1
    }
58 7
    if (is_string($obj)) {
59 5
        $stream = Stream::open('php://temp', 'r+');
60 5
        if ($obj !== '') {
61 3
            $res = $stream->getResource();
62 3
            fwrite($res->getHandle(), $obj);
63 3
            fseek($res->getHandle(), 0);
64 3
        }
65
66 5
        return $stream;
67
    }
68
69 2
    throw new InvalidArgumentException(sprintf(
70 2
        'Invalid argument type for %s: %s',
71 2
        __FUNCTION__,
72 2
        gettype($obj)
73
    ));
74
}