|
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
|
30 |
|
if ($obj instanceof Streamable) { |
|
40
|
1 |
|
return $obj; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
30 |
|
if ($obj instanceof StreamResource) { |
|
44
|
1 |
|
return $obj(); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
29 |
|
if (is_resource($obj) && get_resource_type($obj) == 'stream') { |
|
48
|
18 |
|
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
|
11 |
|
if ($obj instanceof Iterator) { |
|
53
|
1 |
|
return new IteratorStream($obj); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
10 |
|
if (is_object($obj) && method_exists($obj, '__toString')) { |
|
57
|
1 |
|
$obj = (string) $obj; |
|
58
|
1 |
|
} |
|
59
|
10 |
|
if (is_string($obj)) { |
|
60
|
8 |
|
$stream = Stream::open('php://temp', 'r+'); |
|
61
|
8 |
|
if ($obj !== '') { |
|
62
|
5 |
|
$res = $stream->getResource(); |
|
63
|
5 |
|
fwrite($res->getHandle(), $obj); |
|
64
|
5 |
|
fseek($res->getHandle(), 0); |
|
65
|
5 |
|
} |
|
66
|
|
|
|
|
67
|
8 |
|
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
|
|
|
} |