|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Nyholm\Psr7\Factory; |
|
6
|
|
|
|
|
7
|
|
|
use Interop\Http\Factory\StreamFactoryInterface; |
|
8
|
|
|
use Nyholm\Psr7\Stream; |
|
9
|
|
|
use Psr\Http\Message\StreamInterface; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @author Tobias Nyholm <[email protected]> |
|
13
|
|
|
*/ |
|
14
|
|
|
class StreamFactory implements \Http\Message\StreamFactory, StreamFactoryInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* {@inheritdoc} |
|
18
|
|
|
*/ |
|
19
|
|
|
public function createStream($body = null) |
|
20
|
|
|
{ |
|
21
|
|
|
if ($body instanceof StreamInterface) { |
|
22
|
|
|
return $body; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
if (gettype($body) === 'resource') { |
|
26
|
|
|
return Stream::createFromResource($body); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
return Stream::create($body === null ? '' : $body); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* {@inheritdoc} |
|
34
|
|
|
*/ |
|
35
|
|
|
public function createStreamFromFile($file, $mode = 'r') |
|
36
|
|
|
{ |
|
37
|
|
|
$resource = fopen($file, $mode); |
|
38
|
|
|
|
|
39
|
|
|
return Stream::createFromResource($resource); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* {@inheritdoc} |
|
44
|
|
|
*/ |
|
45
|
|
|
public function createStreamFromResource($resource) |
|
46
|
|
|
{ |
|
47
|
|
|
return Stream::createFromResource($resource); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Copy the contents of a stream into another stream until the given number |
|
52
|
|
|
* of bytes have been read. |
|
53
|
|
|
* |
|
54
|
|
|
* @author Michael Dowling and contributors to guzzlehttp/psr7 |
|
55
|
|
|
* |
|
56
|
|
|
* @param StreamInterface $source Stream to read from |
|
57
|
|
|
* @param StreamInterface $dest Stream to write to |
|
58
|
|
|
* @param int $maxLen Maximum number of bytes to read. Pass -1 |
|
59
|
|
|
* to read the entire stream |
|
60
|
|
|
* |
|
61
|
|
|
* @throws \RuntimeException on error |
|
62
|
|
|
*/ |
|
63
|
|
|
public function copyToStream(StreamInterface $source, StreamInterface $dest, $maxLen = -1) |
|
64
|
|
|
{ |
|
65
|
|
|
if ($maxLen === -1) { |
|
66
|
|
|
while (!$source->eof()) { |
|
67
|
|
|
if (!$dest->write($source->read(1048576))) { |
|
68
|
|
|
break; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
$bytes = 0; |
|
76
|
|
|
while (!$source->eof()) { |
|
77
|
|
|
$buf = $source->read($maxLen - $bytes); |
|
78
|
|
|
if (!($len = strlen($buf))) { |
|
79
|
|
|
break; |
|
80
|
|
|
} |
|
81
|
|
|
$bytes += $len; |
|
82
|
|
|
$dest->write($buf); |
|
83
|
|
|
if ($bytes == $maxLen) { |
|
84
|
|
|
break; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|