Completed
Push — master ( 2da458...7cefcd )
by Tobias
03:02
created

StreamFactory   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 13
lcom 0
cbo 2
dl 0
loc 75
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A createStream() 0 12 4
A createStreamFromFile() 0 6 1
A createStreamFromResource() 0 4 1
C copyToStream() 0 25 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nyholm\Psr7\Factory;
6
7
use Interop\Http\Factory\StreamFactoryInterface;
8
use Nyholm\Psr7\Stream;
9
use Psr\Http\Message\StreamInterface;
10
11
/**
12
 * @author Tobias Nyholm <[email protected]>
13
 */
14
class StreamFactory implements \Http\Message\StreamFactory, StreamFactoryInterface
15
{
16
    /**
17
     * {@inheritdoc}
18
     */
19
    public function createStream($body = null)
20
    {
21
        if ($body instanceof StreamInterface) {
22
            return $body;
23
        }
24
25
        if (gettype($body) === 'resource') {
26
            return Stream::createFromResource($body);
27
        }
28
29
        return Stream::create($body === null ? '' : $body);
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function createStreamFromFile($file, $mode = 'r')
36
    {
37
        $resource = fopen($file, $mode);
38
39
        return Stream::createFromResource($resource);
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function createStreamFromResource($resource)
46
    {
47
        return Stream::createFromResource($resource);
48
    }
49
50
    /**
51
     * Copy the contents of a stream into another stream until the given number
52
     * of bytes have been read.
53
     *
54
     * @author Michael Dowling and contributors to guzzlehttp/psr7
55
     *
56
     * @param StreamInterface $source Stream to read from
57
     * @param StreamInterface $dest   Stream to write to
58
     * @param int             $maxLen Maximum number of bytes to read. Pass -1
59
     *                                to read the entire stream
60
     *
61
     * @throws \RuntimeException on error
62
     */
63
    public function copyToStream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)
64
    {
65
        if ($maxLen === -1) {
66
            while (!$source->eof()) {
67
                if (!$dest->write($source->read(1048576))) {
68
                    break;
69
                }
70
            }
71
72
            return;
73
        }
74
75
        $bytes = 0;
76
        while (!$source->eof()) {
77
            $buf = $source->read($maxLen - $bytes);
78
            if (!($len = strlen($buf))) {
79
                break;
80
            }
81
            $bytes += $len;
82
            $dest->write($buf);
83
            if ($bytes == $maxLen) {
84
                break;
85
            }
86
        }
87
    }
88
}
89