1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace DMT\Aura\Psr\Factory; |
4
|
|
|
|
5
|
|
|
use DMT\Aura\Psr\Message\Stream; |
6
|
|
|
use InvalidArgumentException; |
7
|
|
|
use Psr\Http\Message\StreamFactoryInterface; |
8
|
|
|
use Psr\Http\Message\StreamInterface; |
9
|
|
|
use RuntimeException; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class StreamFactory |
13
|
|
|
* |
14
|
|
|
* @package DMT\Aura\Psr\Factory |
15
|
|
|
*/ |
16
|
|
|
class StreamFactory implements StreamFactoryInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Create a new stream from a string. |
20
|
|
|
* |
21
|
|
|
* The stream SHOULD be created with a temporary resource. |
22
|
|
|
* |
23
|
|
|
* @param string $content String content with which to populate the stream. |
24
|
|
|
* |
25
|
|
|
* @return StreamInterface |
26
|
|
|
*/ |
27
|
57 |
|
public function createStream(string $content = ''): StreamInterface |
28
|
|
|
{ |
29
|
57 |
|
return new Stream($content); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Create a stream from an existing file. |
34
|
|
|
* |
35
|
|
|
* The file MUST be opened using the given mode, which may be any mode |
36
|
|
|
* supported by the `fopen` function. |
37
|
|
|
* |
38
|
|
|
* The `$filename` MAY be any string supported by `fopen()`. |
39
|
|
|
* |
40
|
|
|
* @param string $filename Filename or stream URI to use as basis of stream. |
41
|
|
|
* @param string $mode Mode with which to open the underlying filename/stream. |
42
|
|
|
* |
43
|
|
|
* @return StreamInterface |
44
|
|
|
* @throws RuntimeException If the file cannot be opened. |
45
|
|
|
* @throws InvalidArgumentException If the mode is invalid. |
46
|
|
|
*/ |
47
|
6 |
|
public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface |
48
|
|
|
{ |
49
|
6 |
|
if (!preg_match(Stream::MODE_READABLE, $mode) && !preg_match(Stream::MODE_WRITEABLE, $mode)) { |
50
|
1 |
|
throw new InvalidArgumentException('invalid mode'); |
51
|
|
|
} |
52
|
|
|
|
53
|
5 |
|
if (!$resource = @fopen($filename, $mode)) { |
54
|
1 |
|
throw new RuntimeException('file cannot be opened'); |
55
|
|
|
} |
56
|
|
|
|
57
|
4 |
|
return new Stream($resource); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Create a new stream from an existing resource. |
62
|
|
|
* |
63
|
|
|
* The stream MUST be readable and may be writable. |
64
|
|
|
* |
65
|
|
|
* @param resource $resource PHP resource to use as basis of stream. |
66
|
|
|
* |
67
|
|
|
* @return StreamInterface |
68
|
|
|
*/ |
69
|
20 |
|
public function createStreamFromResource($resource): StreamInterface |
70
|
|
|
{ |
71
|
20 |
|
return new Stream($resource); |
72
|
|
|
} |
73
|
|
|
} |