StreamFactory::createStreamFromFile()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 9
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1
<?php
2
namespace DevOp\Core\Http;
3
4
use DevOp\Core\Http\Stream;
5
use Psr\Http\Message\StreamInterface;
6
use Psr\Http\Message\StreamFactoryInterface;
7
8
class StreamFactory implements StreamFactoryInterface
9
{
10
11
    /**
12
     * @param string $content
13
     * @return StreamInterface
14
     */
15 32
    public function createStream(string $content = ''): StreamInterface
16
    {
17 32
        $resource = fopen("php://temp", "w+b");
18
19 32
        if (!is_resource($resource)) {
20
            throw new \InvalidArgumentException('Error while creating PHP stream');
21
        }
22
23 32
        fwrite($resource, $content);
24 32
        rewind($resource);
25
26 32
        return $this->createStreamFromResource($resource);
27
    }
28
29
    /**
30
     * @param string $filename
31
     * @param string $mode
32
     * @return StreamInterface
33
     */
34 4
    public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
35
    {
36 4
        $resource = fopen($filename, $mode);
37
38 4
        if (!is_resource($resource)) {
39
            throw new \InvalidArgumentException('Error while creating PHP stream');
40
        }
41
42 4
        return $this->createStreamFromResource($resource);
43
    }
44
45
    /**
46
     * @param resource $resource
47
     * @return StreamInterface
48
     */
49 36
    public function createStreamFromResource($resource): StreamInterface
50
    {
51 36
        return new Stream($resource);
52
    }
53
}
54