StreamFactory::createStreamFromResource()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 3
nc 2
nop 1
1
<?php
2
declare(strict_types=1);
3
namespace Bnf\Typo3HttpFactory;
4
5
use Psr\Http\Message\StreamFactoryInterface;
6
use Psr\Http\Message\StreamInterface;
7
use TYPO3\CMS\Core\Http\Stream;
8
9
final class StreamFactory implements StreamFactoryInterface
10
{
11
    public function createStream(string $content = ''): StreamInterface
12
    {
13
        $stream = new Stream('php://temp', 'r+');
14
        if ($content !== '') {
15
            $stream->write($content);
16
        }
17
        return $stream;
18
    }
19
20
    public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
21
    {
22
        $resource = @fopen($filename, $mode);
23
        if ($resource === false) {
24
            if ($mode === '' || in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], true) === false) {
25
                throw new \InvalidArgumentException('The mode ' . $mode . ' is invalid.', 1566823434);
26
            }
27
28
            throw new \RuntimeException('The file ' . $filename . ' cannot be opened.', 1566823435);
29
        }
30
31
        return new Stream($resource);
32
    }
33
34
    public function createStreamFromResource($resource): StreamInterface
35
    {
36
        if (!is_resource($resource) || get_resource_type($resource) !== 'stream') {
37
            throw new \InvalidArgumentException('Invalid stream provided; must be a stream resource', 1566853697);
38
        }
39
        return new Stream($resource);
40
    }
41
}
42