Completed
Pull Request — master (#183)
by Luke
07:00 queued 02:56
created

functions.php ➔ streamize()   B

Complexity

Conditions 10
Paths 10

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 10.0578

Importance

Changes 0
Metric Value
cc 10
nc 10
nop 1
dl 0
loc 38
ccs 22
cts 24
cp 0.9167
crap 10.0578
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
}