StreamFactory::createStreamFromFile()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
/**
4
 * High-performance PHP process supervisor and load balancer written in Go
5
 *
6
 * @author Wolfy-J
7
 */
8
declare(strict_types=1);
9
10
namespace Spiral\RoadRunner\Diactoros;
11
12
use RuntimeException;
13
use Psr\Http\Message\StreamFactoryInterface;
14
use Psr\Http\Message\StreamInterface;
15
use Zend\Diactoros\Stream;
16
17
final class StreamFactory implements StreamFactoryInterface
18
{
19
    /**
20
     * @inheritdoc
21
     * @throws RuntimeException
22
     */
23
    public function createStream(string $content = ''): StreamInterface
24
    {
25
        $resource = fopen('php://temp', 'rb+');
26
27
        if (! \is_resource($resource)) {
28
            throw new RuntimeException('Cannot create stream');
29
        }
30
31
        fwrite($resource, $content);
32
        rewind($resource);
33
        return $this->createStreamFromResource($resource);
34
    }
35
36
    /**
37
     * @inheritdoc
38
     */
39
    public function createStreamFromFile(string $file, string $mode = 'rb'): StreamInterface
40
    {
41
        $resource = fopen($file, $mode);
42
43
        if (! \is_resource($resource)) {
44
            throw new RuntimeException('Cannot create stream');
45
        }
46
47
        return $this->createStreamFromResource($resource);
48
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53
    public function createStreamFromResource($resource): StreamInterface
54
    {
55
        return new Stream($resource);
56
    }
57
}
58