1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yuloh\Stream; |
4
|
|
|
|
5
|
|
|
abstract class AbstractStreamFactory implements StreamFactoryInterface |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* {@inheritdoc} |
9
|
|
|
*/ |
10
|
26 |
|
public function create($resource = null) |
11
|
|
|
{ |
12
|
26 |
|
switch (gettype($resource)) { |
13
|
26 |
|
case 'NULL': |
14
|
4 |
|
return $this->forNull(); |
15
|
24 |
|
case 'integer': |
16
|
24 |
|
case 'double': |
17
|
24 |
|
case 'string': |
18
|
8 |
|
return $this->forString($resource); |
19
|
16 |
|
case 'object': |
20
|
6 |
|
return $this->forObject($resource); |
21
|
10 |
|
case 'resource': |
22
|
8 |
|
return $this->forResource($resource); |
23
|
2 |
|
default: |
24
|
2 |
|
throw new \InvalidArgumentException( |
25
|
2 |
|
sprintf( |
26
|
2 |
|
'Unable to create stream for type "%s"', |
27
|
2 |
|
gettype($resource) |
28
|
2 |
|
) |
29
|
2 |
|
); |
30
|
2 |
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param resource $resource |
35
|
|
|
* |
36
|
|
|
* @return \Yuloh\Stream\Stream |
37
|
|
|
*/ |
38
|
|
|
abstract protected function forResource($resource); |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param object $object |
42
|
|
|
* |
43
|
|
|
* @return \Yuloh\Stream\Stream |
44
|
|
|
*/ |
45
|
6 |
|
protected function forObject($object) |
46
|
|
|
{ |
47
|
6 |
|
if (method_exists($object, '__toString')) { |
48
|
2 |
|
return $this->forString((string) $object); |
49
|
|
|
} |
50
|
|
|
|
51
|
4 |
|
if ($object instanceof \JsonSerializable) { |
52
|
2 |
|
return $this->forString(json_encode($object)); |
53
|
|
|
} |
54
|
|
|
|
55
|
2 |
|
throw new \InvalidArgumentException(sprintf('Unable to create stream for "%s"', get_class($object))); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param string $string |
60
|
|
|
* |
61
|
|
|
* @return \Yuloh\Stream\Stream |
62
|
|
|
*/ |
63
|
12 |
|
protected function forString($string) |
64
|
|
|
{ |
65
|
12 |
|
$fp = fopen('php://temp', 'r+'); |
66
|
12 |
|
if ($string !== '') { |
67
|
10 |
|
fwrite($fp, $string); |
68
|
10 |
|
rewind($fp); |
69
|
10 |
|
} |
70
|
12 |
|
return $this->forResource($fp); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @return \Yuloh\Stream\Stream |
75
|
|
|
*/ |
76
|
2 |
|
protected function forNull() |
77
|
|
|
{ |
78
|
2 |
|
return $this->forResource(fopen('php://temp', 'r+')); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|