NonClosingStream::close()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
/**
3
 * This file is part of the ZBateson\StreamDecorators project.
4
 *
5
 * @license http://opensource.org/licenses/bsd-license.php BSD
6
 */
7
8
namespace ZBateson\StreamDecorators;
9
10
use GuzzleHttp\Psr7\StreamDecoratorTrait;
11
use Psr\Http\Message\StreamInterface;
12
13
/**
14
 * Doesn't close the underlying stream when 'close' is called on it.  Instead,
15
 * calling close simply removes any reference to the underlying stream.  Note
16
 * that GuzzleHttp\Psr7\Stream calls close in __destruct, so a reference to the
17
 * Stream needs to be kept.  For example:
18
 *
19
 * ```
20
 * $f = fopen('php://temp', 'r+');
21
 * $test = new NonClosingStream(Psr7\Utils::streamFor('test'));
22
 * // work
23
 * $test->close();
24
 * rewind($f);      // error, $f is a closed resource
25
 * ```
26
 *
27
 * Instead, this would work:
28
 *
29
 * ```
30
 * $stream = Psr7\Utils::streamFor(fopen('php://temp', 'r+'));
31
 * $test = new NonClosingStream($stream);
32
 * // work
33
 * $test->close();
34
 * $stream->rewind();  // works
35
 * ```
36
 *
37
 * @author Zaahid Bateson
38
 */
39
class NonClosingStream implements StreamInterface
40
{
41
    use StreamDecoratorTrait;
42
43
    /**
44
     * @var ?StreamInterface $stream
45
     * @phpstan-ignore-next-line
46
     */
47
    private ?StreamInterface $stream;
48
49
    /**
50
     * @inheritDoc
51
     */
52 1
    public function close() : void
53
    {
54 1
        $this->stream = null;	// @phpstan-ignore-line
55
    }
56
57
    /**
58
     * Overridden to detach the underlying stream without closing it.
59
     *
60
     * @inheritDoc
61
     */
62 1
    public function detach()
63
    {
64 1
        $this->stream = null;	// @phpstan-ignore-line
65 1
        return null;
66
    }
67
}
68