1 | <?php |
||
2 | /* |
||
3 | * This file is part of the Shieldon package. |
||
4 | * |
||
5 | * (c) Terry L. <[email protected]> |
||
6 | * |
||
7 | * For the full copyright and license information, please view the LICENSE |
||
8 | * file that was distributed with this source code. |
||
9 | */ |
||
10 | |||
11 | declare(strict_types=1); |
||
12 | |||
13 | namespace Shieldon\Psr17; |
||
14 | |||
15 | use Psr\Http\Message\StreamInterface; |
||
16 | use Psr\Http\Message\StreamFactoryInterface; |
||
17 | use Shieldon\Psr7\Stream; |
||
18 | use InvalidArgumentException; |
||
19 | use RuntimeException; |
||
20 | |||
21 | use function fopen; |
||
22 | use function fwrite; |
||
23 | use function is_resource; |
||
24 | use function preg_match; |
||
25 | use function rewind; |
||
26 | |||
27 | /** |
||
28 | * PSR-17 Stream Factory |
||
29 | */ |
||
30 | class StreamFactory implements StreamFactoryInterface |
||
31 | { |
||
32 | /** |
||
33 | * {@inheritdoc} |
||
34 | */ |
||
35 | public function createStream(string $content = ''): StreamInterface |
||
36 | { |
||
37 | $resource = @fopen('php://temp', 'r+'); |
||
38 | |||
39 | if (! is_resource($resource)) { |
||
40 | throw new RuntimeException( |
||
41 | 'Unable to open "php://temp" resource.' |
||
42 | ); |
||
43 | } |
||
44 | |||
45 | fwrite($resource, $content); |
||
46 | rewind($resource); |
||
47 | |||
48 | return $this->createStreamFromResource($resource); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * {@inheritdoc} |
||
53 | */ |
||
54 | public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface |
||
55 | { |
||
56 | if ($mode === '' || ! preg_match('/^[rwaxce]{1}[bt]{0,1}[+]{0,1}+$/', $mode)) { |
||
57 | throw new InvalidArgumentException( |
||
58 | sprintf( |
||
59 | 'Invalid file opening mode "%s"', |
||
60 | $mode |
||
61 | ) |
||
62 | ); |
||
63 | } |
||
64 | |||
65 | $resource = @fopen($filename, $mode); |
||
66 | |||
67 | if (! is_resource($resource)) { |
||
68 | throw new RuntimeException( |
||
69 | sprintf( |
||
70 | 'Unable to open file at "%s"', |
||
71 | $filename |
||
72 | ) |
||
73 | ); |
||
74 | } |
||
75 | |||
76 | return new Stream($resource); |
||
77 | } |
||
78 | |||
79 | /** |
||
80 | * {@inheritdoc} |
||
81 | */ |
||
82 | public function createStreamFromResource($resource): StreamInterface |
||
83 | { |
||
84 | if (! is_resource($resource)) { |
||
85 | $resource = fopen('php://temp', 'r+'); |
||
86 | } |
||
87 | |||
88 | return new Stream($resource); |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
89 | } |
||
90 | } |
||
91 |